Decompiled source of Deliter v1.1.4
patchers/Deliter.dll
Decompiled 6 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using BepInEx; using BepInEx.Logging; using Ionic.Zip; using Microsoft.CodeAnalysis; using Mono.Cecil; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using YamlDotNet.Core; using YamlDotNet.RepresentationModel; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("Deliter")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Deliter")] [assembly: AssemblyTitle("Deliter")] [assembly: AssemblyVersion("1.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [DebuggerNonUserCode] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [DebuggerNonUserCode] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [DebuggerNonUserCode] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [DebuggerNonUserCode] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [DebuggerNonUserCode] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] [DebuggerNonUserCode] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace Deliter { internal class Config { public HashSet<string> Ignore { get; set; } public Dictionary<string, Plugin> Plugins { get; set; } } internal class Converter { private const string ManifestJson = "manifest.json"; private readonly Config _config; private readonly ManualLogSource _logger; private readonly YamlStream _masonConfig; private static void Add(YamlNode existing, YamlNode additive) { YamlMappingNode val = (YamlMappingNode)(object)((existing is YamlMappingNode) ? existing : null); if (val == null) { YamlSequenceNode val2 = (YamlSequenceNode)(object)((existing is YamlSequenceNode) ? existing : null); if (val2 == null) { YamlScalarNode val3 = (YamlScalarNode)(object)((existing is YamlScalarNode) ? existing : null); if (val3 == null) { throw new ArgumentException("Unknown type", "existing"); } YamlScalarNode val4 = (YamlScalarNode)(object)((additive is YamlScalarNode) ? additive : null); if (val4 != null) { val3.Value = val4.Value; } else { Mismatch(); } } else { YamlSequenceNode val5 = (YamlSequenceNode)(object)((additive is YamlSequenceNode) ? additive : null); if (val5 != null) { Add(val2, val5); } else { Mismatch(); } } } else { YamlMappingNode val6 = (YamlMappingNode)(object)((additive is YamlMappingNode) ? additive : null); if (val6 != null) { Add(val, val6); } else { Mismatch(); } } static void Mismatch() { throw new ArgumentException("Existing and additive are not the same type"); } } private static void Add(YamlSequenceNode existing, YamlSequenceNode additive) { foreach (YamlNode item in additive) { existing.Add(item); } } private static void Add(YamlMappingNode existing, YamlMappingNode additive) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown foreach (KeyValuePair<YamlNode, YamlNode> item in additive) { YamlScalarNode key = (YamlScalarNode)item.Key; YamlNode value = item.Value; YamlNode value2 = ((IEnumerable<KeyValuePair<YamlNode, YamlNode>>)existing).FirstOrDefault(delegate(KeyValuePair<YamlNode, YamlNode> x) { YamlNode key2 = x.Key; YamlScalarNode val = (YamlScalarNode)(object)((key2 is YamlScalarNode) ? key2 : null); return val != null && val.Value == key.Value; }).Value; if (value2 != null) { Add(value2, value); } else { existing.Add((YamlNode)(object)key, value); } } } private static JsonSerializationException NewException(JToken token, string message) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown return new JsonSerializationException(message, token.Path, ((IJsonLineInfo)token).LineNumber, ((IJsonLineInfo)token).LinePosition, (Exception)null); } private static JObject ReadManifest(ZipEntry entry) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown using Stream stream = entry.OpenReader(); using StreamReader streamReader = new StreamReader(stream); JsonTextReader val = new JsonTextReader((TextReader)streamReader); try { return JObject.Load((JsonReader)(object)val); } finally { ((IDisposable)val)?.Dispose(); } } private static void CreateAllDirectories(string path) { string directoryName = Path.GetDirectoryName(path); if (directoryName != null && !Directory.Exists(directoryName)) { CreateAllDirectories(directoryName); } Directory.CreateDirectory(path); } private void ExtractResources(string resources, ZipFile zip) { Directory.CreateDirectory(resources); try { foreach (ZipEntry entry2 in zip.Entries) { ZipEntry entry = entry2; string fileName = entry.FileName; string path = Path.Combine(resources, fileName); if (entry.IsDirectory) { CreateAllDirectories(path); continue; } if (Path.GetFileName(fileName) == "manifest.json") { if (!string.IsNullOrEmpty(Path.GetDirectoryName(fileName)?.Trim())) { LogWarning($"Ignoring non-Deli manifest from '{zip}' to avoid Deli crashing: '{fileName}'"); } continue; } if (File.Exists(path)) { if (File.GetLastWriteTime(path) < entry.LastModified) { ExtractFile(); } continue; } string directoryName = Path.GetDirectoryName(path); if (directoryName != null) { CreateAllDirectories(directoryName); } ExtractFile(); void ExtractFile() { using FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); entry.Extract((Stream)fileStream); } } } catch (Exception innerException) { throw new IOException("Failed to extract all resources", innerException); } } public Converter(ManualLogSource logger, Config config) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_0048: Expected O, but got Unknown //IL_004d: Expected O, but got Unknown //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown YamlDocument[] array = new YamlDocument[1]; YamlMappingNode val = new YamlMappingNode(); YamlMappingNode val2 = new YamlMappingNode(); val2.Add("bepinex", (YamlNode)new YamlScalarNode(Paths.BepInExRootPath)); val2.Add("managed", (YamlNode)new YamlScalarNode(Paths.ManagedPath)); val.Add("directories", (YamlNode)val2); array[0] = new YamlDocument((YamlNode)val); _masonConfig = new YamlStream((YamlDocument[])(object)array); base..ctor(); _logger = logger; _config = config; } private YamlNode? ConvertAsset(JProperty asset) { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Expected O, but got Unknown //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Expected O, but got Unknown //IL_010d: Expected O, but got Unknown if (asset != null) { string name = asset.Name; if (name != null) { JToken value = asset.Value; JValue val = (JValue)(object)((value is JValue) ? value : null); if (val != null && val.Value is string text) { string[] array = text.Split(new char[1] { ':' }); if (array.Length != 2) { throw NewException((JToken)(object)asset, "Loaders must be a mod GUID and loader name, separated by a single colon"); } if (array[0] == "deli" && array[1] == "assembly") { return null; } string key = array[0]; if (!_config.Plugins.TryGetValue(key, out Plugin value2)) { return null; } string key2 = array[1]; if (!value2.Loaders.TryGetValue(key2, out string value3)) { return null; } ((JToken)asset).Remove(); YamlMappingNode val2 = new YamlMappingNode(); val2.Add("path", (YamlNode)new YamlScalarNode(name) { Style = (ScalarStyle)3 }); val2.Add("plugin", (YamlNode)new YamlScalarNode(value2.GUID) { Style = (ScalarStyle)1 }); val2.Add("loader", (YamlNode)new YamlScalarNode(value3) { Style = (ScalarStyle)1 }); return (YamlNode?)val2; } } } throw NewException((JToken)(object)asset, "Invalid asset"); } private YamlMappingNode GetDependencies(JObject dependencies) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_0092: Expected O, but got Unknown YamlMappingNode val = new YamlMappingNode(); foreach (JProperty item in dependencies.Properties().ToList()) { if (item != null) { string name = item.Name; if (name != null) { JToken value = item.Value; JValue val2 = (JValue)(object)((value is JValue) ? value : null); if (val2 != null && val2.Value is string) { if (_config.Plugins.TryGetValue(name, out Plugin value2)) { ((JToken)item).Remove(); val.Add((YamlNode)new YamlScalarNode(value2.GUID), (YamlNode)new YamlScalarNode(value2.Version)); } continue; } } } throw NewException((JToken)(object)item, "Invalid dependency"); } YamlMappingNode val3 = new YamlMappingNode(); val3.Add("hard", (YamlNode)(object)val); return val3; } private YamlMappingNode GetAssets(JObject assets) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Expected O, but got Unknown //IL_00ec: Expected O, but got Unknown YamlMappingNode val = new YamlMappingNode(); JToken obj = assets["patcher"]; JObject val2 = (JObject)(object)((obj is JObject) ? obj : null); if (val2 != null && ((JToken)val2).HasValues) { throw NewException((JToken)(object)val2, "Mod contained patcher assets. Patcher assets are not supported in Stratum."); } JToken obj2 = assets["setup"]; JObject val3 = (JObject)(object)((obj2 is JObject) ? obj2 : null); if (val3 != null) { val.Add("setup", (YamlNode)new YamlSequenceNode(val3.Properties().ToList().Select(ConvertAsset) .WhereNotNull())); } JToken obj3 = assets["runtime"]; JObject val4 = (JObject)(object)((obj3 is JObject) ? obj3 : null); if (val4 != null) { YamlMappingNode val5 = new YamlMappingNode(); val5.Add("nested", (YamlNode)new YamlSequenceNode(val4.Properties().ToList().Select(ConvertAsset) .WhereNotNull() .Select(delegate(YamlNode asset) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_001d: Expected O, but got Unknown YamlMappingNode val6 = new YamlMappingNode(); YamlSequenceNode val7 = new YamlSequenceNode(); val7.Add(asset); val6.Add("assets", (YamlNode)val7); return (YamlNode)val6; }))); val.Add("runtime", (YamlNode)val5); } return val; } private YamlDocument GetDocument(JObject manifest, out bool partial) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Expected O, but got Unknown partial = false; YamlMappingNode val = new YamlMappingNode(); val.Add("version", "1"); YamlMappingNode val2 = val; JToken obj = manifest["dependencies"]; JObject val3 = (JObject)(object)((obj is JObject) ? obj : null); if (val3 != null) { val2.Add("dependencies", (YamlNode)(object)GetDependencies(val3)); partial = partial || ((JContainer)val3).Count != 0; } JToken obj2 = manifest["assets"]; JObject val4 = (JObject)(object)((obj2 is JObject) ? obj2 : null); if (val4 != null) { val2.Add("assets", (YamlNode)(object)GetAssets(val4)); partial = partial || ((JContainer)val4).Count != 0; } return new YamlDocument((YamlNode)(object)val2); } private void WriteProject(string path, JObject manifest, out bool partial) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown YamlStream val = new YamlStream(); if (File.Exists(path)) { using StreamReader streamReader = new StreamReader(path); val.Load((TextReader)streamReader); } YamlDocument document = GetDocument(manifest, out partial); YamlDocument val2 = val.Documents.FirstOrDefault(); if (val2 != null) { Add(val2.RootNode, document.RootNode); } else { val.Add(document); } using StreamWriter streamWriter = new StreamWriter(path, append: false, Utility.UTF8NoBom); val.Save((TextWriter)streamWriter, false); } private void WriteConfig(string directory) { using StreamWriter streamWriter = new StreamWriter(Path.Combine(directory, "config.yaml"), append: false, Utility.UTF8NoBom); _masonConfig.Save((TextWriter)streamWriter, false); } private void Convert(string path, string name) { //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Expected O, but got Unknown string directoryName = Path.GetDirectoryName(path); string text = path + ".bak"; string text2 = path + ".partial.bak"; string text3 = Path.Combine(directoryName, "project.yaml"); string text4 = text3 + ".bak"; string resources = Path.Combine(directoryName, "resources"); if (File.Exists(text2)) { return; } if (File.Exists(path) && File.Exists(text)) { File.Delete(Path.Combine(directoryName, "bootstrap.dll")); File.Delete(text3); File.Delete(text4); File.Copy(text, path, overwrite: true); File.Delete(text); Directory.Delete(Path.Combine(directoryName, "resources"), recursive: true); } ZipFile val = ZipFile.Read(path); bool partial; try { ZipEntry val2 = val["manifest.json"]; if (val2 == null) { throw new InvalidOperationException("Mod contained no manifest.json"); } JObject val3 = ReadManifest(val2); if (File.Exists(text3)) { File.Copy(text3, text4, overwrite: true); File.Delete(text3); } WriteProject(text3, val3, out partial); WriteConfig(directoryName); ExtractResources(resources, val); if (partial) { string fileName = val2.FileName; val.RemoveEntry(val2); byte[] array; using (MemoryStream memoryStream = new MemoryStream()) { using (StreamWriter streamWriter = new StreamWriter(memoryStream)) { JsonTextWriter val4 = new JsonTextWriter((TextWriter)streamWriter); try { ((JToken)val3).WriteTo((JsonWriter)(object)val4, (JsonConverter[])(object)new JsonConverter[0]); } finally { ((IDisposable)val4)?.Dispose(); } } array = memoryStream.ToArray(); } val.AddEntry(fileName, array); val.Save(); } } finally { ((IDisposable)val)?.Dispose(); } if (!File.Exists(text)) { if (partial) { File.Copy(path, text2, overwrite: true); } else { File.Copy(path, text, overwrite: true); File.Delete(path); } } LogInfo("Converted '" + name + "' to a Mason project"); } public void PreCompile(string directory) { //IL_00b1: Expected O, but got Unknown if (!File.Exists(Path.Combine(directory, "manifest.json"))) { return; } string fileName = Path.GetFileName(directory); string[] array = fileName.Split(new char[1] { '-' }); if (array.Length == 2 && _config.Ignore.Contains(array[1])) { LogDebug("Ignoring '" + fileName + "' because it is in the ignore filter"); return; } using IEnumerator<string> enumerator = ((IEnumerable<string>)Directory.GetFiles(directory, "*.deli", SearchOption.AllDirectories)).GetEnumerator(); if (!enumerator.MoveNext()) { return; } string current = enumerator.Current; if (enumerator.MoveNext()) { LogWarning("'" + fileName + "' contained multiple .deli files. Skipping"); return; } try { Convert(current, fileName); } catch (JsonSerializationException val) { JsonSerializationException val2 = val; LogError($"At ({val2.LineNumber}, {val2.LinePosition}) ({val2.Path}), {val2}"); } catch (Exception arg) { LogError($"'{fileName}' has an error in its format:\n{arg}"); } } private void LogInfo(object obj) { lock (_logger) { _logger.LogInfo(obj); } } private void LogWarning(object obj) { lock (_logger) { _logger.LogWarning(obj); } } private void LogError(object obj) { lock (_logger) { _logger.LogError(obj); } } private void LogDebug(object obj) { lock (_logger) { _logger.LogDebug(obj); } } } public static class Entrypoint { private static readonly ManualLogSource Logger = Logger.CreateLogSource("Deliter"); public static IEnumerable<string> TargetDLLs => Enumerable.Empty<string>(); private static Config ReadConfig() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown using StreamReader streamReader = new StreamReader(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.yaml")); return ((BuilderSkeleton<DeserializerBuilder>)new DeserializerBuilder()).WithNamingConvention(UnderscoredNamingConvention.Instance).Build().Deserialize<Config>((TextReader)streamReader); } public static void Patch(AssemblyDefinition asm) { Logger.LogWarning((object)("No DLLs should be patched, but the patch method was called. Assembly: " + (object)asm)); } public static void Initialize() { Converter converter = new Converter(Logger, ReadConfig()); string[] directories = Directory.GetDirectories(Paths.PluginPath); bool[] completions = new bool[directories.Length]; for (int i = 0; i < directories.Length; i++) { string directory = directories[i]; int iCopy = i; ThreadPool.QueueUserWorkItem(delegate { try { converter.PreCompile(directory); completions[iCopy] = true; } catch (Exception arg) { Logger.LogError((object)$"Failed to run precompile method on threadpool:\n{arg}"); } }); } while (true) { Thread.Sleep(10); bool[] array = completions; int num = 0; while (true) { if (num < array.Length) { if (!array[num]) { break; } num++; continue; } return; } } } } internal static class Extensions { public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> @this) where T : class { return @this.Where((T x) => x != null); } } internal class Plugin { [YamlMember(Alias = "guid")] public string GUID { get; set; } public string Version { get; set; } public Dictionary<string, string> Loaders { get; set; } } }
patchers/DotNetZip.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Ionic.BZip2; using Ionic.Crc; using Ionic.Zip; using Ionic.Zlib; using Microsoft.CSharp; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Ionic's Zip Library")] [assembly: AssemblyConfiguration("Retail")] [assembly: AssemblyDescription("a library for handling zip archives. http://www.codeplex.com/DotNetZip (Flavor=Retail)")] [assembly: ComVisible(true)] [assembly: Guid("dfd2b1f6-e3be-43d1-9b43-11aae1e901d8")] [assembly: CLSCompliant(true)] [assembly: AssemblyFileVersion("1.12.0")] [assembly: AssemblyInformationalVersion("1.12.0.ace992")] [assembly: AssemblyVersion("1.12.0.0")] namespace Ionic { internal enum LogicalConjunction { NONE, AND, OR, XOR } internal enum WhichTime { atime, mtime, ctime } internal enum ComparisonOperator { [Description(">")] GreaterThan, [Description(">=")] GreaterThanOrEqualTo, [Description("<")] LesserThan, [Description("<=")] LesserThanOrEqualTo, [Description("=")] EqualTo, [Description("!=")] NotEqualTo } internal abstract class SelectionCriterion { internal virtual bool Verbose { get; set; } internal abstract bool Evaluate(string filename); [Conditional("SelectorTrace")] protected static void CriterionTrace(string format, params object[] args) { } internal abstract bool Evaluate(ZipEntry entry); } internal class SizeCriterion : SelectionCriterion { internal ComparisonOperator Operator; internal long Size; public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("size ").Append(EnumUtil.GetDescription(Operator)).Append(" ") .Append(Size.ToString()); return stringBuilder.ToString(); } internal override bool Evaluate(string filename) { FileInfo fileInfo = new FileInfo(filename); return _Evaluate(fileInfo.Length); } private bool _Evaluate(long Length) { bool flag = false; return Operator switch { ComparisonOperator.GreaterThanOrEqualTo => Length >= Size, ComparisonOperator.GreaterThan => Length > Size, ComparisonOperator.LesserThanOrEqualTo => Length <= Size, ComparisonOperator.LesserThan => Length < Size, ComparisonOperator.EqualTo => Length == Size, ComparisonOperator.NotEqualTo => Length != Size, _ => throw new ArgumentException("Operator"), }; } internal override bool Evaluate(ZipEntry entry) { return _Evaluate(entry.UncompressedSize); } } internal class TimeCriterion : SelectionCriterion { internal ComparisonOperator Operator; internal WhichTime Which; internal DateTime Time; public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(Which.ToString()).Append(" ").Append(EnumUtil.GetDescription(Operator)) .Append(" ") .Append(Time.ToString("yyyy-MM-dd-HH:mm:ss")); return stringBuilder.ToString(); } internal override bool Evaluate(string filename) { return _Evaluate(Which switch { WhichTime.atime => File.GetLastAccessTime(filename).ToUniversalTime(), WhichTime.mtime => File.GetLastWriteTime(filename).ToUniversalTime(), WhichTime.ctime => File.GetCreationTime(filename).ToUniversalTime(), _ => throw new ArgumentException("Operator"), }); } private bool _Evaluate(DateTime x) { bool flag = false; return Operator switch { ComparisonOperator.GreaterThanOrEqualTo => x >= Time, ComparisonOperator.GreaterThan => x > Time, ComparisonOperator.LesserThanOrEqualTo => x <= Time, ComparisonOperator.LesserThan => x < Time, ComparisonOperator.EqualTo => x == Time, ComparisonOperator.NotEqualTo => x != Time, _ => throw new ArgumentException("Operator"), }; } internal override bool Evaluate(ZipEntry entry) { return _Evaluate(Which switch { WhichTime.atime => entry.AccessedTime, WhichTime.mtime => entry.ModifiedTime, WhichTime.ctime => entry.CreationTime, _ => throw new ArgumentException("??time"), }); } } internal class NameCriterion : SelectionCriterion { private Regex _re; private string _regexString; internal ComparisonOperator Operator; private string _MatchingFileSpec; internal virtual string MatchingFileSpec { set { if (Directory.Exists(value)) { string[] obj = new string[5] { ".", null, null, null, null }; char directorySeparatorChar = Path.DirectorySeparatorChar; obj[1] = directorySeparatorChar.ToString(); obj[2] = value; directorySeparatorChar = Path.DirectorySeparatorChar; obj[3] = directorySeparatorChar.ToString(); obj[4] = "*.*"; _MatchingFileSpec = string.Concat(obj); } else { _MatchingFileSpec = value; } _regexString = "^" + Regex.Escape(_MatchingFileSpec).Replace("\\\\\\*\\.\\*", "\\\\([^\\.]+|.*\\.[^\\\\\\.]*)").Replace("\\.\\*", "\\.[^\\\\\\.]*") .Replace("\\*", ".*") .Replace("\\?", "[^\\\\\\.]") + "$"; _re = new Regex(_regexString, RegexOptions.IgnoreCase); } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("name ").Append(EnumUtil.GetDescription(Operator)).Append(" '") .Append(_MatchingFileSpec) .Append("'"); return stringBuilder.ToString(); } internal override bool Evaluate(string filename) { return _Evaluate(filename); } private bool _Evaluate(string fullpath) { string input = ((_MatchingFileSpec.IndexOf(Path.DirectorySeparatorChar) == -1) ? Path.GetFileName(fullpath) : fullpath); bool flag = _re.IsMatch(input); if (Operator != ComparisonOperator.EqualTo) { flag = !flag; } return flag; } internal override bool Evaluate(ZipEntry entry) { string fullpath = entry.FileName.Replace((Path.DirectorySeparatorChar == '/') ? '\\' : '/', Path.DirectorySeparatorChar); return _Evaluate(fullpath); } } internal class TypeCriterion : SelectionCriterion { private char ObjectType; internal ComparisonOperator Operator; internal string AttributeString { get { return ObjectType.ToString(); } set { if (value.Length != 1 || (value[0] != 'D' && value[0] != 'F')) { throw new ArgumentException("Specify a single character: either D or F"); } ObjectType = value[0]; } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("type ").Append(EnumUtil.GetDescription(Operator)).Append(" ") .Append(AttributeString); return stringBuilder.ToString(); } internal override bool Evaluate(string filename) { bool flag = ((ObjectType == 'D') ? Directory.Exists(filename) : File.Exists(filename)); if (Operator != ComparisonOperator.EqualTo) { flag = !flag; } return flag; } internal override bool Evaluate(ZipEntry entry) { bool flag = ((ObjectType == 'D') ? entry.IsDirectory : (!entry.IsDirectory)); if (Operator != ComparisonOperator.EqualTo) { flag = !flag; } return flag; } } internal class AttributesCriterion : SelectionCriterion { private FileAttributes _Attributes; internal ComparisonOperator Operator; internal string AttributeString { get { string text = ""; if ((_Attributes & FileAttributes.Hidden) != 0) { text += "H"; } if ((_Attributes & FileAttributes.System) != 0) { text += "S"; } if ((_Attributes & FileAttributes.ReadOnly) != 0) { text += "R"; } if ((_Attributes & FileAttributes.Archive) != 0) { text += "A"; } if ((_Attributes & FileAttributes.ReparsePoint) != 0) { text += "L"; } if ((_Attributes & FileAttributes.NotContentIndexed) != 0) { text += "I"; } return text; } set { _Attributes = FileAttributes.Normal; string text = value.ToUpper(); foreach (char c in text) { switch (c) { case 'H': if ((_Attributes & FileAttributes.Hidden) != 0) { throw new ArgumentException($"Repeated flag. ({c})", "value"); } _Attributes |= FileAttributes.Hidden; break; case 'R': if ((_Attributes & FileAttributes.ReadOnly) != 0) { throw new ArgumentException($"Repeated flag. ({c})", "value"); } _Attributes |= FileAttributes.ReadOnly; break; case 'S': if ((_Attributes & FileAttributes.System) != 0) { throw new ArgumentException($"Repeated flag. ({c})", "value"); } _Attributes |= FileAttributes.System; break; case 'A': if ((_Attributes & FileAttributes.Archive) != 0) { throw new ArgumentException($"Repeated flag. ({c})", "value"); } _Attributes |= FileAttributes.Archive; break; case 'I': if ((_Attributes & FileAttributes.NotContentIndexed) != 0) { throw new ArgumentException($"Repeated flag. ({c})", "value"); } _Attributes |= FileAttributes.NotContentIndexed; break; case 'L': if ((_Attributes & FileAttributes.ReparsePoint) != 0) { throw new ArgumentException($"Repeated flag. ({c})", "value"); } _Attributes |= FileAttributes.ReparsePoint; break; default: throw new ArgumentException(value); } } } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("attributes ").Append(EnumUtil.GetDescription(Operator)).Append(" ") .Append(AttributeString); return stringBuilder.ToString(); } private bool _EvaluateOne(FileAttributes fileAttrs, FileAttributes criterionAttrs) { bool flag = false; if ((_Attributes & criterionAttrs) == criterionAttrs) { return (fileAttrs & criterionAttrs) == criterionAttrs; } return true; } internal override bool Evaluate(string filename) { if (Directory.Exists(filename)) { return Operator != ComparisonOperator.EqualTo; } FileAttributes attributes = File.GetAttributes(filename); return _Evaluate(attributes); } private bool _Evaluate(FileAttributes fileAttrs) { bool flag = _EvaluateOne(fileAttrs, FileAttributes.Hidden); if (flag) { flag = _EvaluateOne(fileAttrs, FileAttributes.System); } if (flag) { flag = _EvaluateOne(fileAttrs, FileAttributes.ReadOnly); } if (flag) { flag = _EvaluateOne(fileAttrs, FileAttributes.Archive); } if (flag) { flag = _EvaluateOne(fileAttrs, FileAttributes.NotContentIndexed); } if (flag) { flag = _EvaluateOne(fileAttrs, FileAttributes.ReparsePoint); } if (Operator != ComparisonOperator.EqualTo) { flag = !flag; } return flag; } internal override bool Evaluate(ZipEntry entry) { FileAttributes attributes = entry.Attributes; return _Evaluate(attributes); } } internal class CompoundCriterion : SelectionCriterion { internal LogicalConjunction Conjunction; internal SelectionCriterion Left; private SelectionCriterion _Right; internal SelectionCriterion Right { get { return _Right; } set { _Right = value; if (value == null) { Conjunction = LogicalConjunction.NONE; } else if (Conjunction == LogicalConjunction.NONE) { Conjunction = LogicalConjunction.AND; } } } internal override bool Evaluate(string filename) { bool flag = Left.Evaluate(filename); switch (Conjunction) { case LogicalConjunction.AND: if (flag) { flag = Right.Evaluate(filename); } break; case LogicalConjunction.OR: if (!flag) { flag = Right.Evaluate(filename); } break; case LogicalConjunction.XOR: flag ^= Right.Evaluate(filename); break; default: throw new ArgumentException("Conjunction"); } return flag; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("(").Append((Left != null) ? Left.ToString() : "null").Append(" ") .Append(Conjunction.ToString()) .Append(" ") .Append((Right != null) ? Right.ToString() : "null") .Append(")"); return stringBuilder.ToString(); } internal override bool Evaluate(ZipEntry entry) { bool flag = Left.Evaluate(entry); switch (Conjunction) { case LogicalConjunction.AND: if (flag) { flag = Right.Evaluate(entry); } break; case LogicalConjunction.OR: if (!flag) { flag = Right.Evaluate(entry); } break; case LogicalConjunction.XOR: flag ^= Right.Evaluate(entry); break; } return flag; } } public class FileSelector { private enum ParseState { Start, OpenParen, CriterionDone, ConjunctionPending, Whitespace } private static class RegexAssertions { public static readonly string PrecededByOddNumberOfSingleQuotes = "(?<=(?:[^']*'[^']*')*'[^']*)"; public static readonly string FollowedByOddNumberOfSingleQuotesAndLineEnd = "(?=[^']*'(?:[^']*'[^']*')*[^']*$)"; public static readonly string PrecededByEvenNumberOfSingleQuotes = "(?<=(?:[^']*'[^']*')*[^']*)"; public static readonly string FollowedByEvenNumberOfSingleQuotesAndLineEnd = "(?=(?:[^']*'[^']*')*[^']*$)"; } internal SelectionCriterion _Criterion; public string SelectionCriteria { get { if (_Criterion == null) { return null; } return _Criterion.ToString(); } set { if (value == null) { _Criterion = null; } else if (value.Trim() == "") { _Criterion = null; } else { _Criterion = _ParseCriterion(value); } } } public bool TraverseReparsePoints { get; set; } public FileSelector(string selectionCriteria) : this(selectionCriteria, traverseDirectoryReparsePoints: true) { } public FileSelector(string selectionCriteria, bool traverseDirectoryReparsePoints) { if (!string.IsNullOrEmpty(selectionCriteria)) { _Criterion = _ParseCriterion(selectionCriteria); } TraverseReparsePoints = traverseDirectoryReparsePoints; } private static string NormalizeCriteriaExpression(string source) { string[][] array = new string[11][] { new string[2] { "([^']*)\\(\\(([^']+)", "$1( ($2" }, new string[2] { "(.)\\)\\)", "$1) )" }, new string[2] { "\\(([^'\\f\\n\\r\\t\\v\\x85\\p{Z}])", "( $1" }, new string[2] { "(\\S)\\)", "$1 )" }, new string[2] { "^\\)", " )" }, new string[2] { "(\\S)\\(", "$1 (" }, new string[2] { "\\)([^'\\f\\n\\r\\t\\v\\x85\\p{Z}])", ") $1" }, new string[2] { "(=)('[^']*')", "$1 $2" }, new string[2] { "([^ !><])(>|<|!=|=)", "$1 $2" }, new string[2] { "(>|<|!=|=)([^ =])", "$1 $2" }, new string[2] { "/", "\\" } }; string input = source; for (int i = 0; i < array.Length; i++) { string pattern = RegexAssertions.PrecededByEvenNumberOfSingleQuotes + array[i][0] + RegexAssertions.FollowedByEvenNumberOfSingleQuotesAndLineEnd; input = Regex.Replace(input, pattern, array[i][1]); } string pattern2 = "/" + RegexAssertions.FollowedByOddNumberOfSingleQuotesAndLineEnd; input = Regex.Replace(input, pattern2, "\\"); pattern2 = " " + RegexAssertions.FollowedByOddNumberOfSingleQuotesAndLineEnd; return Regex.Replace(input, pattern2, "\u0006"); } private static SelectionCriterion _ParseCriterion(string s) { if (s == null) { return null; } s = NormalizeCriteriaExpression(s); if (s.IndexOf(" ") == -1) { s = "name = " + s; } string[] array = s.Trim().Split(' ', '\t'); if (array.Length < 3) { throw new ArgumentException(s); } SelectionCriterion selectionCriterion = null; LogicalConjunction logicalConjunction = LogicalConjunction.NONE; Stack<ParseState> stack = new Stack<ParseState>(); Stack<SelectionCriterion> stack2 = new Stack<SelectionCriterion>(); stack.Push(ParseState.Start); for (int i = 0; i < array.Length; i++) { string text = array[i].ToLower(); ParseState parseState; switch (text) { case "and": case "xor": case "or": parseState = stack.Peek(); if (parseState != ParseState.CriterionDone) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } if (array.Length <= i + 3) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } logicalConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), array[i].ToUpper(), ignoreCase: true); selectionCriterion = new CompoundCriterion { Left = selectionCriterion, Right = null, Conjunction = logicalConjunction }; stack.Push(parseState); stack.Push(ParseState.ConjunctionPending); stack2.Push(selectionCriterion); break; case "(": parseState = stack.Peek(); if (parseState != 0 && parseState != ParseState.ConjunctionPending && parseState != ParseState.OpenParen) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } if (array.Length <= i + 4) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } stack.Push(ParseState.OpenParen); break; case ")": parseState = stack.Pop(); if (stack.Peek() != ParseState.OpenParen) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } stack.Pop(); stack.Push(ParseState.CriterionDone); break; case "atime": case "ctime": case "mtime": { if (array.Length <= i + 2) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } DateTime value; try { value = DateTime.ParseExact(array[i + 2], "yyyy-MM-dd-HH:mm:ss", null); } catch (FormatException) { try { value = DateTime.ParseExact(array[i + 2], "yyyy/MM/dd-HH:mm:ss", null); } catch (FormatException) { try { value = DateTime.ParseExact(array[i + 2], "yyyy/MM/dd", null); goto end_IL_0497; } catch (FormatException) { try { value = DateTime.ParseExact(array[i + 2], "MM/dd/yyyy", null); goto end_IL_0497; } catch (FormatException) { value = DateTime.ParseExact(array[i + 2], "yyyy-MM-dd", null); goto end_IL_0497; } } end_IL_0497:; } } value = DateTime.SpecifyKind(value, DateTimeKind.Local).ToUniversalTime(); selectionCriterion = new TimeCriterion { Which = (WhichTime)Enum.Parse(typeof(WhichTime), array[i], ignoreCase: true), Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), array[i + 1]), Time = value }; i += 2; stack.Push(ParseState.CriterionDone); break; } case "length": case "size": { if (array.Length <= i + 2) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } long num = 0L; string text2 = array[i + 2]; num = (text2.ToUpper().EndsWith("K") ? (long.Parse(text2.Substring(0, text2.Length - 1)) * 1024) : (text2.ToUpper().EndsWith("KB") ? (long.Parse(text2.Substring(0, text2.Length - 2)) * 1024) : (text2.ToUpper().EndsWith("M") ? (long.Parse(text2.Substring(0, text2.Length - 1)) * 1024 * 1024) : (text2.ToUpper().EndsWith("MB") ? (long.Parse(text2.Substring(0, text2.Length - 2)) * 1024 * 1024) : (text2.ToUpper().EndsWith("G") ? (long.Parse(text2.Substring(0, text2.Length - 1)) * 1024 * 1024 * 1024) : ((!text2.ToUpper().EndsWith("GB")) ? long.Parse(array[i + 2]) : (long.Parse(text2.Substring(0, text2.Length - 2)) * 1024 * 1024 * 1024))))))); selectionCriterion = new SizeCriterion { Size = num, Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), array[i + 1]) }; i += 2; stack.Push(ParseState.CriterionDone); break; } case "filename": case "name": { if (array.Length <= i + 2) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } ComparisonOperator comparisonOperator2 = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), array[i + 1]); if (comparisonOperator2 != ComparisonOperator.NotEqualTo && comparisonOperator2 != ComparisonOperator.EqualTo) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } string text3 = array[i + 2]; if (text3.StartsWith("'") && text3.EndsWith("'")) { text3 = text3.Substring(1, text3.Length - 2).Replace("\u0006", " "); } if (Path.DirectorySeparatorChar == '/') { text3 = text3.Replace('\\', Path.DirectorySeparatorChar); } selectionCriterion = new NameCriterion { MatchingFileSpec = text3, Operator = comparisonOperator2 }; i += 2; stack.Push(ParseState.CriterionDone); break; } case "attrs": case "attributes": case "type": { if (array.Length <= i + 2) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } ComparisonOperator comparisonOperator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), array[i + 1]); if (comparisonOperator != ComparisonOperator.NotEqualTo && comparisonOperator != ComparisonOperator.EqualTo) { throw new ArgumentException(string.Join(" ", array, i, array.Length - i)); } selectionCriterion = ((text == "type") ? ((SelectionCriterion)new TypeCriterion { AttributeString = array[i + 2], Operator = comparisonOperator }) : ((SelectionCriterion)new AttributesCriterion { AttributeString = array[i + 2], Operator = comparisonOperator })); i += 2; stack.Push(ParseState.CriterionDone); break; } case "": stack.Push(ParseState.Whitespace); break; default: throw new ArgumentException("'" + array[i] + "'"); } parseState = stack.Peek(); if (parseState == ParseState.CriterionDone) { stack.Pop(); if (stack.Peek() == ParseState.ConjunctionPending) { while (stack.Peek() == ParseState.ConjunctionPending) { CompoundCriterion obj = stack2.Pop() as CompoundCriterion; obj.Right = selectionCriterion; selectionCriterion = obj; stack.Pop(); parseState = stack.Pop(); if (parseState != ParseState.CriterionDone) { throw new ArgumentException("??"); } } } else { stack.Push(ParseState.CriterionDone); } } if (parseState == ParseState.Whitespace) { stack.Pop(); } } return selectionCriterion; } public override string ToString() { return "FileSelector(" + _Criterion.ToString() + ")"; } private bool Evaluate(string filename) { return _Criterion.Evaluate(filename); } [Conditional("SelectorTrace")] private void SelectorTrace(string format, params object[] args) { if (_Criterion != null && _Criterion.Verbose) { Console.WriteLine(format, args); } } public ICollection<string> SelectFiles(string directory) { return SelectFiles(directory, recurseDirectories: false); } public ReadOnlyCollection<string> SelectFiles(string directory, bool recurseDirectories) { if (_Criterion == null) { throw new ArgumentException("SelectionCriteria has not been set"); } List<string> list = new List<string>(); try { if (Directory.Exists(directory)) { string[] files = Directory.GetFiles(directory); foreach (string text in files) { if (Evaluate(text)) { list.Add(text); } } if (recurseDirectories) { files = Directory.GetDirectories(directory); foreach (string text2 in files) { if (TraverseReparsePoints || (File.GetAttributes(text2) & FileAttributes.ReparsePoint) == 0) { if (Evaluate(text2)) { list.Add(text2); } list.AddRange(SelectFiles(text2, recurseDirectories)); } } } } } catch (UnauthorizedAccessException) { } catch (IOException) { } return list.AsReadOnly(); } private bool Evaluate(ZipEntry entry) { return _Criterion.Evaluate(entry); } public ICollection<ZipEntry> SelectEntries(ZipFile zip) { if (zip == null) { throw new ArgumentNullException("zip"); } List<ZipEntry> list = new List<ZipEntry>(); foreach (ZipEntry item in zip) { if (Evaluate(item)) { list.Add(item); } } return list; } public ICollection<ZipEntry> SelectEntries(ZipFile zip, string directoryPathInArchive) { if (zip == null) { throw new ArgumentNullException("zip"); } List<ZipEntry> list = new List<ZipEntry>(); string text = directoryPathInArchive?.Replace("/", "\\"); if (text != null) { while (text.EndsWith("\\")) { text = text.Substring(0, text.Length - 1); } } foreach (ZipEntry item in zip) { if ((directoryPathInArchive == null || Path.GetDirectoryName(item.FileName) == directoryPathInArchive || Path.GetDirectoryName(item.FileName) == text) && Evaluate(item)) { list.Add(item); } } return list; } } internal sealed class EnumUtil { private EnumUtil() { } internal static string GetDescription(Enum value) { DescriptionAttribute[] array = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), inherit: false); if (array.Length != 0) { return array[0].Description; } return value.ToString(); } internal static object Parse(Type enumType, string stringRepresentation) { return Parse(enumType, stringRepresentation, ignoreCase: false); } internal static object Parse(Type enumType, string stringRepresentation, bool ignoreCase) { if (ignoreCase) { stringRepresentation = stringRepresentation.ToLower(); } foreach (Enum value in Enum.GetValues(enumType)) { string text = GetDescription(value); if (ignoreCase) { text = text.ToLower(); } if (text == stringRepresentation) { return value; } } return Enum.Parse(enumType, stringRepresentation, ignoreCase); } } } namespace Ionic.Zlib { internal enum BlockState { NeedMore, BlockDone, FinishStarted, FinishDone } internal enum DeflateFlavor { Store, Fast, Slow } internal sealed class DeflateManager { internal delegate BlockState CompressFunc(FlushType flush); internal class Config { internal int GoodLength; internal int MaxLazy; internal int NiceLength; internal int MaxChainLength; internal DeflateFlavor Flavor; private static readonly Config[] Table; private Config(int goodLength, int maxLazy, int niceLength, int maxChainLength, DeflateFlavor flavor) { GoodLength = goodLength; MaxLazy = maxLazy; NiceLength = niceLength; MaxChainLength = maxChainLength; Flavor = flavor; } public static Config Lookup(CompressionLevel level) { return Table[(int)level]; } static Config() { Table = new Config[10] { new Config(0, 0, 0, 0, DeflateFlavor.Store), new Config(4, 4, 8, 4, DeflateFlavor.Fast), new Config(4, 5, 16, 8, DeflateFlavor.Fast), new Config(4, 6, 32, 32, DeflateFlavor.Fast), new Config(4, 4, 16, 16, DeflateFlavor.Slow), new Config(8, 16, 32, 32, DeflateFlavor.Slow), new Config(8, 16, 128, 128, DeflateFlavor.Slow), new Config(8, 32, 128, 256, DeflateFlavor.Slow), new Config(32, 128, 258, 1024, DeflateFlavor.Slow), new Config(32, 258, 258, 4096, DeflateFlavor.Slow) }; } } private static readonly int MEM_LEVEL_MAX = 9; private static readonly int MEM_LEVEL_DEFAULT = 8; private CompressFunc DeflateFunction; private static readonly string[] _ErrorMessage = new string[10] { "need dictionary", "stream end", "", "file error", "stream error", "data error", "insufficient memory", "buffer error", "incompatible version", "" }; private static readonly int PRESET_DICT = 32; private static readonly int INIT_STATE = 42; private static readonly int BUSY_STATE = 113; private static readonly int FINISH_STATE = 666; private static readonly int Z_DEFLATED = 8; private static readonly int STORED_BLOCK = 0; private static readonly int STATIC_TREES = 1; private static readonly int DYN_TREES = 2; private static readonly int Z_BINARY = 0; private static readonly int Z_ASCII = 1; private static readonly int Z_UNKNOWN = 2; private static readonly int Buf_size = 16; private static readonly int MIN_MATCH = 3; private static readonly int MAX_MATCH = 258; private static readonly int MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; private static readonly int HEAP_SIZE = 2 * InternalConstants.L_CODES + 1; private static readonly int END_BLOCK = 256; internal ZlibCodec _codec; internal int status; internal byte[] pending; internal int nextPending; internal int pendingCount; internal sbyte data_type; internal int last_flush; internal int w_size; internal int w_bits; internal int w_mask; internal byte[] window; internal int window_size; internal short[] prev; internal short[] head; internal int ins_h; internal int hash_size; internal int hash_bits; internal int hash_mask; internal int hash_shift; internal int block_start; private Config config; internal int match_length; internal int prev_match; internal int match_available; internal int strstart; internal int match_start; internal int lookahead; internal int prev_length; internal CompressionLevel compressionLevel; internal CompressionStrategy compressionStrategy; internal short[] dyn_ltree; internal short[] dyn_dtree; internal short[] bl_tree; internal Tree treeLiterals = new Tree(); internal Tree treeDistances = new Tree(); internal Tree treeBitLengths = new Tree(); internal short[] bl_count = new short[InternalConstants.MAX_BITS + 1]; internal int[] heap = new int[2 * InternalConstants.L_CODES + 1]; internal int heap_len; internal int heap_max; internal sbyte[] depth = new sbyte[2 * InternalConstants.L_CODES + 1]; internal int _lengthOffset; internal int lit_bufsize; internal int last_lit; internal int _distanceOffset; internal int opt_len; internal int static_len; internal int matches; internal int last_eob_len; internal short bi_buf; internal int bi_valid; private bool Rfc1950BytesEmitted; private bool _WantRfc1950HeaderBytes = true; internal bool WantRfc1950HeaderBytes { get { return _WantRfc1950HeaderBytes; } set { _WantRfc1950HeaderBytes = value; } } internal DeflateManager() { dyn_ltree = new short[HEAP_SIZE * 2]; dyn_dtree = new short[(2 * InternalConstants.D_CODES + 1) * 2]; bl_tree = new short[(2 * InternalConstants.BL_CODES + 1) * 2]; } private void _InitializeLazyMatch() { window_size = 2 * w_size; Array.Clear(head, 0, hash_size); config = Config.Lookup(compressionLevel); SetDeflater(); strstart = 0; block_start = 0; lookahead = 0; match_length = (prev_length = MIN_MATCH - 1); match_available = 0; ins_h = 0; } private void _InitializeTreeData() { treeLiterals.dyn_tree = dyn_ltree; treeLiterals.staticTree = StaticTree.Literals; treeDistances.dyn_tree = dyn_dtree; treeDistances.staticTree = StaticTree.Distances; treeBitLengths.dyn_tree = bl_tree; treeBitLengths.staticTree = StaticTree.BitLengths; bi_buf = 0; bi_valid = 0; last_eob_len = 8; _InitializeBlocks(); } internal void _InitializeBlocks() { for (int i = 0; i < InternalConstants.L_CODES; i++) { dyn_ltree[i * 2] = 0; } for (int j = 0; j < InternalConstants.D_CODES; j++) { dyn_dtree[j * 2] = 0; } for (int k = 0; k < InternalConstants.BL_CODES; k++) { bl_tree[k * 2] = 0; } dyn_ltree[END_BLOCK * 2] = 1; opt_len = (static_len = 0); last_lit = (matches = 0); } internal void pqdownheap(short[] tree, int k) { int num = heap[k]; for (int num2 = k << 1; num2 <= heap_len; num2 <<= 1) { if (num2 < heap_len && _IsSmaller(tree, heap[num2 + 1], heap[num2], depth)) { num2++; } if (_IsSmaller(tree, num, heap[num2], depth)) { break; } heap[k] = heap[num2]; k = num2; } heap[k] = num; } internal static bool _IsSmaller(short[] tree, int n, int m, sbyte[] depth) { short num = tree[n * 2]; short num2 = tree[m * 2]; if (num >= num2) { if (num == num2) { return depth[n] <= depth[m]; } return false; } return true; } internal void scan_tree(short[] tree, int max_code) { int num = -1; int num2 = tree[1]; int num3 = 0; int num4 = 7; int num5 = 4; if (num2 == 0) { num4 = 138; num5 = 3; } tree[(max_code + 1) * 2 + 1] = short.MaxValue; for (int i = 0; i <= max_code; i++) { int num6 = num2; num2 = tree[(i + 1) * 2 + 1]; if (++num3 < num4 && num6 == num2) { continue; } if (num3 < num5) { bl_tree[num6 * 2] = (short)(bl_tree[num6 * 2] + num3); } else if (num6 != 0) { if (num6 != num) { bl_tree[num6 * 2]++; } bl_tree[InternalConstants.REP_3_6 * 2]++; } else if (num3 <= 10) { bl_tree[InternalConstants.REPZ_3_10 * 2]++; } else { bl_tree[InternalConstants.REPZ_11_138 * 2]++; } num3 = 0; num = num6; if (num2 == 0) { num4 = 138; num5 = 3; } else if (num6 == num2) { num4 = 6; num5 = 3; } else { num4 = 7; num5 = 4; } } } internal int build_bl_tree() { scan_tree(dyn_ltree, treeLiterals.max_code); scan_tree(dyn_dtree, treeDistances.max_code); treeBitLengths.build_tree(this); int num = InternalConstants.BL_CODES - 1; while (num >= 3 && bl_tree[Tree.bl_order[num] * 2 + 1] == 0) { num--; } opt_len += 3 * (num + 1) + 5 + 5 + 4; return num; } internal void send_all_trees(int lcodes, int dcodes, int blcodes) { send_bits(lcodes - 257, 5); send_bits(dcodes - 1, 5); send_bits(blcodes - 4, 4); for (int i = 0; i < blcodes; i++) { send_bits(bl_tree[Tree.bl_order[i] * 2 + 1], 3); } send_tree(dyn_ltree, lcodes - 1); send_tree(dyn_dtree, dcodes - 1); } internal void send_tree(short[] tree, int max_code) { int num = -1; int num2 = tree[1]; int num3 = 0; int num4 = 7; int num5 = 4; if (num2 == 0) { num4 = 138; num5 = 3; } for (int i = 0; i <= max_code; i++) { int num6 = num2; num2 = tree[(i + 1) * 2 + 1]; if (++num3 < num4 && num6 == num2) { continue; } if (num3 < num5) { do { send_code(num6, bl_tree); } while (--num3 != 0); } else if (num6 != 0) { if (num6 != num) { send_code(num6, bl_tree); num3--; } send_code(InternalConstants.REP_3_6, bl_tree); send_bits(num3 - 3, 2); } else if (num3 <= 10) { send_code(InternalConstants.REPZ_3_10, bl_tree); send_bits(num3 - 3, 3); } else { send_code(InternalConstants.REPZ_11_138, bl_tree); send_bits(num3 - 11, 7); } num3 = 0; num = num6; if (num2 == 0) { num4 = 138; num5 = 3; } else if (num6 == num2) { num4 = 6; num5 = 3; } else { num4 = 7; num5 = 4; } } } private void put_bytes(byte[] p, int start, int len) { Array.Copy(p, start, pending, pendingCount, len); pendingCount += len; } internal void send_code(int c, short[] tree) { int num = c * 2; send_bits(tree[num] & 0xFFFF, tree[num + 1] & 0xFFFF); } internal void send_bits(int value, int length) { if (bi_valid > Buf_size - length) { bi_buf |= (short)((value << bi_valid) & 0xFFFF); pending[pendingCount++] = (byte)bi_buf; pending[pendingCount++] = (byte)(bi_buf >> 8); bi_buf = (short)(value >>> Buf_size - bi_valid); bi_valid += length - Buf_size; } else { bi_buf |= (short)((value << bi_valid) & 0xFFFF); bi_valid += length; } } internal void _tr_align() { send_bits(STATIC_TREES << 1, 3); send_code(END_BLOCK, StaticTree.lengthAndLiteralsTreeCodes); bi_flush(); if (1 + last_eob_len + 10 - bi_valid < 9) { send_bits(STATIC_TREES << 1, 3); send_code(END_BLOCK, StaticTree.lengthAndLiteralsTreeCodes); bi_flush(); } last_eob_len = 7; } internal bool _tr_tally(int dist, int lc) { pending[_distanceOffset + last_lit * 2] = (byte)((uint)dist >> 8); pending[_distanceOffset + last_lit * 2 + 1] = (byte)dist; pending[_lengthOffset + last_lit] = (byte)lc; last_lit++; if (dist == 0) { dyn_ltree[lc * 2]++; } else { matches++; dist--; dyn_ltree[(Tree.LengthCode[lc] + InternalConstants.LITERALS + 1) * 2]++; dyn_dtree[Tree.DistanceCode(dist) * 2]++; } if ((last_lit & 0x1FFF) == 0 && compressionLevel > CompressionLevel.Level2) { int num = last_lit << 3; int num2 = strstart - block_start; for (int i = 0; i < InternalConstants.D_CODES; i++) { num = (int)(num + dyn_dtree[i * 2] * (5L + (long)Tree.ExtraDistanceBits[i])); } num >>= 3; if (matches < last_lit / 2 && num < num2 / 2) { return true; } } if (last_lit != lit_bufsize - 1) { return last_lit == lit_bufsize; } return true; } internal void send_compressed_block(short[] ltree, short[] dtree) { int num = 0; if (last_lit != 0) { do { int num2 = _distanceOffset + num * 2; int num3 = ((pending[num2] << 8) & 0xFF00) | (pending[num2 + 1] & 0xFF); int num4 = pending[_lengthOffset + num] & 0xFF; num++; if (num3 == 0) { send_code(num4, ltree); continue; } int num5 = Tree.LengthCode[num4]; send_code(num5 + InternalConstants.LITERALS + 1, ltree); int num6 = Tree.ExtraLengthBits[num5]; if (num6 != 0) { num4 -= Tree.LengthBase[num5]; send_bits(num4, num6); } num3--; num5 = Tree.DistanceCode(num3); send_code(num5, dtree); num6 = Tree.ExtraDistanceBits[num5]; if (num6 != 0) { num3 -= Tree.DistanceBase[num5]; send_bits(num3, num6); } } while (num < last_lit); } send_code(END_BLOCK, ltree); last_eob_len = ltree[END_BLOCK * 2 + 1]; } internal void set_data_type() { int i = 0; int num = 0; int num2 = 0; for (; i < 7; i++) { num2 += dyn_ltree[i * 2]; } for (; i < 128; i++) { num += dyn_ltree[i * 2]; } for (; i < InternalConstants.LITERALS; i++) { num2 += dyn_ltree[i * 2]; } data_type = (sbyte)((num2 > num >> 2) ? Z_BINARY : Z_ASCII); } internal void bi_flush() { if (bi_valid == 16) { pending[pendingCount++] = (byte)bi_buf; pending[pendingCount++] = (byte)(bi_buf >> 8); bi_buf = 0; bi_valid = 0; } else if (bi_valid >= 8) { pending[pendingCount++] = (byte)bi_buf; bi_buf >>= 8; bi_valid -= 8; } } internal void bi_windup() { if (bi_valid > 8) { pending[pendingCount++] = (byte)bi_buf; pending[pendingCount++] = (byte)(bi_buf >> 8); } else if (bi_valid > 0) { pending[pendingCount++] = (byte)bi_buf; } bi_buf = 0; bi_valid = 0; } internal void copy_block(int buf, int len, bool header) { bi_windup(); last_eob_len = 8; if (header) { pending[pendingCount++] = (byte)len; pending[pendingCount++] = (byte)(len >> 8); pending[pendingCount++] = (byte)(~len); pending[pendingCount++] = (byte)(~len >> 8); } put_bytes(window, buf, len); } internal void flush_block_only(bool eof) { _tr_flush_block((block_start >= 0) ? block_start : (-1), strstart - block_start, eof); block_start = strstart; _codec.flush_pending(); } internal BlockState DeflateNone(FlushType flush) { int num = 65535; if (num > pending.Length - 5) { num = pending.Length - 5; } while (true) { if (lookahead <= 1) { _fillWindow(); if (lookahead == 0 && flush == FlushType.None) { return BlockState.NeedMore; } if (lookahead == 0) { break; } } strstart += lookahead; lookahead = 0; int num2 = block_start + num; if (strstart == 0 || strstart >= num2) { lookahead = strstart - num2; strstart = num2; flush_block_only(eof: false); if (_codec.AvailableBytesOut == 0) { return BlockState.NeedMore; } } if (strstart - block_start >= w_size - MIN_LOOKAHEAD) { flush_block_only(eof: false); if (_codec.AvailableBytesOut == 0) { return BlockState.NeedMore; } } } flush_block_only(flush == FlushType.Finish); if (_codec.AvailableBytesOut == 0) { if (flush != FlushType.Finish) { return BlockState.NeedMore; } return BlockState.FinishStarted; } if (flush != FlushType.Finish) { return BlockState.BlockDone; } return BlockState.FinishDone; } internal void _tr_stored_block(int buf, int stored_len, bool eof) { send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); copy_block(buf, stored_len, header: true); } internal void _tr_flush_block(int buf, int stored_len, bool eof) { int num = 0; int num2; int num3; if (compressionLevel > CompressionLevel.None) { if (data_type == Z_UNKNOWN) { set_data_type(); } treeLiterals.build_tree(this); treeDistances.build_tree(this); num = build_bl_tree(); num2 = opt_len + 3 + 7 >> 3; num3 = static_len + 3 + 7 >> 3; if (num3 <= num2) { num2 = num3; } } else { num2 = (num3 = stored_len + 5); } if (stored_len + 4 <= num2 && buf != -1) { _tr_stored_block(buf, stored_len, eof); } else if (num3 == num2) { send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3); send_compressed_block(StaticTree.lengthAndLiteralsTreeCodes, StaticTree.distTreeCodes); } else { send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3); send_all_trees(treeLiterals.max_code + 1, treeDistances.max_code + 1, num + 1); send_compressed_block(dyn_ltree, dyn_dtree); } _InitializeBlocks(); if (eof) { bi_windup(); } } private void _fillWindow() { do { int num = window_size - lookahead - strstart; int num2; if (num == 0 && strstart == 0 && lookahead == 0) { num = w_size; } else if (num == -1) { num--; } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) { Array.Copy(window, w_size, window, 0, w_size); match_start -= w_size; strstart -= w_size; block_start -= w_size; num2 = hash_size; int num3 = num2; do { int num4 = head[--num3] & 0xFFFF; head[num3] = (short)((num4 >= w_size) ? (num4 - w_size) : 0); } while (--num2 != 0); num2 = w_size; num3 = num2; do { int num4 = prev[--num3] & 0xFFFF; prev[num3] = (short)((num4 >= w_size) ? (num4 - w_size) : 0); } while (--num2 != 0); num += w_size; } if (_codec.AvailableBytesIn == 0) { break; } num2 = _codec.read_buf(window, strstart + lookahead, num); lookahead += num2; if (lookahead >= MIN_MATCH) { ins_h = window[strstart] & 0xFF; ins_h = ((ins_h << hash_shift) ^ (window[strstart + 1] & 0xFF)) & hash_mask; } } while (lookahead < MIN_LOOKAHEAD && _codec.AvailableBytesIn != 0); } internal BlockState DeflateFast(FlushType flush) { int num = 0; while (true) { if (lookahead < MIN_LOOKAHEAD) { _fillWindow(); if (lookahead < MIN_LOOKAHEAD && flush == FlushType.None) { return BlockState.NeedMore; } if (lookahead == 0) { break; } } if (lookahead >= MIN_MATCH) { ins_h = ((ins_h << hash_shift) ^ (window[strstart + (MIN_MATCH - 1)] & 0xFF)) & hash_mask; num = head[ins_h] & 0xFFFF; prev[strstart & w_mask] = head[ins_h]; head[ins_h] = (short)strstart; } if (num != 0L && ((strstart - num) & 0xFFFF) <= w_size - MIN_LOOKAHEAD && compressionStrategy != CompressionStrategy.HuffmanOnly) { match_length = longest_match(num); } bool flag; if (match_length >= MIN_MATCH) { flag = _tr_tally(strstart - match_start, match_length - MIN_MATCH); lookahead -= match_length; if (match_length <= config.MaxLazy && lookahead >= MIN_MATCH) { match_length--; do { strstart++; ins_h = ((ins_h << hash_shift) ^ (window[strstart + (MIN_MATCH - 1)] & 0xFF)) & hash_mask; num = head[ins_h] & 0xFFFF; prev[strstart & w_mask] = head[ins_h]; head[ins_h] = (short)strstart; } while (--match_length != 0); strstart++; } else { strstart += match_length; match_length = 0; ins_h = window[strstart] & 0xFF; ins_h = ((ins_h << hash_shift) ^ (window[strstart + 1] & 0xFF)) & hash_mask; } } else { flag = _tr_tally(0, window[strstart] & 0xFF); lookahead--; strstart++; } if (flag) { flush_block_only(eof: false); if (_codec.AvailableBytesOut == 0) { return BlockState.NeedMore; } } } flush_block_only(flush == FlushType.Finish); if (_codec.AvailableBytesOut == 0) { if (flush == FlushType.Finish) { return BlockState.FinishStarted; } return BlockState.NeedMore; } if (flush != FlushType.Finish) { return BlockState.BlockDone; } return BlockState.FinishDone; } internal BlockState DeflateSlow(FlushType flush) { int num = 0; while (true) { if (lookahead < MIN_LOOKAHEAD) { _fillWindow(); if (lookahead < MIN_LOOKAHEAD && flush == FlushType.None) { return BlockState.NeedMore; } if (lookahead == 0) { break; } } if (lookahead >= MIN_MATCH) { ins_h = ((ins_h << hash_shift) ^ (window[strstart + (MIN_MATCH - 1)] & 0xFF)) & hash_mask; num = head[ins_h] & 0xFFFF; prev[strstart & w_mask] = head[ins_h]; head[ins_h] = (short)strstart; } prev_length = match_length; prev_match = match_start; match_length = MIN_MATCH - 1; if (num != 0 && prev_length < config.MaxLazy && ((strstart - num) & 0xFFFF) <= w_size - MIN_LOOKAHEAD) { if (compressionStrategy != CompressionStrategy.HuffmanOnly) { match_length = longest_match(num); } if (match_length <= 5 && (compressionStrategy == CompressionStrategy.Filtered || (match_length == MIN_MATCH && strstart - match_start > 4096))) { match_length = MIN_MATCH - 1; } } if (prev_length >= MIN_MATCH && match_length <= prev_length) { int num2 = strstart + lookahead - MIN_MATCH; bool flag = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH); lookahead -= prev_length - 1; prev_length -= 2; do { if (++strstart <= num2) { ins_h = ((ins_h << hash_shift) ^ (window[strstart + (MIN_MATCH - 1)] & 0xFF)) & hash_mask; num = head[ins_h] & 0xFFFF; prev[strstart & w_mask] = head[ins_h]; head[ins_h] = (short)strstart; } } while (--prev_length != 0); match_available = 0; match_length = MIN_MATCH - 1; strstart++; if (flag) { flush_block_only(eof: false); if (_codec.AvailableBytesOut == 0) { return BlockState.NeedMore; } } } else if (match_available != 0) { if (_tr_tally(0, window[strstart - 1] & 0xFF)) { flush_block_only(eof: false); } strstart++; lookahead--; if (_codec.AvailableBytesOut == 0) { return BlockState.NeedMore; } } else { match_available = 1; strstart++; lookahead--; } } if (match_available != 0) { bool flag = _tr_tally(0, window[strstart - 1] & 0xFF); match_available = 0; } flush_block_only(flush == FlushType.Finish); if (_codec.AvailableBytesOut == 0) { if (flush == FlushType.Finish) { return BlockState.FinishStarted; } return BlockState.NeedMore; } if (flush != FlushType.Finish) { return BlockState.BlockDone; } return BlockState.FinishDone; } internal int longest_match(int cur_match) { int num = config.MaxChainLength; int num2 = strstart; int num3 = prev_length; int num4 = ((strstart > w_size - MIN_LOOKAHEAD) ? (strstart - (w_size - MIN_LOOKAHEAD)) : 0); int niceLength = config.NiceLength; int num5 = w_mask; int num6 = strstart + MAX_MATCH; byte b = window[num2 + num3 - 1]; byte b2 = window[num2 + num3]; if (prev_length >= config.GoodLength) { num >>= 2; } if (niceLength > lookahead) { niceLength = lookahead; } do { int num7 = cur_match; if (window[num7 + num3] != b2 || window[num7 + num3 - 1] != b || window[num7] != window[num2] || window[++num7] != window[num2 + 1]) { continue; } num2 += 2; num7++; while (window[++num2] == window[++num7] && window[++num2] == window[++num7] && window[++num2] == window[++num7] && window[++num2] == window[++num7] && window[++num2] == window[++num7] && window[++num2] == window[++num7] && window[++num2] == window[++num7] && window[++num2] == window[++num7] && num2 < num6) { } int num8 = MAX_MATCH - (num6 - num2); num2 = num6 - MAX_MATCH; if (num8 > num3) { match_start = cur_match; num3 = num8; if (num8 >= niceLength) { break; } b = window[num2 + num3 - 1]; b2 = window[num2 + num3]; } } while ((cur_match = prev[cur_match & num5] & 0xFFFF) > num4 && --num != 0); if (num3 <= lookahead) { return num3; } return lookahead; } internal int Initialize(ZlibCodec codec, CompressionLevel level) { return Initialize(codec, level, 15); } internal int Initialize(ZlibCodec codec, CompressionLevel level, int bits) { return Initialize(codec, level, bits, MEM_LEVEL_DEFAULT, CompressionStrategy.Default); } internal int Initialize(ZlibCodec codec, CompressionLevel level, int bits, CompressionStrategy compressionStrategy) { return Initialize(codec, level, bits, MEM_LEVEL_DEFAULT, compressionStrategy); } internal int Initialize(ZlibCodec codec, CompressionLevel level, int windowBits, int memLevel, CompressionStrategy strategy) { _codec = codec; _codec.Message = null; if (windowBits < 9 || windowBits > 15) { throw new ZlibException("windowBits must be in the range 9..15."); } if (memLevel < 1 || memLevel > MEM_LEVEL_MAX) { throw new ZlibException($"memLevel must be in the range 1.. {MEM_LEVEL_MAX}"); } _codec.dstate = this; w_bits = windowBits; w_size = 1 << w_bits; w_mask = w_size - 1; hash_bits = memLevel + 7; hash_size = 1 << hash_bits; hash_mask = hash_size - 1; hash_shift = (hash_bits + MIN_MATCH - 1) / MIN_MATCH; window = new byte[w_size * 2]; prev = new short[w_size]; head = new short[hash_size]; lit_bufsize = 1 << memLevel + 6; pending = new byte[lit_bufsize * 4]; _distanceOffset = lit_bufsize; _lengthOffset = 3 * lit_bufsize; compressionLevel = level; compressionStrategy = strategy; Reset(); return 0; } internal void Reset() { _codec.TotalBytesIn = (_codec.TotalBytesOut = 0L); _codec.Message = null; pendingCount = 0; nextPending = 0; Rfc1950BytesEmitted = false; status = (WantRfc1950HeaderBytes ? INIT_STATE : BUSY_STATE); _codec._Adler32 = Adler.Adler32(0u, null, 0, 0); last_flush = 0; _InitializeTreeData(); _InitializeLazyMatch(); } internal int End() { if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) { return -2; } pending = null; head = null; prev = null; window = null; if (status != BUSY_STATE) { return 0; } return -3; } private void SetDeflater() { switch (config.Flavor) { case DeflateFlavor.Store: DeflateFunction = DeflateNone; break; case DeflateFlavor.Fast: DeflateFunction = DeflateFast; break; case DeflateFlavor.Slow: DeflateFunction = DeflateSlow; break; } } internal int SetParams(CompressionLevel level, CompressionStrategy strategy) { int result = 0; if (compressionLevel != level) { Config config = Config.Lookup(level); if (config.Flavor != this.config.Flavor && _codec.TotalBytesIn != 0L) { result = _codec.Deflate(FlushType.Partial); } compressionLevel = level; this.config = config; SetDeflater(); } compressionStrategy = strategy; return result; } internal int SetDictionary(byte[] dictionary) { int num = dictionary.Length; int sourceIndex = 0; if (dictionary == null || status != INIT_STATE) { throw new ZlibException("Stream error."); } _codec._Adler32 = Adler.Adler32(_codec._Adler32, dictionary, 0, dictionary.Length); if (num < MIN_MATCH) { return 0; } if (num > w_size - MIN_LOOKAHEAD) { num = w_size - MIN_LOOKAHEAD; sourceIndex = dictionary.Length - num; } Array.Copy(dictionary, sourceIndex, window, 0, num); strstart = num; block_start = num; ins_h = window[0] & 0xFF; ins_h = ((ins_h << hash_shift) ^ (window[1] & 0xFF)) & hash_mask; for (int i = 0; i <= num - MIN_MATCH; i++) { ins_h = ((ins_h << hash_shift) ^ (window[i + (MIN_MATCH - 1)] & 0xFF)) & hash_mask; prev[i & w_mask] = head[ins_h]; head[ins_h] = (short)i; } return 0; } internal int Deflate(FlushType flush) { if (_codec.OutputBuffer == null || (_codec.InputBuffer == null && _codec.AvailableBytesIn != 0) || (status == FINISH_STATE && flush != FlushType.Finish)) { _codec.Message = _ErrorMessage[4]; throw new ZlibException($"Something is fishy. [{_codec.Message}]"); } if (_codec.AvailableBytesOut == 0) { _codec.Message = _ErrorMessage[7]; throw new ZlibException("OutputBuffer is full (AvailableBytesOut == 0)"); } int num = last_flush; last_flush = (int)flush; if (status == INIT_STATE) { int num2 = Z_DEFLATED + (w_bits - 8 << 4) << 8; int num3 = (int)((compressionLevel - 1) & (CompressionLevel)255) >> 1; if (num3 > 3) { num3 = 3; } num2 |= num3 << 6; if (strstart != 0) { num2 |= PRESET_DICT; } num2 += 31 - num2 % 31; status = BUSY_STATE; pending[pendingCount++] = (byte)(num2 >> 8); pending[pendingCount++] = (byte)num2; if (strstart != 0) { pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF000000u) >> 24); pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF0000) >> 16); pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF00) >> 8); pending[pendingCount++] = (byte)(_codec._Adler32 & 0xFFu); } _codec._Adler32 = Adler.Adler32(0u, null, 0, 0); } if (pendingCount != 0) { _codec.flush_pending(); if (_codec.AvailableBytesOut == 0) { last_flush = -1; return 0; } } else if (_codec.AvailableBytesIn == 0 && (int)flush <= num && flush != FlushType.Finish) { return 0; } if (status == FINISH_STATE && _codec.AvailableBytesIn != 0) { _codec.Message = _ErrorMessage[7]; throw new ZlibException("status == FINISH_STATE && _codec.AvailableBytesIn != 0"); } if (_codec.AvailableBytesIn != 0 || lookahead != 0 || (flush != 0 && status != FINISH_STATE)) { BlockState blockState = DeflateFunction(flush); if (blockState == BlockState.FinishStarted || blockState == BlockState.FinishDone) { status = FINISH_STATE; } switch (blockState) { case BlockState.NeedMore: case BlockState.FinishStarted: if (_codec.AvailableBytesOut == 0) { last_flush = -1; } return 0; case BlockState.BlockDone: if (flush == FlushType.Partial) { _tr_align(); } else { _tr_stored_block(0, 0, eof: false); if (flush == FlushType.Full) { for (int i = 0; i < hash_size; i++) { head[i] = 0; } } } _codec.flush_pending(); if (_codec.AvailableBytesOut == 0) { last_flush = -1; return 0; } break; } } if (flush != FlushType.Finish) { return 0; } if (!WantRfc1950HeaderBytes || Rfc1950BytesEmitted) { return 1; } pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF000000u) >> 24); pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF0000) >> 16); pending[pendingCount++] = (byte)((_codec._Adler32 & 0xFF00) >> 8); pending[pendingCount++] = (byte)(_codec._Adler32 & 0xFFu); _codec.flush_pending(); Rfc1950BytesEmitted = true; if (pendingCount == 0) { return 1; } return 0; } } public class DeflateStream : Stream { internal ZlibBaseStream _baseStream; internal Stream _innerStream; private bool _disposed; public virtual FlushType FlushMode { get { return _baseStream._flushMode; } set { if (_disposed) { throw new ObjectDisposedException("DeflateStream"); } _baseStream._flushMode = value; } } public int BufferSize { get { return _baseStream._bufferSize; } set { if (_disposed) { throw new ObjectDisposedException("DeflateStream"); } if (_baseStream._workingBuffer != null) { throw new ZlibException("The working buffer is already set."); } if (value < 1024) { throw new ZlibException($"Don't be silly. {value} bytes?? Use a bigger buffer, at least {1024}."); } _baseStream._bufferSize = value; } } public CompressionStrategy Strategy { get { return _baseStream.Strategy; } set { if (_disposed) { throw new ObjectDisposedException("DeflateStream"); } _baseStream.Strategy = value; } } public virtual long TotalIn => _baseStream._z.TotalBytesIn; public virtual long TotalOut => _baseStream._z.TotalBytesOut; public override bool CanRead { get { if (_disposed) { throw new ObjectDisposedException("DeflateStream"); } return _baseStream._stream.CanRead; } } public override bool CanSeek => false; public override bool CanWrite { get { if (_disposed) { throw new ObjectDisposedException("DeflateStream"); } return _baseStream._stream.CanWrite; } } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Writer) { return _baseStream._z.TotalBytesOut; } if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Reader) { return _baseStream._z.TotalBytesIn; } return 0L; } set { throw new NotImplementedException(); } } public DeflateStream(Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, leaveOpen: false) { } public DeflateStream(Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, leaveOpen: false) { } public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } public DeflateStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _innerStream = stream; _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.DEFLATE, leaveOpen); } protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && _baseStream != null) { _baseStream.Dispose(); } _disposed = true; } } finally { base.Dispose(disposing); } } public override void Flush() { if (_disposed) { throw new ObjectDisposedException("DeflateStream"); } _baseStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { if (_disposed) { throw new ObjectDisposedException("DeflateStream"); } return _baseStream.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { if (_disposed) { throw new ObjectDisposedException("DeflateStream"); } _baseStream.Write(buffer, offset, count); } public static byte[] CompressString(string s) { using MemoryStream memoryStream = new MemoryStream(); Stream compressor = new DeflateStream(memoryStream, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return memoryStream.ToArray(); } public static byte[] CompressBuffer(byte[] b) { using MemoryStream memoryStream = new MemoryStream(); Stream compressor = new DeflateStream(memoryStream, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressBuffer(b, compressor); return memoryStream.ToArray(); } public static string UncompressString(byte[] compressed) { using MemoryStream stream = new MemoryStream(compressed); Stream decompressor = new DeflateStream(stream, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } public static byte[] UncompressBuffer(byte[] compressed) { using MemoryStream stream = new MemoryStream(compressed); Stream decompressor = new DeflateStream(stream, CompressionMode.Decompress); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } public class GZipStream : Stream { public DateTime? LastModified; private int _headerByteCount; internal ZlibBaseStream _baseStream; private bool _disposed; private bool _firstReadDone; private string _FileName; private string _Comment; private int _Crc32; internal static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal static readonly Encoding iso8859dash1 = Encoding.GetEncoding("iso-8859-1"); public string Comment { get { return _Comment; } set { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } _Comment = value; } } public string FileName { get { return _FileName; } set { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } _FileName = value; if (_FileName != null) { if (_FileName.IndexOf("/") != -1) { _FileName = _FileName.Replace("/", "\\"); } if (_FileName.EndsWith("\\")) { throw new Exception("Illegal filename"); } if (_FileName.IndexOf("\\") != -1) { _FileName = Path.GetFileName(_FileName); } } } } public int Crc32 => _Crc32; public virtual FlushType FlushMode { get { return _baseStream._flushMode; } set { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } _baseStream._flushMode = value; } } public int BufferSize { get { return _baseStream._bufferSize; } set { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } if (_baseStream._workingBuffer != null) { throw new ZlibException("The working buffer is already set."); } if (value < 1024) { throw new ZlibException($"Don't be silly. {value} bytes?? Use a bigger buffer, at least {1024}."); } _baseStream._bufferSize = value; } } public virtual long TotalIn => _baseStream._z.TotalBytesIn; public virtual long TotalOut => _baseStream._z.TotalBytesOut; public override bool CanRead { get { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } return _baseStream._stream.CanRead; } } public override bool CanSeek => false; public override bool CanWrite { get { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } return _baseStream._stream.CanWrite; } } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Writer) { return _baseStream._z.TotalBytesOut + _headerByteCount; } if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Reader) { return _baseStream._z.TotalBytesIn + _baseStream._gzipHeaderByteCount; } return 0L; } set { throw new NotImplementedException(); } } public GZipStream(Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, leaveOpen: false) { } public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, leaveOpen: false) { } public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, leaveOpen); } protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && _baseStream != null) { _baseStream.Dispose(); _Crc32 = _baseStream.Crc32; } _disposed = true; } } finally { base.Dispose(disposing); } } public override void Flush() { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } _baseStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } int result = _baseStream.Read(buffer, offset, count); if (!_firstReadDone) { _firstReadDone = true; FileName = _baseStream._GzipFileName; Comment = _baseStream._GzipComment; } return result; } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { if (_disposed) { throw new ObjectDisposedException("GZipStream"); } if (_baseStream._streamMode == ZlibBaseStream.StreamMode.Undefined) { if (!_baseStream._wantCompress) { throw new InvalidOperationException(); } _headerByteCount = EmitHeader(); } _baseStream.Write(buffer, offset, count); } private int EmitHeader() { byte[] array = ((Comment == null) ? null : iso8859dash1.GetBytes(Comment)); byte[] array2 = ((FileName == null) ? null : iso8859dash1.GetBytes(FileName)); int num = ((Comment != null) ? (array.Length + 1) : 0); int num2 = ((FileName != null) ? (array2.Length + 1) : 0); byte[] array3 = new byte[10 + num + num2]; int num3 = 0; array3[num3++] = 31; array3[num3++] = 139; array3[num3++] = 8; byte b = 0; if (Comment != null) { b = (byte)(b ^ 0x10u); } if (FileName != null) { b = (byte)(b ^ 8u); } array3[num3++] = b; if (!LastModified.HasValue) { LastModified = DateTime.Now; } Array.Copy(BitConverter.GetBytes((int)(LastModified.Value - _unixEpoch).TotalSeconds), 0, array3, num3, 4); num3 += 4; array3[num3++] = 0; array3[num3++] = byte.MaxValue; if (num2 != 0) { Array.Copy(array2, 0, array3, num3, num2 - 1); num3 += num2 - 1; array3[num3++] = 0; } if (num != 0) { Array.Copy(array, 0, array3, num3, num - 1); num3 += num - 1; array3[num3++] = 0; } _baseStream._stream.Write(array3, 0, array3.Length); return array3.Length; } public static byte[] CompressString(string s) { using MemoryStream memoryStream = new MemoryStream(); Stream compressor = new GZipStream(memoryStream, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return memoryStream.ToArray(); } public static byte[] CompressBuffer(byte[] b) { using MemoryStream memoryStream = new MemoryStream(); Stream compressor = new GZipStream(memoryStream, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressBuffer(b, compressor); return memoryStream.ToArray(); } public static string UncompressString(byte[] compressed) { using MemoryStream stream = new MemoryStream(compressed); Stream decompressor = new GZipStream(stream, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } public static byte[] UncompressBuffer(byte[] compressed) { using MemoryStream stream = new MemoryStream(compressed); Stream decompressor = new GZipStream(stream, CompressionMode.Decompress); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } internal sealed class InflateBlocks { private enum InflateBlockMode { TYPE, LENS, STORED, TABLE, BTREE, DTREE, CODES, DRY, DONE, BAD } private const int MANY = 1440; internal static readonly int[] border = new int[19] { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; private InflateBlockMode mode; internal int left; internal int table; internal int index; internal int[] blens; internal int[] bb = new int[1]; internal int[] tb = new int[1]; internal InflateCodes codes = new InflateCodes(); internal int last; internal ZlibCodec _codec; internal int bitk; internal int bitb; internal int[] hufts; internal byte[] window; internal int end; internal int readAt; internal int writeAt; internal object checkfn; internal uint check; internal InfTree inftree = new InfTree(); internal InflateBlocks(ZlibCodec codec, object checkfn, int w) { _codec = codec; hufts = new int[4320]; window = new byte[w]; end = w; this.checkfn = checkfn; mode = InflateBlockMode.TYPE; Reset(); } internal uint Reset() { uint result = check; mode = InflateBlockMode.TYPE; bitk = 0; bitb = 0; readAt = (writeAt = 0); if (checkfn != null) { _codec._Adler32 = (check = Adler.Adler32(0u, null, 0, 0)); } return result; } internal int Process(int r) { int num = _codec.NextIn; int num2 = _codec.AvailableBytesIn; int num3 = bitb; int i = bitk; int num4 = writeAt; int num5 = ((num4 < readAt) ? (readAt - num4 - 1) : (end - num4)); while (true) { switch (mode) { case InflateBlockMode.TYPE: { for (; i < 3; i += 8) { if (num2 != 0) { r = 0; num2--; num3 |= (_codec.InputBuffer[num++] & 0xFF) << i; continue; } bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } int num6 = num3 & 7; last = num6 & 1; switch ((uint)(num6 >>> 1)) { case 0u: num3 >>= 3; i -= 3; num6 = i & 7; num3 >>= num6; i -= num6; mode = InflateBlockMode.LENS; break; case 1u: { int[] array = new int[1]; int[] array2 = new int[1]; int[][] array3 = new int[1][]; int[][] array4 = new int[1][]; InfTree.inflate_trees_fixed(array, array2, array3, array4, _codec); codes.Init(array[0], array2[0], array3[0], 0, array4[0], 0); num3 >>= 3; i -= 3; mode = InflateBlockMode.CODES; break; } case 2u: num3 >>= 3; i -= 3; mode = InflateBlockMode.TABLE; break; case 3u: num3 >>= 3; i -= 3; mode = InflateBlockMode.BAD; _codec.Message = "invalid block type"; r = -3; bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } break; } case InflateBlockMode.LENS: for (; i < 32; i += 8) { if (num2 != 0) { r = 0; num2--; num3 |= (_codec.InputBuffer[num++] & 0xFF) << i; continue; } bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } if (((~num3 >> 16) & 0xFFFF) != (num3 & 0xFFFF)) { mode = InflateBlockMode.BAD; _codec.Message = "invalid stored block lengths"; r = -3; bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } left = num3 & 0xFFFF; num3 = (i = 0); mode = ((left != 0) ? InflateBlockMode.STORED : ((last != 0) ? InflateBlockMode.DRY : InflateBlockMode.TYPE)); break; case InflateBlockMode.STORED: { if (num2 == 0) { bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } if (num5 == 0) { if (num4 == end && readAt != 0) { num4 = 0; num5 = ((num4 < readAt) ? (readAt - num4 - 1) : (end - num4)); } if (num5 == 0) { writeAt = num4; r = Flush(r); num4 = writeAt; num5 = ((num4 < readAt) ? (readAt - num4 - 1) : (end - num4)); if (num4 == end && readAt != 0) { num4 = 0; num5 = ((num4 < readAt) ? (readAt - num4 - 1) : (end - num4)); } if (num5 == 0) { bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } } } r = 0; int num6 = left; if (num6 > num2) { num6 = num2; } if (num6 > num5) { num6 = num5; } Array.Copy(_codec.InputBuffer, num, window, num4, num6); num += num6; num2 -= num6; num4 += num6; num5 -= num6; if ((left -= num6) == 0) { mode = ((last != 0) ? InflateBlockMode.DRY : InflateBlockMode.TYPE); } break; } case InflateBlockMode.TABLE: { for (; i < 14; i += 8) { if (num2 != 0) { r = 0; num2--; num3 |= (_codec.InputBuffer[num++] & 0xFF) << i; continue; } bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } int num6 = (table = num3 & 0x3FFF); if ((num6 & 0x1F) > 29 || ((num6 >> 5) & 0x1F) > 29) { mode = InflateBlockMode.BAD; _codec.Message = "too many length or distance symbols"; r = -3; bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } num6 = 258 + (num6 & 0x1F) + ((num6 >> 5) & 0x1F); if (blens == null || blens.Length < num6) { blens = new int[num6]; } else { Array.Clear(blens, 0, num6); } num3 >>= 14; i -= 14; index = 0; mode = InflateBlockMode.BTREE; goto case InflateBlockMode.BTREE; } case InflateBlockMode.BTREE: { while (index < 4 + (table >> 10)) { for (; i < 3; i += 8) { if (num2 != 0) { r = 0; num2--; num3 |= (_codec.InputBuffer[num++] & 0xFF) << i; continue; } bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } blens[border[index++]] = num3 & 7; num3 >>= 3; i -= 3; } while (index < 19) { blens[border[index++]] = 0; } bb[0] = 7; int num6 = inftree.inflate_trees_bits(blens, bb, tb, hufts, _codec); if (num6 != 0) { r = num6; if (r == -3) { blens = null; mode = InflateBlockMode.BAD; } bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } index = 0; mode = InflateBlockMode.DTREE; goto case InflateBlockMode.DTREE; } case InflateBlockMode.DTREE: { int num6; while (true) { num6 = table; if (index >= 258 + (num6 & 0x1F) + ((num6 >> 5) & 0x1F)) { break; } for (num6 = bb[0]; i < num6; i += 8) { if (num2 != 0) { r = 0; num2--; num3 |= (_codec.InputBuffer[num++] & 0xFF) << i; continue; } bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } num6 = hufts[(tb[0] + (num3 & InternalInflateConstants.InflateMask[num6])) * 3 + 1]; int num7 = hufts[(tb[0] + (num3 & InternalInflateConstants.InflateMask[num6])) * 3 + 2]; if (num7 < 16) { num3 >>= num6; i -= num6; blens[index++] = num7; continue; } int num8 = ((num7 == 18) ? 7 : (num7 - 14)); int num9 = ((num7 == 18) ? 11 : 3); for (; i < num6 + num8; i += 8) { if (num2 != 0) { r = 0; num2--; num3 |= (_codec.InputBuffer[num++] & 0xFF) << i; continue; } bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } num3 >>= num6; i -= num6; num9 += num3 & InternalInflateConstants.InflateMask[num8]; num3 >>= num8; i -= num8; num8 = index; num6 = table; if (num8 + num9 > 258 + (num6 & 0x1F) + ((num6 >> 5) & 0x1F) || (num7 == 16 && num8 < 1)) { blens = null; mode = InflateBlockMode.BAD; _codec.Message = "invalid bit length repeat"; r = -3; bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } num7 = ((num7 == 16) ? blens[num8 - 1] : 0); do { blens[num8++] = num7; } while (--num9 != 0); index = num8; } tb[0] = -1; int[] array5 = new int[1] { 9 }; int[] array6 = new int[1] { 6 }; int[] array7 = new int[1]; int[] array8 = new int[1]; num6 = table; num6 = inftree.inflate_trees_dynamic(257 + (num6 & 0x1F), 1 + ((num6 >> 5) & 0x1F), blens, array5, array6, array7, array8, hufts, _codec); if (num6 != 0) { if (num6 == -3) { blens = null; mode = InflateBlockMode.BAD; } r = num6; bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } codes.Init(array5[0], array6[0], hufts, array7[0], hufts, array8[0]); mode = InflateBlockMode.CODES; goto case InflateBlockMode.CODES; } case InflateBlockMode.CODES: bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; r = codes.Process(this, r); if (r != 1) { return Flush(r); } r = 0; num = _codec.NextIn; num2 = _codec.AvailableBytesIn; num3 = bitb; i = bitk; num4 = writeAt; num5 = ((num4 < readAt) ? (readAt - num4 - 1) : (end - num4)); if (last == 0) { mode = InflateBlockMode.TYPE; break; } mode = InflateBlockMode.DRY; goto case InflateBlockMode.DRY; case InflateBlockMode.DRY: writeAt = num4; r = Flush(r); num4 = writeAt; num5 = ((num4 < readAt) ? (readAt - num4 - 1) : (end - num4)); if (readAt != writeAt) { bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } mode = InflateBlockMode.DONE; goto case InflateBlockMode.DONE; case InflateBlockMode.DONE: r = 1; bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); case InflateBlockMode.BAD: r = -3; bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); default: r = -2; bitb = num3; bitk = i; _codec.AvailableBytesIn = num2; _codec.TotalBytesIn += num - _codec.NextIn; _codec.NextIn = num; writeAt = num4; return Flush(r); } } } internal void Free() { Reset(); window = null; hufts = null; } internal void SetDictionary(byte[] d, int start, int n) { Array.Copy(d, start, window, 0, n); readAt = (writeAt = n); } internal int SyncPoint() { if (mode != InflateBlockMode.LENS) { return 0; } return 1; } internal int Flush(int r) { for (int i = 0; i < 2; i++) { int num = ((i != 0) ? (writeAt - readAt) : (((readAt <= writeAt) ? writeAt : end) - readAt)); if (num == 0) { if (r == -5) { r = 0; } return r; } if (num > _codec.AvailableBytesOut) { num = _codec.AvailableBytesOut; } if (num != 0 && r == -5) { r = 0; } _codec.AvailableBytesOut -= num; _codec.TotalBytesOut += num; if (checkfn != null) { _codec._Adler32 = (check = Adler.Adler32(check, window, readAt, num)); } Array.Copy(window, readAt, _codec.OutputBuffer, _codec.NextOut, num); _codec.NextOut += num; readAt += num; if (readAt == end && i == 0) { readAt = 0; if (writeAt == end) { writeAt = 0; } } else { i++; } } return r; } } internal static class InternalInflateConstants { internal static readonly int[] InflateMask = new int[17] { 0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535 }; } internal sealed class InflateCodes { private const int START = 0; private const int LEN = 1; private const int LENEXT = 2; private const int DIST = 3; private const int DISTEXT = 4; private const int COPY = 5; private const int LIT = 6; private const int WASH = 7; private const int END = 8; private const int BADCODE = 9; internal int mode; internal int len; internal int[] tree; internal int tree_index; internal int need; internal int lit; internal int bitsToGet; internal int dist; internal byte lbits; internal byte dbits; internal int[] ltree; internal int ltree_index; internal int[] dtree; internal int dtree_index; internal InflateCodes() { } internal void Init(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index) { mode = 0; lbits = (byte)bl; dbits = (byte)bd; ltree = tl; ltree_index = tl_index; dtree = td; dtree_index = td_index; tree = null; } internal int Process(InflateBlocks blocks, int r) { int num = 0; int num2 = 0; int num3 = 0; ZlibCodec codec = blocks._codec; num3 = codec.NextIn; int num4 = codec.AvailableBytesIn; num = blocks.bitb; num2 = blocks.bitk; int num5 = blocks.writeAt; int num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); while (true) { switch (mode) { case 0: if (num6 >= 258 && num4 >= 10) { blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; r = InflateFast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, blocks, codec); num3 = codec.NextIn; num4 = codec.AvailableBytesIn; num = blocks.bitb; num2 = blocks.bitk; num5 = blocks.writeAt; num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); if (r != 0) { mode = ((r == 1) ? 7 : 9); break; } } need = lbits; tree = ltree; tree_index = ltree_index; mode = 1; goto case 1; case 1: { int num7; for (num7 = need; num2 < num7; num2 += 8) { if (num4 != 0) { r = 0; num4--; num |= (codec.InputBuffer[num3++] & 0xFF) << num2; continue; } blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } int num8 = (tree_index + (num & InternalInflateConstants.InflateMask[num7])) * 3; num >>= tree[num8 + 1]; num2 -= tree[num8 + 1]; int num9 = tree[num8]; if (num9 == 0) { lit = tree[num8 + 2]; mode = 6; break; } if (((uint)num9 & 0x10u) != 0) { bitsToGet = num9 & 0xF; len = tree[num8 + 2]; mode = 2; break; } if ((num9 & 0x40) == 0) { need = num9; tree_index = num8 / 3 + tree[num8 + 2]; break; } if (((uint)num9 & 0x20u) != 0) { mode = 7; break; } mode = 9; codec.Message = "invalid literal/length code"; r = -3; blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } case 2: { int num7; for (num7 = bitsToGet; num2 < num7; num2 += 8) { if (num4 != 0) { r = 0; num4--; num |= (codec.InputBuffer[num3++] & 0xFF) << num2; continue; } blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } len += num & InternalInflateConstants.InflateMask[num7]; num >>= num7; num2 -= num7; need = dbits; tree = dtree; tree_index = dtree_index; mode = 3; goto case 3; } case 3: { int num7; for (num7 = need; num2 < num7; num2 += 8) { if (num4 != 0) { r = 0; num4--; num |= (codec.InputBuffer[num3++] & 0xFF) << num2; continue; } blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } int num8 = (tree_index + (num & InternalInflateConstants.InflateMask[num7])) * 3; num >>= tree[num8 + 1]; num2 -= tree[num8 + 1]; int num9 = tree[num8]; if (((uint)num9 & 0x10u) != 0) { bitsToGet = num9 & 0xF; dist = tree[num8 + 2]; mode = 4; break; } if ((num9 & 0x40) == 0) { need = num9; tree_index = num8 / 3 + tree[num8 + 2]; break; } mode = 9; codec.Message = "invalid distance code"; r = -3; blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } case 4: { int num7; for (num7 = bitsToGet; num2 < num7; num2 += 8) { if (num4 != 0) { r = 0; num4--; num |= (codec.InputBuffer[num3++] & 0xFF) << num2; continue; } blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } dist += num & InternalInflateConstants.InflateMask[num7]; num >>= num7; num2 -= num7; mode = 5; goto case 5; } case 5: { int i; for (i = num5 - dist; i < 0; i += blocks.end) { } while (len != 0) { if (num6 == 0) { if (num5 == blocks.end && blocks.readAt != 0) { num5 = 0; num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); } if (num6 == 0) { blocks.writeAt = num5; r = blocks.Flush(r); num5 = blocks.writeAt; num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); if (num5 == blocks.end && blocks.readAt != 0) { num5 = 0; num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); } if (num6 == 0) { blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } } } blocks.window[num5++] = blocks.window[i++]; num6--; if (i == blocks.end) { i = 0; } len--; } mode = 0; break; } case 6: if (num6 == 0) { if (num5 == blocks.end && blocks.readAt != 0) { num5 = 0; num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); } if (num6 == 0) { blocks.writeAt = num5; r = blocks.Flush(r); num5 = blocks.writeAt; num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); if (num5 == blocks.end && blocks.readAt != 0) { num5 = 0; num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); } if (num6 == 0) { blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } } } r = 0; blocks.window[num5++] = (byte)lit; num6--; mode = 0; break; case 7: if (num2 > 7) { num2 -= 8; num4++; num3--; } blocks.writeAt = num5; r = blocks.Flush(r); num5 = blocks.writeAt; num6 = ((num5 < blocks.readAt) ? (blocks.readAt - num5 - 1) : (blocks.end - num5)); if (blocks.readAt != blocks.writeAt) { blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } mode = 8; goto case 8; case 8: r = 1; blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); case 9: r = -3; blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); default: r = -2; blocks.bitb = num; blocks.bitk = num2; codec.AvailableBytesIn = num4; codec.TotalBytesIn += num3 - codec.NextIn; codec.NextIn = num3; blocks.writeAt = num5; return blocks.Flush(r); } } } internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, InflateBlocks s, ZlibCodec z) { int nextIn = z.NextIn; int num = z.AvailableBytesIn; int num2 = s.bitb; int num3 = s.bitk; int num4 = s.writeAt; int num5 = ((num4 < s.readAt) ? (s.readAt - num4 - 1) : (s.end - num4)); int num6 = InternalInflateConstants.InflateMask[bl]; int num7 = InternalInflateConstants.InflateMask[bd]; int num12; while (true) { if (num3 < 20) { num--; num2 |= (z.InputBuffer[nextIn++] & 0xFF) << num3; num3 += 8; continue; } int num8 = num2 & num6; int[] array = tl; int num9 = tl_index; int num10 = (num9 + num8) * 3; int num11; if ((num11 = array[num10]) == 0) { num2 >>= array[num10 + 1]; num3 -= array[num10 + 1]; s.window[num4++] = (byte)array[num10 + 2]; num5--; } else { while (true) { num2 >>= array[num10 + 1]; num3 -= array[num10 + 1]; if (((uint)num11 & 0x10u) != 0) { num11 &= 0xF; num12 = array[num10 + 2] + (num2 & InternalInflateConstants.InflateMask[num11]); num2 >>= num11; for (num3 -= num11; num3 < 15; num3 += 8) { num--; num2 |= (z.InputBuffer[nextIn++] & 0xFF) << num3; } num8 = num2 & num7; array = td; num9 = td_index; num10 = (num9 + num8) * 3; num11 = array[num10]; while (true) { num2 >>= array[num10 + 1]; num3 -= array[num10 + 1]; if (((uint)num11 & 0x10u) != 0) { break; } if ((num11 & 0x40) == 0) { num8 += array[num10 + 2]; num8 += num2 & InternalInflateConstants.InflateMask[num11]; num10 = (num9 + num8) * 3; num11 = array[num10]; continue; } z.Message = "invalid distance code"; num12 = z.AvailableBytesIn - num; num12 = ((num3 >> 3 < num12) ? (num3 >> 3) : num12); num += num12; nextIn -= num12; num3 -= num12 << 3; s.bitb = num2; s.bitk = num3; z.AvailableBytesIn = num; z.TotalBytesIn += nextIn - z.NextIn; z.NextIn = nextIn; s.writeAt = num4; return -3; } for (num11 &= 0xF; num3 < num11; num3 += 8) { num--; num2 |= (z.InputBuffer[nextIn++] & 0xFF) << num3; } int num13 = array[num10 + 2] + (num2 & InternalInflateConstants.InflateMask[num11]); num2 >>= num11; num3 -= num11; num5 -= num12; int num14; if (num4 >= num13) { num14 = num4 - num13; if (num4 - num14 > 0 && 2 > num4 - num14) { s.window[num4++] = s.window[num14++]; s.window[num4++] = s.window[num14++]; num12 -= 2; } else { Array.Copy(s.window, num14, s.window, num4, 2); num4 += 2; num14 += 2; num12 -= 2; } } else { num14 = num4 - num13; do { num14 += s.end; } while (num14 < 0); num11 = s.end - num14; if (num12 > num11) { num12 -= num11; if (num4 - num14 > 0 && num11 > num4 - num14) { do { s.window[num4++] = s.window[num14++]; } while (--num11 != 0); } else { Array.Copy(s.window, num14, s.window, num4, num11); num4 += num11; num14 += num11; num11 = 0; } num14 = 0; } } if (num4 - num14 > 0 && num12 > num4 - num14) { do { s.window[num4++] = s.window[num14++]; } while (--num12 != 0); break; } Array.Copy(s.window, num14, s.window, num4, num12); num4 += num12; num14 += num12; num12 = 0; break; } if ((num11 & 0x40) == 0) { num8 += array[num10 + 2]; num8 += num2 & InternalInflateConstants.InflateMask[num11]; num10 = (num9 + num8) * 3; if ((num11 = array[num10]) == 0) { num2 >>= array[num10 + 1]; num3 -= array[num10 + 1]; s.window[num4++] = (byte)array[num10 + 2]; num5--; break; } continue; } if (((uint)num11 & 0x20u) != 0) { num12 = z.AvailableBytesIn - num; num12 = ((num3 >> 3 < num12) ? (num3 >> 3) : num12); num += num12; nextIn -= num12; num3 -= num12 << 3; s.bitb = num2; s.bitk = num3; z.AvailableBytesIn = num; z.TotalBytesIn += nextIn - z.NextIn; z.NextIn = nextIn; s.writeAt = num4; return 1; } z.Message = "invalid literal/length code"; num12 = z.AvailableBytesIn - num; num12 = ((num3 >> 3 < num12) ? (num3 >> 3) : num12); num += num12; nextIn -= num12; num3 -= num12 << 3; s.bitb = num2; s.bitk = num3; z.AvailableBytesIn = num; z.TotalBytesIn += nextIn - z.NextIn; z.NextIn = nextIn; s.writeAt = num4; return -3; } } if (num5 < 258 || num < 10) { break; } } num12 = z.AvailableBytesIn - num; num12 = ((num3 >> 3 < num12) ? (num3 >> 3) : num12); num += num12; nextIn -= num12; num3 -= num12 << 3; s.bitb = num2; s.bitk = num3; z.AvailableBytesIn = num; z.TotalBytesIn += nextIn - z.NextIn; z.NextIn = nextIn; s.writeAt = num4; return 0; } } internal sealed class InflateManager { private enum InflateManagerMode { METHOD, FLAG, DICT4, DICT3, DICT2, DICT1, DICT0, BLOCKS, CHECK4, CHECK3, CHECK2, CHECK1, DONE, BAD } private const int PRESET_DICT = 32; private const int Z_DEFLATED = 8; private InflateManagerMode mode; internal ZlibCodec _codec; internal int method; internal uint computedCheck; internal uint expectedCheck; internal int marker; private bool _handleRfc1950HeaderBytes = true; internal int wbits; internal InflateBlocks blocks; private static readonly byte[] mark = new byte[4] { 0, 0, 255, 255 }; internal bool HandleRfc1950HeaderBytes { get { return _handleRfc1950HeaderBytes; } set { _handleRfc1950HeaderBytes = value; } } public InflateManager() { } public InflateManager(bool expectRfc1950HeaderBytes) { _handleRfc1950HeaderBytes = expectRfc1950HeaderBytes; } internal int Reset() { _codec.TotalBytesIn = (_codec.TotalBytesOut = 0L); _codec.Message = null; mode = ((!HandleRfc1950HeaderBytes) ? InflateManagerMode.BLOCKS : InflateManagerMode.METHOD); blocks.Reset(); return 0; } internal int End() { if (blocks != null) { blocks.Free(); } blocks = null; return 0; } internal int Initialize(ZlibCodec codec, int w) { _codec = codec; _codec.Message = null; blocks = null; if (w < 8 || w > 15) { End(); throw new ZlibException("Bad window size."); } wbits = w; blocks = new InflateBlocks(codec, HandleRfc1950HeaderBytes ? this : null, 1 << w); Reset(); return 0; } internal int Inflate(FlushType flush) { if (_codec.InputBuffer == null) { throw new ZlibException("InputBuffer is null. "); } int num = 0; int num2 = -5; while (true) { switch (mode) { case InflateManagerMode.METHOD: if (_codec.AvailableBytesIn == 0) { return num2; } num2 = num; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; if (((method = _codec.InputBuffer[_codec.NextIn++]) & 0xF) != 8) { mode = InflateManagerMode.BAD; _codec.Message = $"unknown compression method (0x{method:X2})"; marker = 5; } else if ((method >> 4) + 8 > wbits) { mode = InflateManagerMode.BAD; _codec.Message = $"invalid window size ({(method >> 4) + 8})"; marker = 5;
patchers/I18N.dll
Decompiled 6 months agousing System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../../mono.pub")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: PermissionSet(SecurityAction.RequestMinimum, XML = "<PermissionSet class=\"System.Security.PermissionSet\"\nversion=\"1\">\n<IPermission class=\"System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\nversion=\"1\"\nFlags=\"SkipVerification\"/>\n</PermissionSet>\n")] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] internal static class Consts { public const string MonoVersion = "2.6.5.0"; public const string MonoCompany = "MONO development team"; public const string MonoProduct = "MONO Common language infrastructure"; public const string MonoCopyright = "(c) various MONO Authors"; public const string FxVersion = "2.0.0.0"; public const string VsVersion = "8.0.0.0"; public const string FxFileVersion = "2.0.50727.1433"; public const string VsFileVersion = "8.0.50727.1433"; public const string AssemblyI18N = "I18N, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } namespace I18N.Common; [Serializable] public abstract class ByteEncoding : MonoEncoding { protected char[] toChars; protected string encodingName; protected string bodyName; protected string headerName; protected string webName; protected bool isBrowserDisplay; protected bool isBrowserSave; protected bool isMailNewsDisplay; protected bool isMailNewsSave; protected int windowsCodePage; private static byte[] isNormalized; private static byte[] isNormalizedComputed; private static byte[] normalization_bytes; public override bool IsSingleByte => true; public override string BodyName => bodyName; public override string EncodingName => encodingName; public override string HeaderName => headerName; public override bool IsBrowserDisplay => isBrowserDisplay; public override bool IsBrowserSave => isBrowserSave; public override bool IsMailNewsDisplay => isMailNewsDisplay; public override bool IsMailNewsSave => isMailNewsSave; public override string WebName => webName; public override int WindowsCodePage => windowsCodePage; protected ByteEncoding(int codePage, char[] toChars, string encodingName, string bodyName, string headerName, string webName, bool isBrowserDisplay, bool isBrowserSave, bool isMailNewsDisplay, bool isMailNewsSave, int windowsCodePage) : base(codePage) { if (toChars.Length != 256) { throw new ArgumentException("toChars"); } this.toChars = toChars; this.encodingName = encodingName; this.bodyName = bodyName; this.headerName = headerName; this.webName = webName; this.isBrowserDisplay = isBrowserDisplay; this.isBrowserSave = isBrowserSave; this.isMailNewsDisplay = isMailNewsDisplay; this.isMailNewsSave = isMailNewsSave; this.windowsCodePage = windowsCodePage; } public override bool IsAlwaysNormalized(NormalizationForm form) { if (form != NormalizationForm.FormC) { return false; } if (isNormalized == null) { isNormalized = new byte[8192]; } if (isNormalizedComputed == null) { isNormalizedComputed = new byte[8192]; } if (normalization_bytes == null) { normalization_bytes = new byte[256]; lock (normalization_bytes) { for (int i = 0; i < 256; i++) { normalization_bytes[i] = (byte)i; } } } byte b = (byte)(1 << CodePage % 8); if ((isNormalizedComputed[CodePage / 8] & b) == 0) { Encoding encoding = Clone() as Encoding; encoding.DecoderFallback = new DecoderReplacementFallback(string.Empty); string @string = encoding.GetString(normalization_bytes); if (@string != @string.Normalize(form)) { isNormalized[CodePage / 8] |= b; } isNormalizedComputed[CodePage / 8] |= b; } return (isNormalized[CodePage / 8] & b) == 0; } public override int GetByteCount(string s) { if (s == null) { throw new ArgumentNullException("s"); } return s.Length; } public unsafe override int GetByteCountImpl(char* chars, int count) { return count; } protected unsafe abstract void ToBytes(char* chars, int charCount, byte* bytes, int byteCount); protected unsafe virtual void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { //IL_0027->IL002e: Incompatible stack types: I vs Ref //IL_0046->IL004e: Incompatible stack types: I vs Ref if (charCount == 0 || bytes.Length == byteIndex) { return; } fixed (char* ptr = &System.Runtime.CompilerServices.Unsafe.AsRef<char>((char*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref chars != null && chars.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<char, ?>(ref chars[0]) : ref *(?*)null))) { fixed (byte* ptr2 = &System.Runtime.CompilerServices.Unsafe.AsRef<byte>((byte*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref bytes != null && bytes.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<byte, ?>(ref bytes[0]) : ref *(?*)null))) { ToBytes((char*)((byte*)ptr + charIndex * 2), charCount, ptr2 + byteIndex, bytes.Length - byteIndex); } } } public unsafe override int GetBytesImpl(char* chars, int charCount, byte* bytes, int byteCount) { ToBytes(chars, charCount, bytes, byteCount); return charCount; } public override int GetCharCount(byte[] bytes, int index, int count) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (index < 0 || index > bytes.Length) { throw new ArgumentOutOfRangeException("index", Strings.GetString("ArgRange_Array")); } if (count < 0 || count > bytes.Length - index) { throw new ArgumentOutOfRangeException("count", Strings.GetString("ArgRange_Array")); } return count; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", Strings.GetString("ArgRange_Array")); } if (byteCount < 0 || byteCount > bytes.Length - byteIndex) { throw new ArgumentOutOfRangeException("byteCount", Strings.GetString("ArgRange_Array")); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", Strings.GetString("ArgRange_Array")); } if (chars.Length - charIndex < byteCount) { throw new ArgumentException(Strings.GetString("Arg_InsufficientSpace")); } int num = byteCount; char[] array = toChars; while (num-- > 0) { chars[charIndex++] = array[bytes[byteIndex++]]; } return byteCount; } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", Strings.GetString("ArgRange_NonNegative")); } return charCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", Strings.GetString("ArgRange_NonNegative")); } return byteCount; } public unsafe override string GetString(byte[] bytes, int index, int count) { //IL_0086->IL008d: Incompatible stack types: I vs Ref //IL_00ba->IL00c6: Incompatible stack types: I vs Ref if (bytes == null) { throw new ArgumentNullException("bytes"); } if (index < 0 || index > bytes.Length) { throw new ArgumentOutOfRangeException("index", Strings.GetString("ArgRange_Array")); } if (count < 0 || count > bytes.Length - index) { throw new ArgumentOutOfRangeException("count", Strings.GetString("ArgRange_Array")); } if (count == 0) { return string.Empty; } string text = new string('\0', count); fixed (byte* ptr = &System.Runtime.CompilerServices.Unsafe.AsRef<byte>((byte*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref bytes != null && bytes.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<byte, ?>(ref bytes[0]) : ref *(?*)null))) { fixed (char* ptr3 = text) { fixed (char* ptr5 = &System.Runtime.CompilerServices.Unsafe.AsRef<char>((char*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref toChars != null && toChars.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<char, ?>(ref toChars[0]) : ref *(?*)null))) { byte* ptr2 = ptr + index; char* ptr4 = ptr3; while (count-- != 0) { *(ptr4++) = ptr5[(int)(*(ptr2++))]; } } } } return text; } public override string GetString(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } return GetString(bytes, 0, bytes.Length); } } public sealed class Handlers { public static readonly string[] List = new string[173] { "I18N.CJK.CP932", "I18N.CJK.CP936", "I18N.CJK.CP949", "I18N.CJK.CP950", "I18N.CJK.CP50220", "I18N.CJK.CP50221", "I18N.CJK.CP50222", "I18N.CJK.CP51932", "I18N.CJK.CP51949", "I18N.CJK.CP54936", "I18N.CJK.ENCbig5", "I18N.CJK.ENCgb2312", "I18N.CJK.ENCshift_jis", "I18N.CJK.ENCiso_2022_jp", "I18N.CJK.ENCeuc_jp", "I18N.CJK.ENCeuc_kr", "I18N.CJK.ENCuhc", "I18N.CJK.ENCgb18030", "I18N.MidEast.CP1254", "I18N.MidEast.ENCwindows_1254", "I18N.MidEast.CP1255", "I18N.MidEast.ENCwindows_1255", "I18N.MidEast.CP1256", "I18N.MidEast.ENCwindows_1256", "I18N.MidEast.CP28596", "I18N.MidEast.ENCiso_8859_6", "I18N.MidEast.CP28598", "I18N.MidEast.ENCiso_8859_8", "I18N.MidEast.CP28599", "I18N.MidEast.ENCiso_8859_9", "I18N.MidEast.CP38598", "I18N.MidEast.ENCwindows_38598", "I18N.Other.CP1251", "I18N.Other.ENCwindows_1251", "I18N.Other.CP1257", "I18N.Other.ENCwindows_1257", "I18N.Other.CP1258", "I18N.Other.ENCwindows_1258", "I18N.Other.CP20866", "I18N.Other.ENCkoi8_r", "I18N.Other.CP21866", "I18N.Other.ENCkoi8_u", "I18N.Other.CP28594", "I18N.Other.ENCiso_8859_4", "I18N.Other.CP28595", "I18N.Other.ENCiso_8859_5", "I18N.Other.ISCIIEncoding", "I18N.Other.CP57002", "I18N.Other.CP57003", "I18N.Other.CP57004", "I18N.Other.CP57005", "I18N.Other.CP57006", "I18N.Other.CP57007", "I18N.Other.CP57008", "I18N.Other.CP57009", "I18N.Other.CP57010", "I18N.Other.CP57011", "I18N.Other.ENCx_iscii_de", "I18N.Other.ENCx_iscii_be", "I18N.Other.ENCx_iscii_ta", "I18N.Other.ENCx_iscii_te", "I18N.Other.ENCx_iscii_as", "I18N.Other.ENCx_iscii_or", "I18N.Other.ENCx_iscii_ka", "I18N.Other.ENCx_iscii_ma", "I18N.Other.ENCx_iscii_gu", "I18N.Other.ENCx_iscii_pa", "I18N.Other.CP874", "I18N.Other.ENCwindows_874", "I18N.Rare.CP1026", "I18N.Rare.ENCibm1026", "I18N.Rare.CP1047", "I18N.Rare.ENCibm1047", "I18N.Rare.CP1140", "I18N.Rare.ENCibm01140", "I18N.Rare.CP1141", "I18N.Rare.ENCibm01141", "I18N.Rare.CP1142", "I18N.Rare.ENCibm01142", "I18N.Rare.CP1143", "I18N.Rare.ENCibm01143", "I18N.Rare.CP1144", "I18N.Rare.ENCibm1144", "I18N.Rare.CP1145", "I18N.Rare.ENCibm1145", "I18N.Rare.CP1146", "I18N.Rare.ENCibm1146", "I18N.Rare.CP1147", "I18N.Rare.ENCibm1147", "I18N.Rare.CP1148", "I18N.Rare.ENCibm1148", "I18N.Rare.CP1149", "I18N.Rare.ENCibm1149", "I18N.Rare.CP20273", "I18N.Rare.ENCibm273", "I18N.Rare.CP20277", "I18N.Rare.ENCibm277", "I18N.Rare.CP20278", "I18N.Rare.ENCibm278", "I18N.Rare.CP20280", "I18N.Rare.ENCibm280", "I18N.Rare.CP20284", "I18N.Rare.ENCibm284", "I18N.Rare.CP20285", "I18N.Rare.ENCibm285", "I18N.Rare.CP20290", "I18N.Rare.ENCibm290", "I18N.Rare.CP20297", "I18N.Rare.ENCibm297", "I18N.Rare.CP20420", "I18N.Rare.ENCibm420", "I18N.Rare.CP20424", "I18N.Rare.ENCibm424", "I18N.Rare.CP20871", "I18N.Rare.ENCibm871", "I18N.Rare.CP21025", "I18N.Rare.ENCibm1025", "I18N.Rare.CP37", "I18N.Rare.ENCibm037", "I18N.Rare.CP500", "I18N.Rare.ENCibm500", "I18N.Rare.CP708", "I18N.Rare.ENCasmo_708", "I18N.Rare.CP852", "I18N.Rare.ENCibm852", "I18N.Rare.CP855", "I18N.Rare.ENCibm855", "I18N.Rare.CP857", "I18N.Rare.ENCibm857", "I18N.Rare.CP858", "I18N.Rare.ENCibm00858", "I18N.Rare.CP862", "I18N.Rare.ENCibm862", "I18N.Rare.CP864", "I18N.Rare.ENCibm864", "I18N.Rare.CP866", "I18N.Rare.ENCibm866", "I18N.Rare.CP869", "I18N.Rare.ENCibm869", "I18N.Rare.CP870", "I18N.Rare.ENCibm870", "I18N.Rare.CP875", "I18N.Rare.ENCibm875", "I18N.West.CP10000", "I18N.West.ENCmacintosh", "I18N.West.CP10079", "I18N.West.ENCx_mac_icelandic", "I18N.West.CP1250", "I18N.West.ENCwindows_1250", "I18N.West.CP1252", "I18N.West.ENCwindows_1252", "I18N.West.CP1253", "I18N.West.ENCwindows_1253", "I18N.West.CP28592", "I18N.West.ENCiso_8859_2", "I18N.West.CP28593", "I18N.West.ENCiso_8859_3", "I18N.West.CP28597", "I18N.West.ENCiso_8859_7", "I18N.West.CP28605", "I18N.West.ENCiso_8859_15", "I18N.West.CP437", "I18N.West.ENCibm437", "I18N.West.CP850", "I18N.West.ENCibm850", "I18N.West.CP860", "I18N.West.ENCibm860", "I18N.West.CP861", "I18N.West.ENCibm861", "I18N.West.CP863", "I18N.West.ENCibm863", "I18N.West.CP865", "I18N.West.ENCibm865" }; private static Hashtable aliases; public static string GetAlias(string name) { if (aliases == null) { BuildHash(); } return aliases[name] as string; } private static void BuildHash() { aliases = new Hashtable(new CaseInsensitiveHashCodeProvider(), new CaseInsensitiveComparer()); aliases.Add("arabic", "iso_8859_6"); aliases.Add("csISOLatinArabic", "iso_8859_6"); aliases.Add("ECMA_114", "iso_8859_6"); aliases.Add("ISO_8859_6:1987", "iso_8859_6"); aliases.Add("iso_ir_127", "iso_8859_6"); aliases.Add("cp1256", "windows_1256"); aliases.Add("csISOLatin4", "iso_8859_4"); aliases.Add("ISO_8859_4:1988", "iso_8859_4"); aliases.Add("iso_ir_110", "iso_8859_4"); aliases.Add("l4", "iso_8859_4"); aliases.Add("latin4", "iso_8859_4"); aliases.Add("cp852", "ibm852"); aliases.Add("csISOLatin2", "iso_8859_2"); aliases.Add("iso_8859_2:1987", "iso_8859_2"); aliases.Add("iso8859_2", "iso_8859_2"); aliases.Add("iso_ir_101", "iso_8859_2"); aliases.Add("l2", "iso_8859_2"); aliases.Add("latin2", "iso_8859_2"); aliases.Add("x-cp1250", "windows_1250"); aliases.Add("chinese", "gb2312"); aliases.Add("CN-GB", "gb2312"); aliases.Add("csGB2312", "gb2312"); aliases.Add("csGB231280", "gb2312"); aliases.Add("csISO58GB231280", "gb2312"); aliases.Add("GB_2312_80", "gb2312"); aliases.Add("GB231280", "gb2312"); aliases.Add("GB2312_80", "gb2312"); aliases.Add("GBK", "gb2312"); aliases.Add("iso_ir_58", "gb2312"); aliases.Add("cn-big5", "big5"); aliases.Add("csbig5", "big5"); aliases.Add("x-x-big5", "big5"); aliases.Add("cp866", "ibm866"); aliases.Add("csISOLatin5", "iso_8859_5"); aliases.Add("csISOLatinCyrillic", "iso_8859_5"); aliases.Add("cyrillic", "iso_8859_5"); aliases.Add("ISO_8859_5:1988", "iso_8859_5"); aliases.Add("iso_ir_144", "iso_8859_5"); aliases.Add("l5", "iso_8859_5"); aliases.Add("csKOI8R", "koi8_r"); aliases.Add("koi", "koi8_r"); aliases.Add("koi8", "koi8_r"); aliases.Add("koi8r", "koi8_r"); aliases.Add("koi8ru", "koi8_u"); aliases.Add("x-cp1251", "windows_1251"); aliases.Add("csISOLatinGreek", "iso_8859_7"); aliases.Add("ECMA_118", "iso_8859_7"); aliases.Add("ELOT_928", "iso_8859_7"); aliases.Add("greek", "iso_8859_7"); aliases.Add("greek8", "iso_8859_7"); aliases.Add("ISO_8859_7:1987", "iso_8859_7"); aliases.Add("iso_ir_126", "iso_8859_7"); aliases.Add("csISOLatinHebrew", "iso_8859_8"); aliases.Add("hebrew", "iso_8859_8"); aliases.Add("ISO_8859_8:1988", "iso_8859_8"); aliases.Add("iso_ir_138", "iso_8859_8"); aliases.Add("csShiftJIS", "shift_jis"); aliases.Add("csWindows31J", "shift_jis"); aliases.Add("ms_Kanji", "shift_jis"); aliases.Add("shift-jis", "shift_jis"); aliases.Add("x-ms-cp932", "shift_jis"); aliases.Add("x-sjis", "shift_jis"); aliases.Add("csISOLatin3", "iso_8859_3"); aliases.Add("ISO_8859_3:1988", "iso_8859_3"); aliases.Add("iso_ir_109", "iso_8859_3"); aliases.Add("l3", "iso_8859_3"); aliases.Add("latin3", "iso_8859_3"); aliases.Add("csISOLatin9", "iso_8859_15"); aliases.Add("l9", "iso_8859_15"); aliases.Add("latin9", "iso_8859_15"); aliases.Add("cp437", "ibm437"); aliases.Add("csPC8", "ibm437"); aliases.Add("CodePage437", "ibm437"); aliases.Add("DOS_874", "windows_874"); aliases.Add("iso_8859_11", "windows_874"); aliases.Add("TIS_620", "windows_874"); } } public class Manager { private const string hex = "0123456789abcdef"; private static Manager manager; private Hashtable handlers; private Hashtable active; private Hashtable assemblies; private static readonly object lockobj = new object(); public static Manager PrimaryManager { get { lock (lockobj) { if (manager == null) { manager = new Manager(); } return manager; } } } private Manager() { handlers = new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); active = new Hashtable(16); assemblies = new Hashtable(8); LoadClassList(); } private static string Normalize(string name) { return name.ToLower(CultureInfo.InvariantCulture).Replace('-', '_'); } public Encoding GetEncoding(int codePage) { return Instantiate("CP" + codePage) as Encoding; } public Encoding GetEncoding(string name) { if (name == null) { return null; } string text = name; name = Normalize(name); Encoding encoding = Instantiate("ENC" + name) as Encoding; if (encoding == null) { encoding = Instantiate(name) as Encoding; } if (encoding == null) { string alias = Handlers.GetAlias(name); if (alias != null) { encoding = Instantiate("ENC" + alias) as Encoding; if (encoding == null) { encoding = Instantiate(alias) as Encoding; } } } if (encoding == null) { return null; } if (text.IndexOf('_') > 0 && encoding.WebName.IndexOf('-') > 0) { return null; } if (text.IndexOf('-') > 0 && encoding.WebName.IndexOf('_') > 0) { return null; } return encoding; } public CultureInfo GetCulture(int culture, bool useUserOverride) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("0123456789abcdef"[(culture >> 12) & 0xF]); stringBuilder.Append("0123456789abcdef"[(culture >> 8) & 0xF]); stringBuilder.Append("0123456789abcdef"[(culture >> 4) & 0xF]); stringBuilder.Append("0123456789abcdef"[culture & 0xF]); string text = stringBuilder.ToString(); if (useUserOverride) { object obj = Instantiate("CIDO" + text); if (obj != null) { return obj as CultureInfo; } } return Instantiate("CID" + text) as CultureInfo; } public CultureInfo GetCulture(string name, bool useUserOverride) { if (name == null) { return null; } name = Normalize(name); if (useUserOverride) { object obj = Instantiate("CNO" + name.ToString()); if (obj != null) { return obj as CultureInfo; } } return Instantiate("CN" + name.ToString()) as CultureInfo; } internal object Instantiate(string name) { lock (this) { object obj = active[name]; if (obj != null) { return obj; } string text = (string)handlers[name]; if (text == null) { return null; } Assembly assembly = (Assembly)assemblies[text]; if ((object)assembly == null) { try { AssemblyName name2 = typeof(Manager).Assembly.GetName(); name2.Name = text; assembly = Assembly.Load(name2); } catch (SystemException) { assembly = null; } if ((object)assembly == null) { return null; } assemblies[text] = assembly; } Type type = assembly.GetType(text + "." + name, throwOnError: false, ignoreCase: true); if ((object)type == null) { return null; } try { obj = type.InvokeMember(string.Empty, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null, null, null, null); } catch (MissingMethodException) { return null; } catch (SecurityException) { return null; } active.Add(name, obj); return obj; } } private void LoadClassList() { FileStream file; try { file = Assembly.GetExecutingAssembly().GetFile("I18N-handlers.def"); if (file == null) { LoadInternalClasses(); return; } } catch (FileLoadException) { LoadInternalClasses(); return; } StreamReader streamReader = new StreamReader(file); string text; while ((text = streamReader.ReadLine()) != null) { if (text.Length == 0 || text[0] == '#') { continue; } int num = text.LastIndexOf('.'); if (num != -1) { string key = text.Substring(num + 1); if (!handlers.Contains(key)) { handlers.Add(key, text.Substring(0, num)); } } } streamReader.Close(); } private void LoadInternalClasses() { string[] list = Handlers.List; foreach (string text in list) { int num = text.LastIndexOf('.'); if (num != -1) { string key = text.Substring(num + 1); if (!handlers.Contains(key)) { handlers.Add(key, text.Substring(0, num)); } } } } } [Serializable] public abstract class MonoEncoding : Encoding { private readonly int win_code_page; public override int WindowsCodePage => (win_code_page == 0) ? base.WindowsCodePage : win_code_page; public MonoEncoding(int codePage) : this(codePage, 0) { } public MonoEncoding(int codePage, int windowsCodePage) : base(codePage) { win_code_page = windowsCodePage; } public unsafe void HandleFallback(ref EncoderFallbackBuffer buffer, char* chars, ref int charIndex, ref int charCount, byte* bytes, ref int byteIndex, ref int byteCount) { //IL_00c3->IL00ca: Incompatible stack types: I vs Ref if (buffer == null) { buffer = base.EncoderFallback.CreateFallbackBuffer(); } if (char.IsSurrogate(*(char*)((byte*)chars + charIndex * 2)) && charCount > 0 && char.IsSurrogate(*(char*)((byte*)chars + (charIndex + 1) * 2))) { buffer.Fallback(*(char*)((byte*)chars + charIndex * 2), *(char*)((byte*)chars + (charIndex + 1) * 2), charIndex); charIndex++; charCount--; } else { buffer.Fallback(*(char*)((byte*)chars + charIndex * 2), charIndex); } char[] array = new char[buffer.Remaining]; int num = 0; while (buffer.Remaining > 0) { array[num++] = buffer.GetNextChar(); } fixed (char* chars2 = &System.Runtime.CompilerServices.Unsafe.AsRef<char>((char*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref array != null && array.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<char, ?>(ref array[0]) : ref *(?*)null))) { byteIndex += GetBytes(chars2, array.Length, bytes + byteIndex, byteCount); } } public unsafe override int GetByteCount(char[] chars, int index, int count) { //IL_007a->IL0081: Incompatible stack types: I vs Ref if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || index > chars.Length) { throw new ArgumentOutOfRangeException("index", Strings.GetString("ArgRange_Array")); } if (count < 0 || count > chars.Length - index) { throw new ArgumentOutOfRangeException("count", Strings.GetString("ArgRange_Array")); } if (count == 0) { return 0; } fixed (char* ptr = &System.Runtime.CompilerServices.Unsafe.AsRef<char>((char*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref chars != null && chars.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<char, ?>(ref chars[0]) : ref *(?*)null))) { return GetByteCountImpl((char*)((byte*)ptr + index * 2), count); } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { //IL_00d6->IL00dd: Incompatible stack types: I vs Ref //IL_00f5->IL00fd: Incompatible stack types: I vs Ref if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", Strings.GetString("ArgRange_Array")); } if (charCount < 0 || charCount > chars.Length - charIndex) { throw new ArgumentOutOfRangeException("charCount", Strings.GetString("ArgRange_Array")); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", Strings.GetString("ArgRange_Array")); } if (bytes.Length - byteIndex < charCount) { throw new ArgumentException(Strings.GetString("Arg_InsufficientSpace"), "bytes"); } if (charCount == 0) { return 0; } fixed (char* ptr = &System.Runtime.CompilerServices.Unsafe.AsRef<char>((char*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref chars != null && chars.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<char, ?>(ref chars[0]) : ref *(?*)null))) { fixed (byte* ptr2 = &System.Runtime.CompilerServices.Unsafe.AsRef<byte>((byte*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref bytes != null && bytes.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<byte, ?>(ref bytes[0]) : ref *(?*)null))) { return GetBytesImpl((char*)((byte*)ptr + charIndex * 2), charCount, ptr2 + byteIndex, bytes.Length - byteIndex); } } } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { //IL_00f4->IL00fc: Incompatible stack types: I vs Ref if (s == null) { throw new ArgumentNullException("s"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charIndex > s.Length) { throw new ArgumentOutOfRangeException("charIndex", Strings.GetString("ArgRange_StringIndex")); } if (charCount < 0 || charCount > s.Length - charIndex) { throw new ArgumentOutOfRangeException("charCount", Strings.GetString("ArgRange_StringRange")); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", Strings.GetString("ArgRange_Array")); } if (bytes.Length - byteIndex < charCount) { throw new ArgumentException(Strings.GetString("Arg_InsufficientSpace"), "bytes"); } if (charCount == 0 || bytes.Length == byteIndex) { return 0; } fixed (char* ptr = s) { fixed (byte* ptr2 = &System.Runtime.CompilerServices.Unsafe.AsRef<byte>((byte*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref bytes != null && bytes.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<byte, ?>(ref bytes[0]) : ref *(?*)null))) { return GetBytesImpl((char*)((byte*)ptr + charIndex * 2), charCount, ptr2 + byteIndex, bytes.Length - byteIndex); } } } public unsafe override int GetByteCount(char* chars, int count) { return GetByteCountImpl(chars, count); } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return GetBytesImpl(chars, charCount, bytes, byteCount); } public unsafe abstract int GetByteCountImpl(char* chars, int charCount); public unsafe abstract int GetBytesImpl(char* chars, int charCount, byte* bytes, int byteCount); } public abstract class MonoEncoder : Encoder { private MonoEncoding encoding; public MonoEncoder(MonoEncoding encoding) { this.encoding = encoding; } public unsafe override int GetByteCount(char[] chars, int index, int count, bool refresh) { //IL_007a->IL0081: Incompatible stack types: I vs Ref if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || index > chars.Length) { throw new ArgumentOutOfRangeException("index", Strings.GetString("ArgRange_Array")); } if (count < 0 || count > chars.Length - index) { throw new ArgumentOutOfRangeException("count", Strings.GetString("ArgRange_Array")); } if (count == 0) { return 0; } fixed (char* ptr = &System.Runtime.CompilerServices.Unsafe.AsRef<char>((char*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref chars != null && chars.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<char, ?>(ref chars[0]) : ref *(?*)null))) { return GetByteCountImpl((char*)((byte*)ptr + index * 2), count, refresh); } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { //IL_00d6->IL00dd: Incompatible stack types: I vs Ref //IL_00f5->IL00fd: Incompatible stack types: I vs Ref if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", Strings.GetString("ArgRange_Array")); } if (charCount < 0 || charCount > chars.Length - charIndex) { throw new ArgumentOutOfRangeException("charCount", Strings.GetString("ArgRange_Array")); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", Strings.GetString("ArgRange_Array")); } if (bytes.Length - byteIndex < charCount) { throw new ArgumentException(Strings.GetString("Arg_InsufficientSpace"), "bytes"); } if (charCount == 0) { return 0; } fixed (char* ptr = &System.Runtime.CompilerServices.Unsafe.AsRef<char>((char*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref chars != null && chars.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<char, ?>(ref chars[0]) : ref *(?*)null))) { fixed (byte* ptr2 = &System.Runtime.CompilerServices.Unsafe.AsRef<byte>((byte*)System.Runtime.CompilerServices.Unsafe.AsPointer(ref bytes != null && bytes.Length != 0 ? ref System.Runtime.CompilerServices.Unsafe.As<byte, ?>(ref bytes[0]) : ref *(?*)null))) { return GetBytesImpl((char*)((byte*)ptr + charIndex * 2), charCount, ptr2 + byteIndex, bytes.Length - byteIndex, flush); } } } public unsafe abstract int GetByteCountImpl(char* chars, int charCount, bool refresh); public unsafe abstract int GetBytesImpl(char* chars, int charCount, byte* bytes, int byteCount, bool refresh); public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { return GetBytesImpl(chars, charCount, bytes, byteCount, flush); } public unsafe void HandleFallback(char* chars, ref int charIndex, ref int charCount, byte* bytes, ref int byteIndex, ref int byteCount) { EncoderFallbackBuffer buffer = base.FallbackBuffer; encoding.HandleFallback(ref buffer, chars, ref charIndex, ref charCount, bytes, ref byteIndex, ref byteCount); } } public sealed class Strings { public static string GetString(string tag) { return tag switch { "ArgRange_Array" => "Argument index is out of array range.", "Arg_InsufficientSpace" => "Insufficient space in the argument array.", "ArgRange_NonNegative" => "Non-negative value is expected.", "NotSupp_MissingCodeTable" => "This encoding is not supported. Code table is missing.", "ArgRange_StringIndex" => "String index is out of range.", "ArgRange_StringRange" => "String length is out of range.", _ => throw new ArgumentException($"Unexpected error tag name: {tag}"), }; } }
patchers/I18N.West.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using I18N.Common; [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../../mono.pub")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: PermissionSet(SecurityAction.RequestMinimum, XML = "<PermissionSet class=\"System.Security.PermissionSet\"\nversion=\"1\">\n<IPermission class=\"System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\nversion=\"1\"\nFlags=\"SkipVerification\"/>\n</PermissionSet>\n")] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] internal static class Consts { public const string MonoVersion = "2.6.5.0"; public const string MonoCompany = "MONO development team"; public const string MonoProduct = "MONO Common language infrastructure"; public const string MonoCopyright = "(c) various MONO Authors"; public const string FxVersion = "2.0.0.0"; public const string VsVersion = "8.0.0.0"; public const string FxFileVersion = "2.0.50727.1433"; public const string VsFileVersion = "8.0.50727.1433"; public const string AssemblyI18N = "I18N, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } namespace I18N.West; [Serializable] public class CP10000 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '\u00b4', '\u00a8', '≠', 'Æ', 'Ø', '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u00a0', 'À', 'Ã', 'Õ', 'Œ', 'œ', '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '¤', '‹', '›', 'fi', 'fl', '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', '\uf8ff', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '\u02dc', '\u00af', '\u02d8', '\u02d9', '\u02da', '\u00b8', '\u02dd', '\u02db', 'ˇ' }; public CP10000() : base(10000, ToChars, "Western European (Mac)", "macintosh", "macintosh", "macintosh", false, false, false, false, 1252) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 128) { switch (num3) { case 160: num3 = 202; break; case 161: num3 = 193; break; case 164: num3 = 219; break; case 165: num3 = 180; break; case 167: num3 = 164; break; case 168: num3 = 172; break; case 170: num3 = 187; break; case 171: num3 = 199; break; case 172: num3 = 194; break; case 174: num3 = 168; break; case 175: num3 = 248; break; case 176: num3 = 161; break; case 180: num3 = 171; break; case 182: num3 = 166; break; case 183: num3 = 225; break; case 184: num3 = 252; break; case 186: num3 = 188; break; case 187: num3 = 200; break; case 191: num3 = 192; break; case 192: num3 = 203; break; case 193: num3 = 231; break; case 194: num3 = 229; break; case 195: num3 = 204; break; case 196: num3 = 128; break; case 197: num3 = 129; break; case 198: num3 = 174; break; case 199: num3 = 130; break; case 200: num3 = 233; break; case 201: num3 = 131; break; case 202: num3 = 230; break; case 203: num3 = 232; break; case 204: num3 = 237; break; case 205: num3 = 234; break; case 206: num3 = 235; break; case 207: num3 = 236; break; case 209: num3 = 132; break; case 210: num3 = 241; break; case 211: num3 = 238; break; case 212: num3 = 239; break; case 213: num3 = 205; break; case 214: num3 = 133; break; case 216: num3 = 175; break; case 217: num3 = 244; break; case 218: num3 = 242; break; case 219: num3 = 243; break; case 220: num3 = 134; break; case 223: num3 = 167; break; case 224: num3 = 136; break; case 225: num3 = 135; break; case 226: num3 = 137; break; case 227: num3 = 139; break; case 228: num3 = 138; break; case 229: num3 = 140; break; case 230: num3 = 190; break; case 231: num3 = 141; break; case 232: num3 = 143; break; case 233: num3 = 142; break; case 234: num3 = 144; break; case 235: num3 = 145; break; case 236: num3 = 147; break; case 237: num3 = 146; break; case 238: num3 = 148; break; case 239: num3 = 149; break; case 241: num3 = 150; break; case 242: num3 = 152; break; case 243: num3 = 151; break; case 244: num3 = 153; break; case 245: num3 = 155; break; case 246: num3 = 154; break; case 247: num3 = 214; break; case 248: num3 = 191; break; case 249: num3 = 157; break; case 250: num3 = 156; break; case 251: num3 = 158; break; case 252: num3 = 159; break; case 255: num3 = 216; break; case 305: num3 = 245; break; case 338: num3 = 206; break; case 339: num3 = 207; break; case 376: num3 = 217; break; case 402: num3 = 196; break; case 710: num3 = 246; break; case 711: num3 = 255; break; case 728: num3 = 249; break; case 729: num3 = 250; break; case 730: num3 = 251; break; case 731: num3 = 254; break; case 732: num3 = 247; break; case 733: num3 = 253; break; case 960: num3 = 185; break; case 8211: num3 = 208; break; case 8212: num3 = 209; break; case 8216: num3 = 212; break; case 8217: num3 = 213; break; case 8218: num3 = 226; break; case 8220: num3 = 210; break; case 8221: num3 = 211; break; case 8222: num3 = 227; break; case 8224: num3 = 160; break; case 8225: num3 = 224; break; case 8226: num3 = 165; break; case 8230: num3 = 201; break; case 8240: num3 = 228; break; case 8249: num3 = 220; break; case 8250: num3 = 221; break; case 8260: num3 = 218; break; case 8482: num3 = 170; break; case 8486: num3 = 189; break; case 8706: num3 = 182; break; case 8710: num3 = 198; break; case 8719: num3 = 184; break; case 8721: num3 = 183; break; case 8730: num3 = 195; break; case 8734: num3 = 176; break; case 8747: num3 = 186; break; case 8776: num3 = 197; break; case 8800: num3 = 173; break; case 8804: num3 = 178; break; case 8805: num3 = 179; break; case 8984: num3 = 17; break; case 9674: num3 = 215; break; case 9830: num3 = 19; break; case 10003: num3 = 18; break; case 63743: num3 = 240; break; case 64257: num3 = 222; break; case 64258: num3 = 223; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; } else { ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); } break; case 162: case 163: case 169: case 177: case 181: break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCmacintosh : CP10000 { } [Serializable] public class CP10079 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', 'Ý', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '\u00b4', '\u00a8', '≠', 'Æ', 'Ø', '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u00a0', 'À', 'Ã', 'Õ', 'Œ', 'œ', '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '¤', 'Ð', 'ð', 'Þ', 'þ', 'ý', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', '\uf8ff', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '\u02dc', '\u00af', '\u02d8', '\u02d9', '\u02da', '\u00b8', '\u02dd', '\u02db', 'ˇ' }; public CP10079() : base(10079, ToChars, "Icelandic (Mac)", "x-mac-icelandic", "x-mac-icelandic", "x-mac-icelandic", false, false, false, false, 1252) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 128) { switch (num3) { case 160: num3 = 202; break; case 161: num3 = 193; break; case 164: num3 = 219; break; case 165: num3 = 180; break; case 167: num3 = 164; break; case 168: num3 = 172; break; case 170: num3 = 187; break; case 171: num3 = 199; break; case 172: num3 = 194; break; case 174: num3 = 168; break; case 175: num3 = 248; break; case 176: num3 = 161; break; case 180: num3 = 171; break; case 182: num3 = 166; break; case 183: num3 = 225; break; case 184: num3 = 252; break; case 186: num3 = 188; break; case 187: num3 = 200; break; case 191: num3 = 192; break; case 192: num3 = 203; break; case 193: num3 = 231; break; case 194: num3 = 229; break; case 195: num3 = 204; break; case 196: num3 = 128; break; case 197: num3 = 129; break; case 198: num3 = 174; break; case 199: num3 = 130; break; case 200: num3 = 233; break; case 201: num3 = 131; break; case 202: num3 = 230; break; case 203: num3 = 232; break; case 204: num3 = 237; break; case 205: num3 = 234; break; case 206: num3 = 235; break; case 207: num3 = 236; break; case 208: num3 = 220; break; case 209: num3 = 132; break; case 210: num3 = 241; break; case 211: num3 = 238; break; case 212: num3 = 239; break; case 213: num3 = 205; break; case 214: num3 = 133; break; case 216: num3 = 175; break; case 217: num3 = 244; break; case 218: num3 = 242; break; case 219: num3 = 243; break; case 220: num3 = 134; break; case 221: num3 = 160; break; case 223: num3 = 167; break; case 224: num3 = 136; break; case 225: num3 = 135; break; case 226: num3 = 137; break; case 227: num3 = 139; break; case 228: num3 = 138; break; case 229: num3 = 140; break; case 230: num3 = 190; break; case 231: num3 = 141; break; case 232: num3 = 143; break; case 233: num3 = 142; break; case 234: num3 = 144; break; case 235: num3 = 145; break; case 236: num3 = 147; break; case 237: num3 = 146; break; case 238: num3 = 148; break; case 239: num3 = 149; break; case 240: num3 = 221; break; case 241: num3 = 150; break; case 242: num3 = 152; break; case 243: num3 = 151; break; case 244: num3 = 153; break; case 245: num3 = 155; break; case 246: num3 = 154; break; case 247: num3 = 214; break; case 248: num3 = 191; break; case 249: num3 = 157; break; case 250: num3 = 156; break; case 251: num3 = 158; break; case 252: num3 = 159; break; case 253: num3 = 224; break; case 254: num3 = 223; break; case 255: num3 = 216; break; case 305: num3 = 245; break; case 338: num3 = 206; break; case 339: num3 = 207; break; case 376: num3 = 217; break; case 402: num3 = 196; break; case 710: num3 = 246; break; case 711: num3 = 255; break; case 728: num3 = 249; break; case 729: num3 = 250; break; case 730: num3 = 251; break; case 731: num3 = 254; break; case 732: num3 = 247; break; case 733: num3 = 253; break; case 960: num3 = 185; break; case 8211: num3 = 208; break; case 8212: num3 = 209; break; case 8216: num3 = 212; break; case 8217: num3 = 213; break; case 8218: num3 = 226; break; case 8220: num3 = 210; break; case 8221: num3 = 211; break; case 8222: num3 = 227; break; case 8226: num3 = 165; break; case 8230: num3 = 201; break; case 8240: num3 = 228; break; case 8260: num3 = 218; break; case 8482: num3 = 170; break; case 8486: num3 = 189; break; case 8706: num3 = 182; break; case 8710: num3 = 198; break; case 8719: num3 = 184; break; case 8721: num3 = 183; break; case 8730: num3 = 195; break; case 8734: num3 = 176; break; case 8747: num3 = 186; break; case 8776: num3 = 197; break; case 8800: num3 = 173; break; case 8804: num3 = 178; break; case 8805: num3 = 179; break; case 9674: num3 = 215; break; case 63743: num3 = 240; break; default: ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); break; case 162: case 163: case 169: case 177: case 181: case 222: break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCx_mac_icelandic : CP10079 { } [Serializable] public class CP1250 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', '€', '\u0081', '‚', '\u0083', '„', '…', '†', '‡', '\u0088', '‰', 'Š', '‹', 'Ś', 'Ť', 'Ž', 'Ź', '\u0090', '‘', '’', '“', '”', '•', '–', '—', '\u0098', '™', 'š', '›', 'ś', 'ť', 'ž', 'ź', '\u00a0', 'ˇ', '\u02d8', 'Ł', '¤', 'Ą', '¦', '§', '\u00a8', '©', 'Ş', '«', '¬', '\u00ad', '®', 'Ż', '°', '±', '\u02db', 'ł', '\u00b4', 'µ', '¶', '·', '\u00b8', 'ą', 'ş', '»', 'Ľ', '\u02dd', 'ľ', 'ż', 'Ŕ', 'Á', 'Â', 'Ă', 'Ä', 'Ĺ', 'Ć', 'Ç', 'Č', 'É', 'Ę', 'Ë', 'Ě', 'Í', 'Î', 'Ď', 'Đ', 'Ń', 'Ň', 'Ó', 'Ô', 'Ő', 'Ö', '×', 'Ř', 'Ů', 'Ú', 'Ű', 'Ü', 'Ý', 'Ţ', 'ß', 'ŕ', 'á', 'â', 'ă', 'ä', 'ĺ', 'ć', 'ç', 'č', 'é', 'ę', 'ë', 'ě', 'í', 'î', 'ď', 'đ', 'ń', 'ň', 'ó', 'ô', 'ő', 'ö', '÷', 'ř', 'ů', 'ú', 'ű', 'ü', 'ý', 'ţ', '\u02d9' }; public CP1250() : base(1250, ToChars, "Central European (Windows)", "iso-8859-2", "windows-1250", "windows-1250", true, true, true, true, 1250) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); charCount--; if (num3 >= 128) { switch (num3) { case 258: num3 = 195; break; case 259: num3 = 227; break; case 260: num3 = 165; break; case 261: num3 = 185; break; case 262: num3 = 198; break; case 263: num3 = 230; break; case 268: num3 = 200; break; case 269: num3 = 232; break; case 270: num3 = 207; break; case 271: num3 = 239; break; case 272: num3 = 208; break; case 273: num3 = 240; break; case 280: num3 = 202; break; case 281: num3 = 234; break; case 282: num3 = 204; break; case 283: num3 = 236; break; case 313: num3 = 197; break; case 314: num3 = 229; break; case 317: num3 = 188; break; case 318: num3 = 190; break; case 321: num3 = 163; break; case 322: num3 = 179; break; case 323: num3 = 209; break; case 324: num3 = 241; break; case 327: num3 = 210; break; case 328: num3 = 242; break; case 336: num3 = 213; break; case 337: num3 = 245; break; case 340: num3 = 192; break; case 341: num3 = 224; break; case 344: num3 = 216; break; case 345: num3 = 248; break; case 346: num3 = 140; break; case 347: num3 = 156; break; case 350: num3 = 170; break; case 351: num3 = 186; break; case 352: num3 = 138; break; case 353: num3 = 154; break; case 354: num3 = 222; break; case 355: num3 = 254; break; case 356: num3 = 141; break; case 357: num3 = 157; break; case 366: num3 = 217; break; case 367: num3 = 249; break; case 368: num3 = 219; break; case 369: num3 = 251; break; case 377: num3 = 143; break; case 378: num3 = 159; break; case 379: num3 = 175; break; case 380: num3 = 191; break; case 381: num3 = 142; break; case 382: num3 = 158; break; case 711: num3 = 161; break; case 728: num3 = 162; break; case 729: num3 = 255; break; case 731: num3 = 178; break; case 733: num3 = 189; break; case 8211: num3 = 150; break; case 8212: num3 = 151; break; case 8216: num3 = 145; break; case 8217: num3 = 146; break; case 8218: num3 = 130; break; case 8220: num3 = 147; break; case 8221: num3 = 148; break; case 8222: num3 = 132; break; case 8224: num3 = 134; break; case 8225: num3 = 135; break; case 8226: num3 = 149; break; case 8230: num3 = 133; break; case 8240: num3 = 137; break; case 8249: num3 = 139; break; case 8250: num3 = 155; break; case 8364: num3 = 128; break; case 8482: num3 = 153; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; break; } ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); continue; case 129: case 131: case 136: case 144: case 152: case 160: case 164: case 166: case 167: case 168: case 169: case 171: case 172: case 173: case 174: case 176: case 177: case 180: case 181: case 182: case 183: case 184: case 187: case 193: case 194: case 196: case 199: case 201: case 203: case 205: case 206: case 211: case 212: case 214: case 215: case 218: case 220: case 221: case 223: case 225: case 226: case 228: case 231: case 233: case 235: case 237: case 238: case 243: case 244: case 246: case 247: case 250: case 252: case 253: break; } } bytes[num2++] = (byte)num3; byteCount--; } } } [Serializable] public class ENCwindows_1250 : CP1250 { } [Serializable] public class CP1252 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', '€', '\u0081', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u008d', 'Ž', '\u008f', '\u0090', '‘', '’', '“', '”', '•', '–', '—', '\u02dc', '™', 'š', '›', 'œ', '\u009d', 'ž', 'Ÿ', '\u00a0', '¡', '¢', '£', '¤', '¥', '¦', '§', '\u00a8', '©', 'ª', '«', '¬', '\u00ad', '®', '\u00af', '°', '±', '²', '³', '\u00b4', 'µ', '¶', '·', '\u00b8', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ' }; public CP1252() : base(1252, ToChars, "Western European (Windows)", "iso-8859-1", "Windows-1252", "Windows-1252", true, true, true, true, 1252) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); charCount--; if (num3 >= 128) { int num4 = num3; switch (num4) { default: switch (num4) { case 376: num3 = 159; break; case 381: num3 = 142; break; case 382: num3 = 158; break; case 402: num3 = 131; break; case 710: num3 = 136; break; case 732: num3 = 152; break; case 8211: num3 = 150; break; case 8212: num3 = 151; break; case 8216: num3 = 145; break; case 8217: num3 = 146; break; case 8218: num3 = 130; break; case 8220: num3 = 147; break; case 8221: num3 = 148; break; case 8222: num3 = 132; break; case 8224: num3 = 134; break; case 8225: num3 = 135; break; case 8226: num3 = 149; break; case 8230: num3 = 133; break; case 8240: num3 = 137; break; case 8249: num3 = 139; break; case 8250: num3 = 155; break; case 8364: num3 = 128; break; case 8482: num3 = 153; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; break; } ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); continue; case 129: case 141: case 143: case 144: break; } break; case 338: num3 = 140; break; case 339: num3 = 156; break; case 352: num3 = 138; break; case 353: num3 = 154; break; case 157: case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: case 176: case 177: case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: case 186: case 187: case 188: case 189: case 190: case 191: case 192: case 193: case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: case 240: case 241: case 242: case 243: case 244: case 245: case 246: case 247: case 248: case 249: case 250: case 251: case 252: case 253: case 254: case 255: break; } } bytes[num2++] = (byte)num3; byteCount--; } } } [Serializable] public class ENCwindows_1252 : CP1252 { } [Serializable] public class CP1253 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', '€', '\u0081', '‚', 'ƒ', '„', '…', '†', '‡', '\u0088', '‰', '\u008a', '‹', '\u008c', '\u008d', '\u008e', '\u008f', '\u0090', '‘', '’', '“', '”', '•', '–', '—', '\u0098', '™', '\u009a', '›', '\u009c', '\u009d', '\u009e', '\u009f', '\u00a0', '\u0385', 'Ά', '£', '¤', '¥', '¦', '§', '\u00a8', '©', 'ª', '«', '¬', '\u00ad', '®', '―', '°', '±', '²', '³', '\u0384', 'µ', '¶', '·', 'Έ', 'Ή', 'Ί', '»', 'Ό', '½', 'Ύ', 'Ώ', 'ΐ', 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', '?', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω', 'Ϊ', 'Ϋ', 'ά', 'έ', 'ή', 'ί', 'ΰ', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ϊ', 'ϋ', 'ό', 'ύ', 'ώ', '?' }; public CP1253() : base(1253, ToChars, "Greek (Windows)", "iso-8859-7", "windows-1253", "windows-1253", true, true, true, true, 1253) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 128) { switch (num3) { case 402: num3 = 131; break; case 900: num3 = 180; break; case 901: num3 = 161; break; case 902: num3 = 162; break; case 904: num3 = 184; break; case 905: num3 = 185; break; case 906: num3 = 186; break; case 908: num3 = 188; break; case 910: case 911: case 912: case 913: case 914: case 915: case 916: case 917: case 918: case 919: case 920: case 921: case 922: case 923: case 924: case 925: case 926: case 927: case 928: case 929: num3 -= 720; break; case 931: case 932: case 933: case 934: case 935: case 936: case 937: case 938: case 939: case 940: case 941: case 942: case 943: case 944: case 945: case 946: case 947: case 948: case 949: case 950: case 951: case 952: case 953: case 954: case 955: case 956: case 957: case 958: case 959: case 960: case 961: case 962: case 963: case 964: case 965: case 966: case 967: case 968: case 969: case 970: case 971: case 972: case 973: case 974: num3 -= 720; break; case 981: num3 = 246; break; case 8211: num3 = 150; break; case 8212: num3 = 151; break; case 8213: num3 = 175; break; case 8216: num3 = 145; break; case 8217: num3 = 146; break; case 8218: num3 = 130; break; case 8220: num3 = 147; break; case 8221: num3 = 148; break; case 8222: num3 = 132; break; case 8224: num3 = 134; break; case 8225: num3 = 135; break; case 8226: num3 = 149; break; case 8230: num3 = 133; break; case 8240: num3 = 137; break; case 8249: num3 = 139; break; case 8250: num3 = 155; break; case 8364: num3 = 128; break; case 8482: num3 = 153; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; } else { ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); } break; case 129: case 136: case 138: case 140: case 141: case 142: case 143: case 144: case 152: case 154: case 156: case 157: case 158: case 159: case 160: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 176: case 177: case 178: case 179: case 181: case 182: case 183: case 187: case 189: break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCwindows_1253 : CP1253 { } [Serializable] public class CP28592 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u0085', '\u0086', '\u0087', '\u0088', '\u0089', '\u008a', '\u008b', '\u008c', '\u008d', '\u008e', '\u008f', '\u0090', '\u0091', '\u0092', '\u0093', '\u0094', '\u0095', '\u0096', '\u0097', '\u0098', '\u0099', '\u009a', '\u009b', '\u009c', '\u009d', '\u009e', '\u009f', '\u00a0', 'Ą', '\u02d8', 'Ł', '¤', 'Ľ', 'Ś', '§', '\u00a8', 'Š', 'Ş', 'Ť', 'Ź', '\u00ad', 'Ž', 'Ż', '°', 'ą', '\u02db', 'ł', '\u00b4', 'ľ', 'ś', 'ˇ', '\u00b8', 'š', 'ş', 'ť', 'ź', '\u02dd', 'ž', 'ż', 'Ŕ', 'Á', 'Â', 'Ă', 'Ä', 'Ĺ', 'Ć', 'Ç', 'Č', 'É', 'Ę', 'Ë', 'Ě', 'Í', 'Î', 'Ď', 'Đ', 'Ń', 'Ň', 'Ó', 'Ô', 'Ő', 'Ö', '×', 'Ř', 'Ů', 'Ú', 'Ű', 'Ü', 'Ý', 'Ţ', 'ß', 'ŕ', 'á', 'â', 'ă', 'ä', 'ĺ', 'ć', 'ç', 'č', 'é', 'ę', 'ë', 'ě', 'í', 'î', 'ď', 'đ', 'ń', 'ň', 'ó', 'ô', 'ő', 'ö', '÷', 'ř', 'ů', 'ú', 'ű', 'ü', 'ý', 'ţ', '\u02d9' }; public CP28592() : base(28592, ToChars, "Central European (ISO)", "iso-8859-2", "iso-8859-2", "iso-8859-2", true, true, true, true, 1250) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 161) { switch (num3) { case 162: num3 = 141; break; case 165: num3 = 142; break; case 169: num3 = 136; break; case 174: num3 = 159; break; case 182: num3 = 20; break; case 258: num3 = 195; break; case 259: num3 = 227; break; case 260: num3 = 161; break; case 261: num3 = 177; break; case 262: num3 = 198; break; case 263: num3 = 230; break; case 268: num3 = 200; break; case 269: num3 = 232; break; case 270: num3 = 207; break; case 271: num3 = 239; break; case 272: num3 = 208; break; case 273: num3 = 240; break; case 280: num3 = 202; break; case 281: num3 = 234; break; case 282: num3 = 204; break; case 283: num3 = 236; break; case 313: num3 = 197; break; case 314: num3 = 229; break; case 317: num3 = 165; break; case 318: num3 = 181; break; case 321: num3 = 163; break; case 322: num3 = 179; break; case 323: num3 = 209; break; case 324: num3 = 241; break; case 327: num3 = 210; break; case 328: num3 = 242; break; case 336: num3 = 213; break; case 337: num3 = 245; break; case 340: num3 = 192; break; case 341: num3 = 224; break; case 344: num3 = 216; break; case 345: num3 = 248; break; case 346: num3 = 166; break; case 347: num3 = 182; break; case 350: num3 = 170; break; case 351: num3 = 186; break; case 352: num3 = 169; break; case 353: num3 = 185; break; case 354: num3 = 222; break; case 355: num3 = 254; break; case 356: num3 = 171; break; case 357: num3 = 187; break; case 366: num3 = 217; break; case 367: num3 = 249; break; case 368: num3 = 219; break; case 369: num3 = 251; break; case 377: num3 = 172; break; case 378: num3 = 188; break; case 379: num3 = 175; break; case 380: num3 = 191; break; case 381: num3 = 174; break; case 382: num3 = 190; break; case 711: num3 = 183; break; case 728: num3 = 162; break; case 729: num3 = 255; break; case 731: num3 = 178; break; case 733: num3 = 189; break; case 8226: num3 = 7; break; case 8252: num3 = 19; break; case 8592: num3 = 27; break; case 8593: num3 = 24; break; case 8594: num3 = 26; break; case 8595: num3 = 25; break; case 8596: num3 = 29; break; case 8597: num3 = 18; break; case 8616: num3 = 23; break; case 8735: num3 = 28; break; case 9472: num3 = 148; break; case 9474: num3 = 131; break; case 9484: num3 = 134; break; case 9488: num3 = 143; break; case 9492: num3 = 144; break; case 9496: num3 = 133; break; case 9500: num3 = 147; break; case 9508: num3 = 132; break; case 9516: num3 = 146; break; case 9524: num3 = 145; break; case 9532: num3 = 149; break; case 9552: num3 = 157; break; case 9553: num3 = 138; break; case 9556: num3 = 153; break; case 9559: num3 = 139; break; case 9562: num3 = 152; break; case 9565: num3 = 140; break; case 9568: num3 = 156; break; case 9571: num3 = 137; break; case 9574: num3 = 155; break; case 9577: num3 = 154; break; case 9580: num3 = 158; break; case 9600: num3 = 151; break; case 9604: num3 = 150; break; case 9608: num3 = 135; break; case 9617: num3 = 128; break; case 9618: num3 = 129; break; case 9619: num3 = 130; break; case 9644: num3 = 22; break; case 9650: num3 = 30; break; case 9658: num3 = 16; break; case 9660: num3 = 31; break; case 9668: num3 = 17; break; case 9675: num3 = 9; break; case 9688: num3 = 8; break; case 9689: num3 = 10; break; case 9786: num3 = 1; break; case 9787: num3 = 2; break; case 9788: num3 = 15; break; case 9792: num3 = 12; break; case 9794: num3 = 11; break; case 9824: num3 = 6; break; case 9827: num3 = 5; break; case 9829: num3 = 3; break; case 9830: num3 = 4; break; case 9834: num3 = 13; break; case 9836: num3 = 14; break; case 65512: num3 = 131; break; case 65513: num3 = 27; break; case 65514: num3 = 24; break; case 65515: num3 = 26; break; case 65516: num3 = 25; break; case 65518: num3 = 9; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; } else { ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); } break; case 164: case 167: case 168: case 173: case 176: case 180: case 184: case 193: case 194: case 196: case 199: case 201: case 203: case 205: case 206: case 208: case 211: case 212: case 214: case 215: case 218: case 220: case 221: case 223: case 225: case 226: case 228: case 231: case 233: case 235: case 237: case 238: case 243: case 244: case 246: case 247: case 250: case 252: case 253: break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCiso_8859_2 : CP28592 { } [Serializable] public class CP28593 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u0085', '\u0086', '\u0087', '\u0088', '\u0089', '\u008a', '\u008b', '\u008c', '\u008d', '\u008e', '\u008f', '\u0090', '\u0091', '\u0092', '\u0093', '\u0094', '\u0095', '\u0096', '\u0097', '\u0098', '\u0099', '\u009a', '\u009b', '\u009c', '\u009d', '\u009e', '\u009f', '\u00a0', 'Ħ', '\u02d8', '£', '¤', '?', 'Ĥ', '§', '\u00a8', 'İ', 'Ş', 'Ğ', 'Ĵ', '\u00ad', '?', 'Ż', '°', 'ħ', '²', '³', '\u00b4', 'µ', 'ĥ', '·', '\u00b8', 'ı', 'ş', 'ğ', 'ĵ', '½', '?', 'ż', 'À', 'Á', 'Â', '?', 'Ä', 'Ċ', 'Ĉ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', '?', 'Ñ', 'Ò', 'Ó', 'Ô', 'Ġ', 'Ö', '×', 'Ĝ', 'Ù', 'Ú', 'Û', 'Ü', 'Ŭ', 'Ŝ', 'ß', 'à', 'á', 'â', '?', 'ä', 'ċ', 'ĉ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', '?', 'ñ', 'ò', 'ó', 'ô', 'ġ', 'ö', '÷', 'ĝ', 'ù', 'ú', 'û', 'ü', 'ŭ', 'ŝ', '\u02d9' }; public CP28593() : base(28593, ToChars, "Latin 3 (ISO)", "iso-8859-3", "iso-8859-3", "iso-8859-3", true, true, true, true, 28593) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 161) { switch (num3) { case 264: num3 = 198; break; case 265: num3 = 230; break; case 266: num3 = 197; break; case 267: num3 = 229; break; case 284: num3 = 216; break; case 285: num3 = 248; break; case 286: num3 = 171; break; case 287: num3 = 187; break; case 288: num3 = 213; break; case 289: num3 = 245; break; case 292: num3 = 166; break; case 293: num3 = 182; break; case 294: num3 = 161; break; case 295: num3 = 177; break; case 304: num3 = 169; break; case 305: num3 = 185; break; case 308: num3 = 172; break; case 309: num3 = 188; break; case 348: num3 = 222; break; case 349: num3 = 254; break; case 350: num3 = 170; break; case 351: num3 = 186; break; case 364: num3 = 221; break; case 365: num3 = 253; break; case 379: num3 = 175; break; case 380: num3 = 191; break; case 728: num3 = 162; break; case 729: num3 = 255; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; } else { ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); } break; case 163: case 164: case 167: case 168: case 173: case 176: case 178: case 179: case 180: case 181: case 183: case 184: case 189: case 192: case 193: case 194: case 196: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 209: case 210: case 211: case 212: case 214: case 215: case 217: case 218: case 219: case 220: case 223: case 224: case 225: case 226: case 228: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: case 241: case 242: case 243: case 244: case 246: case 247: case 249: case 250: case 251: case 252: break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCiso_8859_3 : CP28593 { } [Serializable] public class CP28597 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u0085', '\u0086', '\u0087', '\u0088', '\u0089', '\u008a', '\u008b', '\u008c', '\u008d', '\u008e', '\u008f', '\u0090', '\u0091', '\u0092', '\u0093', '\u0094', '\u0095', '\u0096', '\u0097', '\u0098', '\u0099', '\u009a', '\u009b', '\u009c', '\u009d', '\u009e', '\u009f', '\u00a0', '‘', '’', '£', '€', '?', '¦', '§', '\u00a8', '©', '?', '«', '¬', '\u00ad', '?', '―', '°', '±', '²', '³', '\u00b4', '\u0385', 'Ά', '·', 'Έ', 'Ή', 'Ί', '»', 'Ό', '½', 'Ύ', 'Ώ', 'ΐ', 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', '?', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω', 'Ϊ', 'Ϋ', 'ά', 'έ', 'ή', 'ί', 'ΰ', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ϊ', 'ϋ', 'ό', 'ύ', 'ώ', '?' }; public CP28597() : base(28597, ToChars, "Greek (ISO)", "iso-8859-7", "iso-8859-7", "iso-8859-7", true, true, true, true, 1253) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 161) { switch (num3) { case 901: case 902: case 903: case 904: case 905: case 906: num3 -= 720; break; case 908: num3 = 188; break; case 910: case 911: case 912: case 913: case 914: case 915: case 916: case 917: case 918: case 919: case 920: case 921: case 922: case 923: case 924: case 925: case 926: case 927: case 928: case 929: num3 -= 720; break; case 931: case 932: case 933: case 934: case 935: case 936: case 937: case 938: case 939: case 940: case 941: case 942: case 943: case 944: case 945: case 946: case 947: case 948: case 949: case 950: case 951: case 952: case 953: case 954: case 955: case 956: case 957: case 958: case 959: case 960: case 961: case 962: case 963: case 964: case 965: case 966: case 967: case 968: case 969: case 970: case 971: case 972: case 973: case 974: num3 -= 720; break; case 981: num3 = 246; break; case 8213: num3 = 175; break; case 8216: num3 = 161; break; case 8217: num3 = 162; break; case 8364: num3 = 164; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; } else { ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); } break; case 163: case 166: case 167: case 168: case 169: case 171: case 172: case 173: case 176: case 177: case 178: case 179: case 180: case 183: case 187: case 189: break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCiso_8859_7 : CP28597 { } [Serializable] public class CP28605 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u0085', '\u0086', '\u0087', '\u0088', '\u0089', '\u008a', '\u008b', '\u008c', '\u008d', '\u008e', '\u008f', '\u0090', '\u0091', '\u0092', '\u0093', '\u0094', '\u0095', '\u0096', '\u0097', '\u0098', '\u0099', '\u009a', '\u009b', '\u009c', '\u009d', '\u009e', '\u009f', '\u00a0', '¡', '¢', '£', '€', '¥', 'Š', '§', 'š', '©', 'ª', '«', '¬', '\u00ad', '®', '\u00af', '°', '±', '²', '³', 'Ž', 'µ', '¶', '·', 'ž', '¹', 'º', '»', 'Œ', 'œ', 'Ÿ', '¿', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ' }; public CP28605() : base(28605, ToChars, "Latin 9 (ISO)", "iso-8859-15", "iso-8859-15", "iso-8859-15", false, true, true, true, 1252) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 164) { switch (num3) { case 338: num3 = 188; break; case 339: num3 = 189; break; case 352: num3 = 166; break; case 353: num3 = 168; break; case 376: num3 = 190; break; case 381: num3 = 180; break; case 382: num3 = 184; break; case 8364: num3 = 164; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; } else { ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); } break; case 165: case 167: case 169: case 170: case 171: case 172: case 173: case 174: case 175: case 176: case 177: case 178: case 179: case 181: case 182: case 183: case 185: case 186: case 187: case 191: case 192: case 193: case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: case 240: case 241: case 242: case 243: case 244: case 245: case 246: case 247: case 248: case 249: case 250: case 251: case 252: case 253: case 254: case 255: break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCiso_8859_15 : CP28605 { } [Serializable] public class CP437 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u007f', 'Ç', 'ü', 'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å', 'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', '¢', '£', '¥', '₧', 'ƒ', 'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '⌐', '¬', '½', '¼', '¡', '«', '»', '░', '▒', '▓', '│', '┤', '╡', '╢', '╖', '╕', '╣', '║', '╗', '╝', '╜', '╛', '┐', '└', '┴', '┬', '├', '─', '┼', '╞', '╟', '╚', '╔', '╩', '╦', '╠', '═', '╬', '╧', '╨', '╤', '╥', '╙', '╘', '╒', '╓', '╫', '╪', '┘', '┌', '█', '▄', '▌', '▐', '▀', 'α', 'ß', 'Γ', 'π', 'Σ', 'σ', 'µ', 'τ', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩', '≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'ⁿ', '²', '■', '\u00a0' }; public CP437() : base(437, ToChars, "OEM United States", "IBM437", "IBM437", "IBM437", false, false, false, false, 1252) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 128) { switch (num3) { case 160: num3 = 255; break; case 161: num3 = 173; break; case 162: num3 = 155; break; case 163: num3 = 156; break; case 164: num3 = 15; break; case 165: num3 = 157; break; case 166: num3 = 221; break; case 167: num3 = 21; break; case 168: num3 = 34; break; case 169: num3 = 99; break; case 170: num3 = 166; break; case 171: num3 = 174; break; case 172: num3 = 170; break; case 173: num3 = 45; break; case 174: num3 = 114; break; case 175: num3 = 95; break; case 176: num3 = 248; break; case 177: num3 = 241; break; case 178: num3 = 253; break; case 179: num3 = 51; break; case 180: num3 = 39; break; case 181: num3 = 230; break; case 182: num3 = 20; break; case 183: num3 = 250; break; case 184: num3 = 44; break; case 185: num3 = 49; break; case 186: num3 = 167; break; case 187: num3 = 175; break; case 188: num3 = 172; break; case 189: num3 = 171; break; case 190: num3 = 95; break; case 191: num3 = 168; break; case 192: num3 = 65; break; case 193: num3 = 65; break; case 194: num3 = 65; break; case 195: num3 = 65; break; case 196: num3 = 142; break; case 197: num3 = 143; break; case 198: num3 = 146; break; case 199: num3 = 128; break; case 200: num3 = 69; break; case 201: num3 = 144; break; case 202: num3 = 69; break; case 203: num3 = 69; break; case 204: num3 = 73; break; case 205: num3 = 73; break; case 206: num3 = 73; break; case 207: num3 = 73; break; case 208: num3 = 68; break; case 209: num3 = 165; break; case 210: num3 = 79; break; case 211: num3 = 79; break; case 212: num3 = 79; break; case 213: num3 = 79; break; case 214: num3 = 153; break; case 215: num3 = 120; break; case 216: num3 = 79; break; case 217: num3 = 85; break; case 218: num3 = 85; break; case 219: num3 = 85; break; case 220: num3 = 154; break; case 221: num3 = 89; break; case 222: num3 = 95; break; case 223: num3 = 225; break; case 224: num3 = 133; break; case 225: num3 = 160; break; case 226: num3 = 131; break; case 227: num3 = 97; break; case 228: num3 = 132; break; case 229: num3 = 134; break; case 230: num3 = 145; break; case 231: num3 = 135; break; case 232: num3 = 138; break; case 233: num3 = 130; break; case 234: num3 = 136; break; case 235: num3 = 137; break; case 236: num3 = 141; break; case 237: num3 = 161; break; case 238: num3 = 140; break; case 239: num3 = 139; break; case 240: num3 = 100; break; case 241: num3 = 164; break; case 242: num3 = 149; break; case 243: num3 = 162; break; case 244: num3 = 147; break; case 245: num3 = 111; break; case 246: num3 = 148; break; case 247: num3 = 246; break; case 248: num3 = 111; break; case 249: num3 = 151; break; case 250: num3 = 163; break; case 251: num3 = 150; break; case 252: num3 = 129; break; case 253: num3 = 121; break; case 254: num3 = 95; break; case 255: num3 = 152; break; case 256: num3 = 65; break; case 257: num3 = 97; break; case 258: num3 = 65; break; case 259: num3 = 97; break; case 260: num3 = 65; break; case 261: num3 = 97; break; case 262: num3 = 67; break; case 263: num3 = 99; break; case 264: num3 = 67; break; case 265: num3 = 99; break; case 266: num3 = 67; break; case 267: num3 = 99; break; case 268: num3 = 67; break; case 269: num3 = 99; break; case 270: num3 = 68; break; case 271: num3 = 100; break; case 272: num3 = 68; break; case 273: num3 = 100; break; case 274: num3 = 69; break; case 275: num3 = 101; break; case 276: num3 = 69; break; case 277: num3 = 101; break; case 278: num3 = 69; break; case 279: num3 = 101; break; case 280: num3 = 69; break; case 281: num3 = 101; break; case 282: num3 = 69; break; case 283: num3 = 101; break; case 284: num3 = 71; break; case 285: num3 = 103; break; case 286: num3 = 71; break; case 287: num3 = 103; break; case 288: num3 = 71; break; case 289: num3 = 103; break; case 290: num3 = 71; break; case 291: num3 = 103; break; case 292: num3 = 72; break; case 293: num3 = 104; break; case 294: num3 = 72; break; case 295: num3 = 104; break; case 296: num3 = 73; break; case 297: num3 = 105; break; case 298: num3 = 73; break; case 299: num3 = 105; break; case 300: num3 = 73; break; case 301: num3 = 105; break; case 302: num3 = 73; break; case 303: num3 = 105; break; case 304: num3 = 73; break; case 305: num3 = 105; break; case 308: num3 = 74; break; case 309: num3 = 106; break; case 310: num3 = 75; break; case 311: num3 = 107; break; case 313: num3 = 76; break; case 314: num3 = 108; break; case 315: num3 = 76; break; case 316: num3 = 108; break; case 317: num3 = 76; break; case 318: num3 = 108; break; case 321: num3 = 76; break; case 322: num3 = 108; break; case 323: num3 = 78; break; case 324: num3 = 110; break; case 325: num3 = 78; break; case 326: num3 = 110; break; case 327: num3 = 78; break; case 328: num3 = 110; break; case 332: num3 = 79; break; case 333: num3 = 111; break; case 334: num3 = 79; break; case 335: num3 = 111; break; case 336: num3 = 79; break; case 337: num3 = 111; break; case 338: num3 = 79; break; case 339: num3 = 111; break; case 340: num3 = 82; break; case 341: num3 = 114; break; case 342: num3 = 82; break; case 343: num3 = 114; break; case 344: num3 = 82; break; case 345: num3 = 114; break; case 346: num3 = 83; break; case 347: num3 = 115; break; case 348: num3 = 83; break; case 349: num3 = 115; break; case 350: num3 = 83; break; case 351: num3 = 115; break; case 352: num3 = 83; break; case 353: num3 = 115; break; case 354: num3 = 84; break; case 355: num3 = 116; break; case 356: num3 = 84; break; case 357: num3 = 116; break; case 358: num3 = 84; break; case 359: num3 = 116; break; case 360: num3 = 85; break; case 361: num3 = 117; break; case 362: num3 = 85; break; case 363: num3 = 117; break; case 364: num3 = 85; break; case 365: num3 = 117; break; case 366: num3 = 85; break; case 367: num3 = 117; break; case 368: num3 = 85; break; case 369: num3 = 117; break; case 370: num3 = 85; break; case 371: num3 = 117; break; case 372: num3 = 87; break; case 373: num3 = 119; break; case 374: num3 = 89; break; case 375: num3 = 121; break; case 376: num3 = 89; break; case 377: num3 = 90; break; case 378: num3 = 122; break; case 379: num3 = 90; break; case 380: num3 = 122; break; case 381: num3 = 90; break; case 382: num3 = 122; break; case 384: num3 = 98; break; case 393: num3 = 68; break; case 401: num3 = 159; break; case 402: num3 = 159; break; case 407: num3 = 73; break; case 410: num3 = 108; break; case 415: num3 = 79; break; case 416: num3 = 79; break; case 417: num3 = 111; break; case 425: num3 = 228; break; case 427: num3 = 116; break; case 430: num3 = 84; break; case 431: num3 = 85; break; case 432: num3 = 117; break; case 438: num3 = 122; break; case 448: num3 = 124; break; case 451: num3 = 33; break; case 461: num3 = 65; break; case 462: num3 = 97; break; case 463: num3 = 73; break; case 464: num3 = 105; break; case 465: num3 = 79; break; case 466: num3 = 111; break; case 467: num3 = 85; break; case 468: num3 = 117; break; case 469: num3 = 85; break; case 470: num3 = 117; break; case 471: num3 = 85; break; case 472: num3 = 117; break; case 473: num3 = 85; break; case 474: num3 = 117; break; case 475: num3 = 85; break; case 476: num3 = 117; break; case 478: num3 = 65; break; case 479: num3 = 97; break; case 484: num3 = 71; break; case 485: num3 = 103; break; case 486: num3 = 71; break; case 487: num3 = 103; break; case 488: num3 = 75; break; case 489: num3 = 107; break; case 490: num3 = 79; break; case 491: num3 = 111; break; case 492: num3 = 79; break; case 493: num3 = 111; break; case 496: num3 = 106; break; case 609: num3 = 103; break; case 632: num3 = 237; break; case 697: num3 = 39; break; case 698: num3 = 34; break; case 700: num3 = 39; break; case 708: num3 = 94; break; case 710: num3 = 94; break; case 712: num3 = 39; break; case 713: num3 = 196; break; case 714: num3 = 39; break; case 715: num3 = 96; break; case 717: num3 = 95; break; case 730: num3 = 248; break; case 732: num3 = 126; break; case 768: num3 = 96; break; case 769: num3 = 39; break; case 770: num3 = 94; break; case 771: num3 = 126; break; case 772: num3 = 196; break; case 776: num3 = 34; break; case 778: num3 = 248; break; case 782: num3 = 34; break; case 807: num3 = 44; break; case 817: num3 = 95; break; case 818: num3 = 95; break; case 894: num3 = 59; break; case 913: num3 = 224; break; case 915: num3 = 226; break; case 916: num3 = 235; break; case 917: num3 = 238; break; case 920: num3 = 233; break; case 928: num3 = 227; break; case 931: num3 = 228; break; case 932: num3 = 231; break; case 934: num3 = 232; break; case 937: num3 = 234; break; case 945: num3 = 224; break; case 946: num3 = 225; break; case 948: num3 = 235; break; case 949: num3 = 238; break; case 956: num3 = 230; break; case 960: num3 = 227; break; case 963: num3 = 229; break; case 964: num3 = 231; break; case 966: num3 = 237; break; case 1211: num3 = 104; break; case 1417: num3 = 58; break; case 1642: num3 = 37; break; case 8192: num3 = 32; break; case 8193: num3 = 32; break; case 8194: num3 = 32; break; case 8195: num3 = 32; break; case 8196: num3 = 32; break; case 8197: num3 = 32; break; case 8198: num3 = 32; break; case 8208: num3 = 45; break; case 8209: num3 = 45; break; case 8211: num3 = 45; break; case 8212: num3 = 45; break; case 8215: num3 = 95; break; case 8216: num3 = 96; break; case 8217: num3 = 39; break; case 8218: num3 = 44; break; case 8220: num3 = 34; break; case 8221: num3 = 34; break; case 8222: num3 = 44; break; case 8224: num3 = 43; break; case 8225: num3 = 216; break; case 8226: num3 = 7; break; case 8228: num3 = 250; break; case 8230: num3 = 46; break; case 8240: num3 = 37; break; case 8242: num3 = 39; break; case 8245: num3 = 96; break; case 8249: num3 = 60; break; case 8250: num3 = 62; break; case 8252: num3 = 19; break; case 8260: num3 = 47; break; case 8304: num3 = 248; break; case 8308: case 8309: case 8310: case 8311: case 8312: num3 -= 8256; break; case 8319: num3 = 252; break; case 8320: case 8321: case 8322: case 8323: case 8324: case 8325: case 8326: case 8327: case 8328: case 8329: num3 -= 8272; break; case 8356: num3 = 156; break; case 8359: num3 = 158; break; case 8413: num3 = 9; break; case 8450: num3 = 67; break; case 8455: num3 = 69; break; case 8458: num3 = 103; break; case 8459: num3 = 72; break; case 8460: num3 = 72; break; case 8461: num3 = 72; break; case 8462: num3 = 104; break; case 8464: num3 = 73; break; case 8465: num3 = 73; break; case 8466: num3 = 76; break; case 8467: num3 = 108; break; case 8469: num3 = 78; break; case 8472: num3 = 80; break; case 8473: num3 = 80; break; case 8474: num3 = 81; break; case 8475: num3 = 82; break; case 8476: num3 = 82; break; case 8477: num3 = 82; break; case 8482: num3 = 84; break; case 8484: num3 = 90; break; case 8486: num3 = 234; break; case 8488: num3 = 90; break; case 8490: num3 = 75; break; case 8491: num3 = 143; break; case 8492: num3 = 66; break; case 8493: num3 = 67; break; case 8494: num3 = 101; break; case 8495: num3 = 101; break; case 8496: num3 = 69; break; case 8497: num3 = 70; break; case 8499: num3 = 77; break; case 8500: num3 = 111; break; case 8592: num3 = 27; break; case 8593: num3 = 24; break; case 8594: num3 = 26; break; case 8595: num3 = 25; break; case 8596: num3 = 29; break; case 8597: num3 = 18; break; case 8616: num3 = 23; break; case 8709: num3 = 237; break; case 8721: num3 = 228; break; case 8722: num3 = 45; break; case 8723: num3 = 241; break; case 8725: num3 = 47; break; case 8726: num3 = 92; break; case 8727: num3 = 42; break; case 8728: num3 = 248; break; case 8729: num3 = 249; break; case 8730: num3 = 251; break; case 8734: num3 = 236; break; case 8735: num3 = 28; break; case 8739: num3 = 124; break; case 8745: num3 = 239; break; case 8758: num3 = 58; break; case 8764: num3 = 126; break; case 8776: num3 = 247; break; case 8801: num3 = 240; break; case 8804: num3 = 243; break; case 8805: num3 = 242; break; case 8810: num3 = 174; break; case 8811: num3 = 175; break; case 8901: num3 = 250; break; case 8962: num3 = 127; break; case 8963: num3 = 94; break; case 8976: num3 = 169; break; case 8992: num3 = 244; break; case 8993: num3 = 245; break; case 9001: num3 = 60; break; case 9002: num3 = 62; break; case 9472: num3 = 196; break; case 9474: num3 = 179; break; case 9484: num3 = 218; break; case 9488: num3 = 191; break; case 9492: num3 = 192; break; case 9496: num3 = 217; break; case 9500: num3 = 195; break; case 9508: num3 = 180; break; case 9516: num3 = 194; break; case 9524: num3 = 193; break; case 9532: num3 = 197; break; case 9552: num3 = 205; break; case 9553: num3 = 186; break; case 9554: num3 = 213; break; case 9555: num3 = 214; break; case 9556: num3 = 201; break; case 9557: num3 = 184; break; case 9558: num3 = 183; break; case 9559: num3 = 187; break; case 9560: num3 = 212; break; case 9561: num3 = 211; break; case 9562: num3 = 200; break; case 9563: num3 = 190; break; case 9564: num3 = 189; break; case 9565: num3 = 188; break; case 9566: num3 = 198; break; case 9567: num3 = 199; break; case 9568: num3 = 204; break; case 9569: num3 = 181; break; case 9570: num3 = 182; break; case 9571: num3 = 185; break; case 9572: num3 = 209; break; case 9573: num3 = 210; break; case 9574: num3 = 203; break; case 9575: num3 = 207; break; case 9576: num3 = 208; break; case 9577: num3 = 202; break; case 9578: num3 = 216; break; case 9579: num3 = 215; break; case 9580: num3 = 206; break; case 9600: num3 = 223; break; case 9604: num3 = 220; break; case 9608: num3 = 219; break; case 9612: num3 = 221; break; case 9616: num3 = 222; break; case 9617: num3 = 176; break; case 9618: num3 = 177; break; case 9619: num3 = 178; break; case 9632: num3 = 254; break; case 9644: num3 = 22; break; case 9650: num3 = 30; break; case 9658: num3 = 16; break; case 9660: num3 = 31; break; case 9668: num3 = 17; break; case 9675: num3 = 9; break; case 9688: num3 = 8; break; case 9689: num3 = 10; break; case 9786: num3 = 1; break; case 9787: num3 = 2; break; case 9788: num3 = 15; break; case 9792: num3 = 12; break; case 9794: num3 = 11; break; case 9824: num3 = 6; break; case 9827: num3 = 5; break; case 9829: num3 = 3; break; case 9830: num3 = 4; break; case 9834: num3 = 13; break; case 9835: num3 = 14; break; case 10003: num3 = 251; break; case 10072: num3 = 124; break; case 12288: num3 = 32; break; case 12295: num3 = 9; break; case 12296: num3 = 60; break; case 12297: num3 = 62; break; case 12298: num3 = 174; break; case 12299: num3 = 175; break; case 12314: num3 = 91; break; case 12315: num3 = 93; break; case 12539: num3 = 250; break; case 65281: case 65282: case 65283: case 65284: case 65285: case 65286: case 65287: case 65288: case 65289: case 65290: case 65291: case 65292: case 65293: case 65294: case 65295: case 65296: case 65297: case 65298: case 65299: case 65300: case 65301: case 65302: case 65303: case 65304: case 65305: case 65306: case 65307: case 65308: case 65309: case 65310: num3 -= 65248; break; case 65312: case 65313: case 65314: case 65315: case 65316: case 65317: case 65318: case 65319: case 65320: case 65321: case 65322: case 65323: case 65324: case 65325: case 65326: case 65327: case 65328: case 65329: case 65330: case 65331: case 65332: case 65333: case 65334: case 65335: case 65336: case 65337: case 65338: case 65339: case 65340: case 65341: case 65342: case 65343: case 65344: case 65345: case 65346: case 65347: case 65348: case 65349: case 65350: case 65351: case 65352: case 65353: case 65354: case 65355: case 65356: case 65357: case 65358: case 65359: case 65360: case 65361: case 65362: case 65363: case 65364: case 65365: case 65366: case 65367: case 65368: case 65369: case 65370: case 65371: case 65372: case 65373: case 65374: num3 -= 65248; break; default: ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCibm437 : CP437 { } [Serializable] public class CP850 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001c', '\u001b', '\u007f', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u001a', 'Ç', 'ü', 'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å', 'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', 'ø', '£', 'Ø', '×', 'ƒ', 'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '®', '¬', '½', '¼', '¡', '«', '»', '░', '▒', '▓', '│', '┤', 'Á', 'Â', 'À', '©', '╣', '║', '╗', '╝', '¢', '¥', '┐', '└', '┴', '┬', '├', '─', '┼', 'ã', 'Ã', '╚', '╔', '╩', '╦', '╠', '═', '╬', '¤', 'ð', 'Ð', 'Ê', 'Ë', 'È', 'ı', 'Í', 'Î', 'Ï', '┘', '┌', '█', '▄', '¦', 'Ì', '▀', 'Ó', 'ß', 'Ô', 'Ò', 'õ', 'Õ', 'µ', 'þ', 'Þ', 'Ú', 'Û', 'Ù', 'ý', 'Ý', '\u00af', '\u00b4', '\u00ad', '±', '‗', '¾', '¶', '§', '÷', '\u00b8', '°', '\u00a8', '·', '¹', '³', '²', '■', '\u00a0' }; public CP850() : base(850, ToChars, "Western European (DOS)", "ibm850", "ibm850", "ibm850", false, false, false, false, 1252) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 26) { switch (num3) { case 26: num3 = 127; break; case 28: num3 = 26; break; case 127: num3 = 28; break; case 160: num3 = 255; break; case 161: num3 = 173; break; case 162: num3 = 189; break; case 163: num3 = 156; break; case 164: num3 = 207; break; case 165: num3 = 190; break; case 166: num3 = 221; break; case 167: num3 = 245; break; case 168: num3 = 249; break; case 169: num3 = 184; break; case 170: num3 = 166; break; case 171: num3 = 174; break; case 172: num3 = 170; break; case 173: num3 = 240; break; case 174: num3 = 169; break; case 175: num3 = 238; break; case 176: num3 = 248; break; case 177: num3 = 241; break; case 178: num3 = 253; break; case 179: num3 = 252; break; case 180: num3 = 239; break; case 181: num3 = 230; break; case 182: num3 = 244; break; case 183: num3 = 250; break; case 184: num3 = 247; break; case 185: num3 = 251; break; case 186: num3 = 167; break; case 187: num3 = 175; break; case 188: num3 = 172; break; case 189: num3 = 171; break; case 190: num3 = 243; break; case 191: num3 = 168; break; case 192: num3 = 183; break; case 193: num3 = 181; break; case 194: num3 = 182; break; case 195: num3 = 199; break; case 196: num3 = 142; break; case 197: num3 = 143; break; case 198: num3 = 146; break; case 199: num3 = 128; break; case 200: num3 = 212; break; case 201: num3 = 144; break; case 202: num3 = 210; break; case 203: num3 = 211; break; case 204: num3 = 222; break; case 205: num3 = 214; break; case 206: num3 = 215; break; case 207: num3 = 216; break; case 208: num3 = 209; break; case 209: num3 = 165; break; case 210: num3 = 227; break; case 211: num3 = 224; break; case 212: num3 = 226; break; case 213: num3 = 229; break; case 214: num3 = 153; break; case 215: num3 = 158; break; case 216: num3 = 157; break; case 217: num3 = 235; break; case 218: num3 = 233; break; case 219: num3 = 234; break; case 220: num3 = 154; break; case 221: num3 = 237; break; case 222: num3 = 232; break; case 223: num3 = 225; break; case 224: num3 = 133; break; case 225: num3 = 160; break; case 226: num3 = 131; break; case 227: num3 = 198; break; case 228: num3 = 132; break; case 229: num3 = 134; break; case 230: num3 = 145; break; case 231: num3 = 135; break; case 232: num3 = 138; break; case 233: num3 = 130; break; case 234: num3 = 136; break; case 235: num3 = 137; break; case 236: num3 = 141; break; case 237: num3 = 161; break; case 238: num3 = 140; break; case 239: num3 = 139; break; case 240: num3 = 208; break; case 241: num3 = 164; break; case 242: num3 = 149; break; case 243: num3 = 162; break; case 244: num3 = 147; break; case 245: num3 = 228; break; case 246: num3 = 148; break; case 247: num3 = 246; break; case 248: num3 = 155; break; case 249: num3 = 151; break; case 250: num3 = 163; break; case 251: num3 = 150; break; case 252: num3 = 129; break; case 253: num3 = 236; break; case 254: num3 = 231; break; case 255: num3 = 152; break; case 272: num3 = 209; break; case 305: num3 = 213; break; case 402: num3 = 159; break; case 8215: num3 = 242; break; case 8226: num3 = 7; break; case 8252: num3 = 19; break; case 8254: num3 = 238; break; case 8592: num3 = 27; break; case 8593: num3 = 24; break; case 8594: num3 = 26; break; case 8595: num3 = 25; break; case 8596: num3 = 29; break; case 8597: num3 = 18; break; case 8616: num3 = 23; break; case 8735: num3 = 28; break; case 8962: num3 = 127; break; case 9472: num3 = 196; break; case 9474: num3 = 179; break; case 9484: num3 = 218; break; case 9488: num3 = 191; break; case 9492: num3 = 192; break; case 9496: num3 = 217; break; case 9500: num3 = 195; break; case 9508: num3 = 180; break; case 9516: num3 = 194; break; case 9524: num3 = 193; break; case 9532: num3 = 197; break; case 9552: num3 = 205; break; case 9553: num3 = 186; break; case 9556: num3 = 201; break; case 9559: num3 = 187; break; case 9562: num3 = 200; break; case 9565: num3 = 188; break; case 9568: num3 = 204; break; case 9571: num3 = 185; break; case 9574: num3 = 203; break; case 9577: num3 = 202; break; case 9580: num3 = 206; break; case 9600: num3 = 223; break; case 9604: num3 = 220; break; case 9608: num3 = 219; break; case 9617: num3 = 176; break; case 9618: num3 = 177; break; case 9619: num3 = 178; break; case 9632: num3 = 254; break; case 9644: num3 = 22; break; case 9650: num3 = 30; break; case 9658: num3 = 16; break; case 9660: num3 = 31; break; case 9668: num3 = 17; break; case 9675: num3 = 9; break; case 9688: num3 = 8; break; case 9689: num3 = 10; break; case 9786: num3 = 1; break; case 9787: num3 = 2; break; case 9788: num3 = 15; break; case 9792: num3 = 12; break; case 9794: num3 = 11; break; case 9824: num3 = 6; break; case 9827: num3 = 5; break; case 9829: num3 = 3; break; case 9830: num3 = 4; break; case 9834: num3 = 13; break; case 9836: num3 = 14; break; case 65512: num3 = 179; break; case 65513: num3 = 27; break; case 65514: num3 = 24; break; case 65515: num3 = 26; break; case 65516: num3 = 25; break; case 65517: num3 = 254; break; case 65518: num3 = 9; break; default: if (num3 >= 65281 && num3 <= 65374) { num3 -= 65248; } else { ((MonoEncoding)this).HandleFallback(ref encoderFallbackBuffer, chars, ref num, ref charCount, bytes, ref num2, ref byteCount); } break; case 27: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: break; } } bytes[num2++] = (byte)num3; charCount--; byteCount--; } } } [Serializable] public class ENCibm850 : CP850 { } [Serializable] public class CP860 : ByteEncoding { private static readonly char[] ToChars = new char[256] { '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b', '\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001c', '\u001b', '\u007f', '\u001d', '\u001e', '\u001f', ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '\u001a', 'Ç', 'ü', 'é', 'â', 'ã', 'à', 'Á', 'ç', 'ê', 'Ê', 'è', 'Í', 'Ô', 'ì', 'Ã', 'Â', 'É', 'À', 'È', 'ô', 'õ', 'ò', 'Ú', 'ù', 'Ì', 'Õ', 'Ü', '¢', '£', 'Ù', '₧', 'Ó', 'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', 'Ò', '¬', '½', '¼', '¡', '«', '»', '░', '▒', '▓', '│', '┤', '╡', '╢', '╖', '╕', '╣', '║', '╗', '╝', '╜', '╛', '┐', '└', '┴', '┬', '├', '─', '┼', '╞', '╟', '╚', '╔', '╩', '╦', '╠', '═', '╬', '╧', '╨', '╤', '╥', '╙', '╘', '╒', '╓', '╫', '╪', '┘', '┌', '█', '▄', '▌', '▐', '▀', 'α', 'ß', 'Γ', 'π', 'Σ', 'σ', 'μ', 'τ', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩', '≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'ⁿ', '²', '■', '\u00a0' }; public CP860() : base(860, ToChars, "Portuguese (DOS)", "ibm860", "ibm860", "ibm860", false, false, false, false, 1252) { } protected unsafe override void ToBytes(char* chars, int charCount, byte* bytes, int byteCount) { int num = 0; int num2 = 0; EncoderFallbackBuffer encoderFallbackBuffer = null; while (charCount > 0) { int num3 = *(ushort*)((byte*)chars + num++ * 2); if (num3 >= 26) { switch (num3) { case 26: num3 = 127; break; case 28: num3 = 26; break; case 127: num3 = 28; break; case 160: num3 = 255; break; case 161: num3 = 173; break; case 162: num3 = 155; break; case 163: num3 = 156; break; case 167: num3 = 21; break; case 170: num3 = 166; break; case 171: num3 = 174; break; case 172: num3 = 170; break; case 176: num3 = 248; break; case 177: num3 = 241; break; case 178: num3 = 253; break; case 182: num3 = 20; break; case 183: num3 = 250; break; case 186: num3 = 167; break; case 187: num3 = 175; break; case 188: num3 = 172; break; case 189: num3 = 171; break; case 191: num3 = 168; break; case 192: num3 = 145; break; case 193: num3 = 134; break; case 194: num3 = 143; break; case 195: num3 = 142; break; case 199: num3 = 128; break; case 200: num3 = 146; break; case 201: num3 = 144; break; case 202: num3 = 137; break; case 204: num3 = 152; break; case 205: num3 = 139; break; case 209: num3 = 165; break; case 210: num3 = 169; break; case 211: num3 = 159; break; case 212: num3 = 140; break; case 213: num3 = 153; break; case 217: num3 = 157; break; case 218: num3 = 150; break; case 220: num3 = 154; break; case 223: num3 = 225; break; case 224: num3 = 133; break; case 225: num3 = 160; break; case 226: num3 = 131; break; case 227: num3 = 132; break; case 231: num3 = 135; break; case 232: num3 = 138; break; case 233: num3 = 130; break; case 234: num3 = 136; break; case 236: num3 = 141; break; case 237: num3 = 161; break; case 241: num3 = 164; break; case 242: num3 = 149; break; case 243: num3 = 162; break; case 244: num3 = 147; break; case 245: num3 = 148; break; case 247: num3 = 246; break; case 249: num3 = 151; break; case 250: num3 = 163; break; case 252: num3 = 129; break; case 915: num3 = 226; break; case 920: num3 = 233; break; case 931: num3 = 228; break; case 934: num3 = 232; break; case 937: num3 = 234; break; case 945: num3 = 224; break; case 948: num3 = 235; break; case 949: num3 = 238; break; case 956: num3 = 230; break; case 960: num3 = 227; break; case 963: num3 = 229; break; case 964: num3 = 231; break; case 966: num3 = 237; break; case 8226: num3 = 7; break; case 8252: num3 = 19; break; case 8319: num3 = 252; break; case 8359: num3 = 158; break; case 8592: num3 = 27; break; case 8593: num3 = 24; break; case 8594: num3 = 26; break; case 8595: num3 = 25; break; case 8596: num3 = 29; break; case 8597: num3 = 18; break; case 8616: num3 = 23; break; case 8729: num3 = 249; break; case 8730: num3 = 251; break; case 8734: num3 = 236; break; case 8735: num3 = 28; break; case 8745: num3 = 239; break; case 8776: num3 = 247; break; case 8801: num3 = 240; break; case 8804: num3 = 243; break; case 8805: num3 = 242; break; case 8962: num3 = 127; break; c
patchers/Newtonsoft.Json.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyTrademark("")] [assembly: CLSCompliant(true)] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyFileVersion("11.0.1")] [assembly: AssemblyInformationalVersion("11.0.1-beta2+bdfeb80d3eb277241ce8f051a360c9461b33afc5")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET .NET 3.5")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("11.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } } namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } public class DefaultJsonNameTable : JsonNameTable { private class Entry { internal readonly string Value; internal readonly int HashCode; internal Entry Next; internal Entry(string value, int hashCode, Entry next) { Value = value; HashCode = hashCode; Next = next; } } private static readonly int HashCodeRandomizer; private int _count; private Entry[] _entries; private int _mask = 31; static DefaultJsonNameTable() { HashCodeRandomizer = Environment.TickCount; } public DefaultJsonNameTable() { _entries = new Entry[_mask + 1]; } public override string? Get(char[] key, int start, int length) { if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; num += (num << 7) ^ key[start]; int num2 = start + length; for (int i = start + 1; i < num2; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; int num3 = num & _mask; for (Entry entry = _entries[num3]; entry != null; entry = entry.Next) { if (entry.HashCode == num && TextEquals(entry.Value, key, start, length)) { return entry.Value; } } return null; } public string Add(string key) { if (key == null) { throw new ArgumentNullException("key"); } int length = key.Length; if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } } return AddEntry(key, num); } private string AddEntry(string str, int hashCode) { int num = hashCode & _mask; Entry entry = new Entry(str, hashCode, _entries[num]); _entries[num] = entry; if (_count++ == _mask) { Grow(); } return entry.Value; } private void Grow() { Entry[] entries = _entries; int num = _mask * 2 + 1; Entry[] array = new Entry[num + 1]; for (int i = 0; i < entries.Length; i++) { Entry entry = entries[i]; while (entry != null) { int num2 = entry.HashCode & num; Entry next = entry.Next; entry.Next = array[num2]; array[num2] = entry; entry = next; } } _entries = array; _mask = num; } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[]? array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type? _namingStrategyType; private object[]? _namingStrategyParameters; public string? Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[]? NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy? NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings>? DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri? value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string? value) { return ToString(value, '"'); } public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object? value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { 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); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(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, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if ((object)converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get; set; } public object[]? NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public int Order { get { return _order.GetValueOrDefault(); } set { _order = value; } } public Required Required { get { return _required.GetValueOrDefault(); } set { _required = value; } } public string? PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string? _dateFormatString; private List<JsonPosition>? _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string? DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object? Value => _value; public virtual Type? ValueType => _value?.GetType(); public virtual int Depth { get { int num = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; _maxDepth = 64; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth) { return; } _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is int) { return (int)value; } int num; try { num = Convert.ToInt32(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } SetToken(JsonToken.Integer, num, updateIndex: false); return num; } case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string? ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken)) { object value = Value; if (value != null) { string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture)); SetToken(JsonToken.String, text, updateIndex: false); return text; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[]? ReadAsBytes() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] array2 = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid guid) { byte[] array = guid.ToByteArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); do { if (!Read()) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(list)); byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is double) { return (double)value; } double num = Convert.ToDouble(value, CultureInfo.InvariantCulture); SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is decimal) { return (decimal)value; } decimal num; try { num = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset dateTimeOffset) { SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: return ReadDateTimeString((string)Value); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime dateTime) { SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { _currentState = ((!SupportMultipleContent) ? State.Finished : State.Start); } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract? contract, bool hasConverter) { if (hasConverter) { return Read(); } switch (contract?.InternalReadType ?? ReadType.Read) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: { bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; } case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; default: throw new ArgumentOutOfRangeException(); } return TokenType != JsonToken.None; } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } 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) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, path, lineNumber, linePosition, ex); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } 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) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonSerializationException(message, path, lineNumber, linePosition, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; internal ITraceWriter? _traceWriter; internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string? _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver? ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder is SerializationBinder result) { return result; } if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value); } } public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = value; } } public virtual ITraceWriter? TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer? EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent.GetValueOrDefault(); } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling.HasValue) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } [DebuggerStepThrough] public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } [DebuggerStepThrough] public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } [DebuggerStepThrough] public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } [DebuggerStepThrough] public T? Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } internal 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)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable(); } } private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable()) { jsonTextReader.PropertyNameTable = null; } } public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceJsonReader = new TraceJsonReader(reader); if (reader.TokenType != 0) { traceJsonReader.WriteCurrentToken(); } return traceJsonReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter? GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple; 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; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo? _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string? _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling.GetValueOrDefault(); } set { _preserveReferencesHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling.GetValueOrDefault(); } set { _metadataPropertyHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)TypeNameAssemblyFormatHandling; } set { TypeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling.GetValueOrDefault(); } set { _typeNameAssemblyFormatHandling = value; } } public ConstructorHandling ConstructorHandling { get { return _constructorHandling.GetValueOrDefault(); } set { _constructorHandling = value; } } public IContractResolver? ContractResolver { get; set; } public IEqualityComparer? EqualityComparer { get; set; } [Obsolete("ReferenceResolver property is obsolete. Use the ReferenceResolverProvider property to set the IReferenceResolver: settings.ReferenceResolverProvider = () => resolver")] public IReferenceResolver? ReferenceResolver { get { return ReferenceResolverProvider?.Invoke(); } set { IReferenceResolver value2 = value; ReferenceResolverProvider = ((value2 != null) ? ((Func<IReferenceResolver>)(() => value2)) : null); } } public Func<IReferenceResolver?>? ReferenceResolverProvider { get; set; } public ITraceWriter? TraceWriter { get; set; } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public SerializationBinder? Binder { get { if (SerializationBinder == null) { return null; } if (SerializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { SerializationBinder = ((value == null) ? null : new SerializationBinderAdapter(value)); } } public ISerializationBinder? SerializationBinder { get; set; } public EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error { get; set; } public StreamingContext Context { get { return _context ?? DefaultContext; } set { _context = value; } } public string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public int? MaxDepth { get { if (!_maxDepthSet) { return 64; } return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public CultureInfo Culture { get { return _culture ?? DefaultCulture; } set { _culture = value; } } public bool CheckAdditionalContent { get { return _checkAdditionalContent.GetValueOrDefault(); } set { _checkAdditionalContent = value; } } static JsonSerializerSettings() { DefaultContext = default(StreamingContext); DefaultCulture = CultureInfo.InvariantCulture; } [DebuggerStepThrough] public JsonSerializerSettings() { Converters = new List<JsonConverter>(); } } internal enum ReadType { Read, ReadAsInt32, ReadAsInt64, ReadAsBytes, ReadAsString, ReadAsDecimal, ReadAsDateTime, ReadAsDateTimeOffset, ReadAsDouble, ReadAsBoolean } public class JsonTextReader : JsonReader, IJsonLineInfo { private const char UnicodeReplacementChar = '\ufffd'; private const int LargeBufferLength = 1073741823; private readonly TextReader _reader; private char[]? _chars; private int _charsUsed; private int _charPos; private int _lineStartPos; private int _lineNumber; private bool _isEndOfFile; private StringBuffer _stringBuffer; private StringReference _stringReference; private IArrayPool<char>? _arrayPool; public JsonNameTable? PropertyNameTable { get; set; } public IArrayPool<char>? ArrayPool { get { return _arrayPool; } set { if (value == null) { throw new ArgumentNullException("value"); } _arrayPool = value; } } public int LineNumber { get { if (base.CurrentState == State.Start && LinePosition == 0 && TokenType != JsonToken.Comment) { return 0; } return _lineNumber; } } public int LinePosition => _charPos - _lineStartPos; public JsonTextReader(TextReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } _reader = reader; _lineNumber = 1; } private void EnsureBufferNotEmpty() { if (_stringBuffer.IsEmpty) { _stringBuffer = new StringBuffer(_arrayPool, 1024); } } private void SetNewLine(bool hasNextChar) { if (hasNextChar && _chars[_charPos] == '\n') { _charPos++; } OnNewLine(_charPos); } private void OnNewLine(int pos) { _lineNumber++; _lineStartPos = pos; } private void ParseString(char quote, ReadType readType) { _charPos++; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quote); ParseReadString(quote, readType); } private void ParseReadString(char quote, ReadType readType) { SetPostValueState(updateIndex: true); switch (readType) { case ReadType.ReadAsBytes: { Guid g; byte[] value2 = ((_stringReference.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((_stringReference.Length != 36 || !ConvertUtils.TryConvertGuid(_stringReference.ToString(), out g)) ? Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length) : g.ToByteArray())); SetToken(JsonToken.Bytes, value2, updateIndex: false); return; } case ReadType.ReadAsString: { string value = _stringReference.ToString(); SetToken(JsonToken.String, value, updateIndex: false); _quoteChar = quote; return; } case ReadType.ReadAsInt32: case ReadType.ReadAsDecimal: case ReadType.ReadAsBoolean: return; } if (_dateParseHandling != 0) { DateTimeOffset dt2; if (readType switch { ReadType.ReadAsDateTime => 1, ReadType.ReadAsDateTimeOffset => 2, _ => (int)_dateParseHandling, } == 1) { if (DateTimeUtils.TryParseDateTime(_stringReference, base.DateTimeZoneHandling, base.DateFormatString, base.Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return; } } else if (DateTimeUtils.TryParseDateTimeOffset(_stringReference, base.DateFormatString, base.Culture, out dt2)) { SetToken(JsonToken.Date, dt2, updateIndex: false); return; } } SetToken(JsonToken.String, _stringReference.ToString(), updateIndex: false); _quoteChar = quote; } private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) { Buffer.BlockCopy(src, srcOffset * 2, dst, dstOffset * 2, count * 2); } private void ShiftBufferIfNeeded() { int num = _chars.Length; if ((double)(num - _charPos) <= (double)num * 0.1 || num >= 1073741823) { int num2 = _charsUsed - _charPos; if (num2 > 0) { BlockCopyChars(_chars, _charPos, _chars, 0, num2); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = num2; _chars[_charsUsed] = '\0'; } } private int ReadData(bool append) { return ReadData(append, 0); } private void PrepareBufferForReadData(bool append, int charsRequired) { if (_charsUsed + charsRequired < _chars.Length - 1) { return; } if (append) { int num = _chars.Length * 2; int minSize = Math.Ma
patchers/YamlDotNet.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.0", FrameworkDisplayName = "")] [assembly: AssemblyVersion("0.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System { internal sealed class Lazy<T> { private enum ValueState { NotCreated, Creating, Created } private T value; private Func<T>? valueFactory; private ValueState valueState; private readonly bool isThreadSafe; public T Value { get { if (isThreadSafe) { lock (this) { return ComputeValue(); } } return ComputeValue(); } } public Lazy(T value) { this.value = value; valueState = ValueState.Created; } public Lazy(Func<T> valueFactory) { this.valueFactory = valueFactory; isThreadSafe = false; valueState = ValueState.NotCreated; } public Lazy(Func<T> valueFactory, bool isThreadSafe) { this.valueFactory = valueFactory; this.isThreadSafe = isThreadSafe; valueState = ValueState.NotCreated; value = default(T); } private T ComputeValue() { switch (valueState) { case ValueState.NotCreated: valueState = ValueState.Creating; value = valueFactory(); valueState = ValueState.Created; valueFactory = null; break; case ValueState.Creating: throw new InvalidOperationException("ValueFactory attempted to access the Value property of this instance."); } return value; } } public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetFrameworkAttribute : Attribute { public string FrameworkName { get; set; } public string? FrameworkDisplayName { get; set; } public TargetFrameworkAttribute(string frameworkName) { FrameworkName = frameworkName; } } } namespace System.Runtime.CompilerServices { internal sealed class TupleElementNamesAttribute : Attribute { public IList<string?> TransformNames { get; } public TupleElementNamesAttribute(string?[] transformNames) { TransformNames = transformNames; } } } namespace System.Linq { internal static class Enumerable2 { public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) { using IEnumerator<TFirst> firstEnumerator = first.GetEnumerator(); using IEnumerator<TSecond> secondEnumerator = second.GetEnumerator(); while (firstEnumerator.MoveNext() && secondEnumerator.MoveNext()) { yield return resultSelector(firstEnumerator.Current, secondEnumerator.Current); } } } } namespace System.Collections.Concurrent { internal sealed class ConcurrentDictionary<TKey, TValue> { public delegate TValue ValueFactory(TKey key); private readonly Dictionary<TKey, TValue> entries = new Dictionary<TKey, TValue>(); public TValue GetOrAdd(TKey key, ValueFactory valueFactory) { lock (entries) { if (!entries.TryGetValue(key, out var value)) { value = valueFactory(key); entries.Add(key, value); } return value; } } public bool TryAdd(TKey key, TValue value) { lock (entries) { if (!entries.ContainsKey(key)) { entries.Add(key, value); return true; } return false; } } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { lock (entries) { return entries.TryGetValue(key, out value); } } } } namespace System.Collections.Generic { internal static class DeconstructionExtensions { public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } } public interface IReadOnlyCollection<T> : IEnumerable<T>, IEnumerable { int Count { get; } } public interface IReadOnlyDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IReadOnlyCollection<KeyValuePair<TKey, TValue>> where TKey : notnull { TValue this[TKey key] { get; } IEnumerable<TKey> Keys { get; } IEnumerable<TValue> Values { get; } bool ContainsKey(TKey key); bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value); } public interface IReadOnlyList<T> : IEnumerable<T>, IEnumerable, IReadOnlyCollection<T> { T this[int index] { get; } } } namespace YamlDotNet { internal static class PropertyInfoExtensions { public static object? ReadValue(this PropertyInfo property, object target) { return property.GetGetMethod().Invoke(target, null); } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.None; } internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.LCID) { this.provider = provider; } public override object? GetFormat(Type? formatType) { return provider.GetFormat(formatType); } } internal static class ReflectionExtensions { private static readonly FieldInfo? RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); public static Type? BaseType(this Type type) { return type.BaseType; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsDbNull(this object value) { return value is DBNull; } public static bool HasDefaultConstructor(this Type type) { if (!type.IsValueType) { return (object)type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null) != null; } return true; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static PropertyInfo? GetPublicProperty(this Type type, string name) { return type.GetProperty(name); } public static FieldInfo? GetPublicStaticField(this Type type, string name) { return type.GetField(name, BindingFlags.Static | BindingFlags.Public); } public static IEnumerable<PropertyInfo> GetProperties(this Type type, bool includeNonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (includeNonPublic) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsInterface) { return type.GetProperties(bindingFlags); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetProperties(bindingFlags)); } public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type) { return type.GetProperties(includeNonPublic: false); } public static IEnumerable<FieldInfo> GetPublicFields(this Type type) { return type.GetFields(BindingFlags.Instance | BindingFlags.Public); } public static IEnumerable<MethodInfo> GetPublicStaticMethods(this Type type) { return type.GetMethods(BindingFlags.Static | BindingFlags.Public); } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null); } public static MethodInfo? GetPublicInstanceMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public); } public static Exception Unwrap(this TargetInvocationException ex) { Exception innerException = ex.InnerException; if (innerException == null) { return ex; } if ((object)RemoteStackTraceField != null) { RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n"); } return innerException; } public static bool IsInstanceOf(this Type type, object o) { return type.IsInstanceOfType(o); } public static Attribute[] GetAllCustomAttributes<TAttribute>(this PropertyInfo property) { return Attribute.GetCustomAttributes(property, typeof(TAttribute)); } } } namespace YamlDotNet.Serialization { public abstract class BuilderSkeleton<TBuilder> where TBuilder : BuilderSkeleton<TBuilder> { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly YamlAttributeOverrides overrides; internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories; internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories; private bool ignoreFields; private bool includeNonPublicProperties; protected abstract TBuilder Self { get; } internal BuilderSkeleton(ITypeResolver typeResolver) { overrides = new YamlAttributeOverrides(); typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter> { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) }, { typeof(SystemTypeConverter), (Nothing _) => new SystemTypeConverter() } }; typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = true; return Self; } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithAttributeOverride<TClass>(Expression<Func<TClass, object>> propertyAccessor, Attribute attribute) { overrides.Add(propertyAccessor, attribute); return Self; } public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute) { overrides.Add(type, member, attribute); return Self; } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) { IYamlTypeConverter typeConverter2 = typeConverter; if (typeConverter2 == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2)); return Self; } public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter { WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory2 = typeConverterFactory; if (typeConverterFactory2 == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped))); return Self; } public TBuilder WithoutTypeConverter<TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if ((object)converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w) { w.OnTop(); }); } public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector { Func<ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner))); return Self; } public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector { WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector<TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if ((object)inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable<IYamlTypeConverter> BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } public delegate TComponent WrapperFactory<TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase; public delegate TComponent WrapperFactory<TArgument, TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] public enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } public sealed class Deserializer : IDeserializer { private readonly IValueDeserializer valueDeserializer; public Deserializer() : this(new DeserializerBuilder().BuildValueDeserializer()) { } private Deserializer(IValueDeserializer valueDeserializer) { this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer"); } public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer) { return new Deserializer(valueDeserializer); } public T Deserialize<T>(string input) { using StringReader input2 = new StringReader(input); return Deserialize<T>(input2); } public T Deserialize<T>(TextReader input) { return Deserialize<T>(new Parser(input)); } public object? Deserialize(TextReader input) { return Deserialize(input, typeof(object)); } public object? Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } public object? Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } public T Deserialize<T>(IParser parser) { return (T)Deserialize(parser, typeof(T)); } public object? Deserialize(IParser parser) { return Deserialize(parser, typeof(object)); } public object? Deserialize(IParser parser, Type type) { if (parser == null) { throw new ArgumentNullException("parser"); } if ((object)type == null) { throw new ArgumentNullException("type"); } YamlDotNet.Core.Events.StreamStart @event; bool flag = parser.TryConsume<YamlDotNet.Core.Events.StreamStart>(out @event); YamlDotNet.Core.Events.DocumentStart event2; bool flag2 = parser.TryConsume<YamlDotNet.Core.Events.DocumentStart>(out event2); object result = null; if (!parser.Accept<YamlDotNet.Core.Events.DocumentEnd>(out var _) && !parser.Accept<YamlDotNet.Core.Events.StreamEnd>(out var _)) { using SerializerState serializerState = new SerializerState(); result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer); serializerState.OnDeserialization(); } if (flag2) { parser.Consume<YamlDotNet.Core.Events.DocumentEnd>(); } if (flag) { parser.Consume<YamlDotNet.Core.Events.StreamEnd>(); } return result; } } public sealed class DeserializerBuilder : BuilderSkeleton<DeserializerBuilder> { private Lazy<IObjectFactory> objectFactory; private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories; private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories; private readonly Dictionary<TagName, Type> tagMappings; private readonly Dictionary<Type, Type> typeMappings; private bool ignoreUnmatched; protected override DeserializerBuilder Self => this; public DeserializerBuilder() : base((ITypeResolver)new StaticTypeResolver()) { typeMappings = new Dictionary<Type, Type>(); objectFactory = new Lazy<IObjectFactory>(() => new DefaultObjectFactory(typeMappings), isThreadSafe: true); tagMappings = new Dictionary<TagName, Type> { { FailsafeSchema.Tags.Map, typeof(Dictionary<object, object>) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList<Nothing, INodeDeserializer> { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer() }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer() }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver> { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; } public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory) { IObjectFactory objectFactory2 = objectFactory; if (objectFactory2 == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy<IObjectFactory>(() => objectFactory2, isThreadSafe: true); return this; } public DeserializerBuilder WithObjectFactory(Func<Type, object> objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } return WithObjectFactory(new LambdaObjectFactory(objectFactory)); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w) { w.OnTop(); }); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where) { INodeDeserializer nodeDeserializer2 = nodeDeserializer; if (nodeDeserializer2 == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2)); return this; } public DeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer { WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory2 = nodeDeserializerFactory; if (nodeDeserializerFactory2 == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer<TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if ((object)nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) { INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver; if (nodeTypeResolver2 == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2)); return this; } public DeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver { WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory2 = nodeTypeResolverFactory; if (nodeTypeResolverFactory2 == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeTypeResolver<TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if ((object)nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override DeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if ((object)type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out Type value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public DeserializerBuilder WithTypeMapping<TInterface, TConcrete>() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (typeMappings.ContainsKey(typeFromHandle)) { typeMappings[typeFromHandle] = typeFromHandle2; } else { typeMappings.Add(typeFromHandle, typeFromHandle2); } return this; } public DeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public DeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList())); } } public sealed class EmissionPhaseObjectGraphVisitorArgs { private readonly IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors; public IObjectGraphVisitor<IEmitter> InnerVisitor { get; private set; } public IEventEmitter EventEmitter { get; private set; } public ObjectSerializer NestedObjectSerializer { get; private set; } public IEnumerable<IYamlTypeConverter> TypeConverters { get; private set; } public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor<IEmitter> innerVisitor, IEventEmitter eventEmitter, IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors, IEnumerable<IYamlTypeConverter> typeConverters, ObjectSerializer nestedObjectSerializer) { InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor"); EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter"); this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors"); TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters"); NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer"); } public T GetPreProcessingPhaseObjectGraphVisitor<T>() where T : IObjectGraphVisitor<Nothing> { return preProcessingPhaseVisitors.OfType<T>().Single(); } } public abstract class EventInfo { public IObjectDescriptor Source { get; } protected EventInfo(IObjectDescriptor source) { Source = source ?? throw new ArgumentNullException("source"); } } public class AliasEventInfo : EventInfo { public AnchorName Alias { get; } public bool NeedsExpansion { get; set; } public AliasEventInfo(IObjectDescriptor source, AnchorName alias) : base(source) { if (alias.IsEmpty) { throw new ArgumentNullException("alias"); } Alias = alias; } } public class ObjectEventInfo : EventInfo { public AnchorName Anchor { get; set; } public TagName Tag { get; set; } protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } public sealed class ScalarEventInfo : ObjectEventInfo { public string RenderedValue { get; set; } public ScalarStyle Style { get; set; } public bool IsPlainImplicit { get; set; } public bool IsQuotedImplicit { get; set; } public ScalarEventInfo(IObjectDescriptor source) : base(source) { Style = source.ScalarStyle; RenderedValue = string.Empty; } } public sealed class MappingStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public MappingStyle Style { get; set; } public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } public sealed class MappingEndEventInfo : EventInfo { public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } public sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } public sealed class SequenceEndEventInfo : EventInfo { public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } public interface IAliasProvider { AnchorName GetAlias(object target); } public interface IDeserializer { T Deserialize<T>(string input); T Deserialize<T>(TextReader input); object? Deserialize(TextReader input); object? Deserialize(string input, Type type); object? Deserialize(TextReader input, Type type); T Deserialize<T>(IParser parser); object? Deserialize(IParser parser); object? Deserialize(IParser parser, Type type); } public interface IEventEmitter { void Emit(AliasEventInfo eventInfo, IEmitter emitter); void Emit(ScalarEventInfo eventInfo, IEmitter emitter); void Emit(MappingStartEventInfo eventInfo, IEmitter emitter); void Emit(MappingEndEventInfo eventInfo, IEmitter emitter); void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter); } public interface INamingConvention { string Apply(string value); } public interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value); } public interface INodeTypeResolver { bool Resolve(NodeEvent? nodeEvent, ref Type currentType); } public interface IObjectDescriptor { object? Value { get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } public static class ObjectDescriptorExtensions { public static object NonNullValue(this IObjectDescriptor objectDescriptor) { return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet."); } } public interface IObjectFactory { object Create(Type type); } public interface IObjectGraphTraversalStrategy { void Traverse<TContext>(IObjectDescriptor graph, IObjectGraphVisitor<TContext> visitor, TContext context); } public interface IObjectGraphVisitor<TContext> { bool Enter(IObjectDescriptor value, TContext context); bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context); bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context); void VisitScalar(IObjectDescriptor scalar, TContext context); void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context); void VisitMappingEnd(IObjectDescriptor mapping, TContext context); void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context); void VisitSequenceEnd(IObjectDescriptor sequence, TContext context); } public interface IPropertyDescriptor { string Name { get; } bool CanWrite { get; } Type Type { get; } Type? TypeOverride { get; set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } T GetCustomAttribute<T>() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, object? value); } public interface IRegistrationLocationSelectionSyntax<TBaseRegistrationType> { void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType; void Before<TRegistrationType>() where TRegistrationType : TBaseRegistrationType; void After<TRegistrationType>() where TRegistrationType : TBaseRegistrationType; void OnTop(); void OnBottom(); } public interface ITrackingRegistrationLocationSelectionSyntax<TBaseRegistrationType> { void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType; } public interface ISerializer { void Serialize(TextWriter writer, object graph); string Serialize(object graph); void Serialize(TextWriter writer, object graph, Type type); void Serialize(IEmitter emitter, object graph); void Serialize(IEmitter emitter, object graph, Type type); } public interface ITypeInspector { IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container); IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched); } public interface ITypeResolver { Type Resolve(Type staticType, object? actualValue); } public interface IValueDeserializer { object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); } public interface IValuePromise { event Action<object?> ValueAvailable; } public interface IValueSerializer { void SerializeValue(IEmitter emitter, object? value, Type? type); } public interface IYamlConvertible { void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } public delegate object? ObjectDeserializer(Type type); public delegate void ObjectSerializer(object? value, Type? type = null); [Obsolete("Please use IYamlConvertible instead")] public interface IYamlSerializable { void ReadYaml(IParser parser); void WriteYaml(IEmitter emitter); } public interface IYamlTypeConverter { bool Accepts(Type type); object? ReadYaml(IParser parser, Type type); void WriteYaml(IEmitter emitter, object? value, Type type); } internal sealed class LazyComponentRegistrationList<TArgument, TComponent> : IEnumerable<Func<TArgument, TComponent>>, IEnumerable { public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func<TArgument, TComponent> Factory; public LazyComponentRegistration(Type componentType, Func<TArgument, TComponent> factory) { ComponentType = componentType; Factory = factory; } } public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func<TComponent, TArgument, TComponent> Factory; public TrackingLazyComponentRegistration(Type componentType, Func<TComponent, TArgument, TComponent> factory) { ComponentType = componentType; Factory = factory; } } private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax<TComponent> { private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations; private readonly LazyComponentRegistration newRegistration; public RegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, LazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void IRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>() { if ((object)newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists<TRegistrationType>(); registrations.entries[index] = newRegistration; } void IRegistrationLocationSelectionSyntax<TComponent>.After<TRegistrationType>() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int num = registrations.EnsureRegistrationExists<TRegistrationType>(); registrations.entries.Insert(num + 1, newRegistration); } void IRegistrationLocationSelectionSyntax<TComponent>.Before<TRegistrationType>() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int index = registrations.EnsureRegistrationExists<TRegistrationType>(); registrations.entries.Insert(index, newRegistration); } void IRegistrationLocationSelectionSyntax<TComponent>.OnBottom() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Add(newRegistration); } void IRegistrationLocationSelectionSyntax<TComponent>.OnTop() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Insert(0, newRegistration); } } private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax<TComponent> { private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations; private readonly TrackingLazyComponentRegistration newRegistration; public TrackingRegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, TrackingLazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void ITrackingRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>() { if ((object)newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists<TRegistrationType>(); Func<TArgument, TComponent> innerComponentFactory = registrations.entries[index].Factory; registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } private readonly List<LazyComponentRegistration> entries = new List<LazyComponentRegistration>(); public int Count => entries.Count; public IEnumerable<Func<TArgument, TComponent>> InReverseOrder { get { int i = entries.Count - 1; while (i >= 0) { yield return entries[i].Factory; int num = i - 1; i = num; } } } public LazyComponentRegistrationList<TArgument, TComponent> Clone() { LazyComponentRegistrationList<TArgument, TComponent> lazyComponentRegistrationList = new LazyComponentRegistrationList<TArgument, TComponent>(); foreach (LazyComponentRegistration entry in entries) { lazyComponentRegistrationList.entries.Add(entry); } return lazyComponentRegistrationList; } public void Add(Type componentType, Func<TArgument, TComponent> factory) { entries.Add(new LazyComponentRegistration(componentType, factory)); } public void Remove(Type componentType) { for (int i = 0; i < entries.Count; i++) { if ((object)entries[i].ComponentType == componentType) { entries.RemoveAt(i); return; } } throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found."); } public IRegistrationLocationSelectionSyntax<TComponent> CreateRegistrationLocationSelector(Type componentType, Func<TArgument, TComponent> factory) { return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory)); } public ITrackingRegistrationLocationSelectionSyntax<TComponent> CreateTrackingRegistrationLocationSelector(Type componentType, Func<TComponent, TArgument, TComponent> factory) { return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory)); } public IEnumerator<Func<TArgument, TComponent>> GetEnumerator() { return entries.Select((LazyComponentRegistration e) => e.Factory).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private int IndexOfRegistration(Type registrationType) { for (int i = 0; i < entries.Count; i++) { if ((object)registrationType == entries[i].ComponentType) { return i; } } return -1; } private void EnsureNoDuplicateRegistrationType(Type componentType) { if (IndexOfRegistration(componentType) != -1) { throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered."); } } private int EnsureRegistrationExists<TRegistrationType>() { int num = IndexOfRegistration(typeof(TRegistrationType)); if (num == -1) { throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered."); } return num; } } internal static class LazyComponentRegistrationListExtensions { public static TComponent BuildComponentChain<TComponent>(this LazyComponentRegistrationList<TComponent, TComponent> registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TComponent, TComponent> factory) => factory(inner)); } public static TComponent BuildComponentChain<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TComponent innerComponent, Func<TComponent, TArgument> argumentBuilder) { Func<TComponent, TArgument> argumentBuilder2 = argumentBuilder; return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TArgument, TComponent> factory) => factory(argumentBuilder2(inner))); } public static List<TComponent> BuildComponentList<TComponent>(this LazyComponentRegistrationList<Nothing, TComponent> registrations) { return registrations.Select((Func<Nothing, TComponent> factory) => factory(default(Nothing))).ToList(); } public static List<TComponent> BuildComponentList<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TArgument argument) { TArgument argument2 = argument; return registrations.Select((Func<TArgument, TComponent> factory) => factory(argument2)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct Nothing { } public sealed class ObjectDescriptor : IObjectDescriptor { public object? Value { get; private set; } public Type Type { get; private set; } public Type StaticType { get; private set; } public ScalarStyle ScalarStyle { get; private set; } public ObjectDescriptor(object? value, Type type, Type staticType) : this(value, type, staticType, ScalarStyle.Any) { } public ObjectDescriptor(object? value, Type type, Type staticType, ScalarStyle scalarStyle) { Value = value; Type = type ?? throw new ArgumentNullException("type"); StaticType = staticType ?? throw new ArgumentNullException("staticType"); ScalarStyle = scalarStyle; } } public delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion); public sealed class PropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; public string Name { get; set; } public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public int Order { get; set; } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public bool CanWrite => baseDescriptor.CanWrite; public PropertyDescriptor(IPropertyDescriptor baseDescriptor) { this.baseDescriptor = baseDescriptor; Name = baseDescriptor.Name; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T GetCustomAttribute<T>() where T : Attribute { return baseDescriptor.GetCustomAttribute<T>(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } public sealed class Serializer : ISerializer { private readonly IValueSerializer valueSerializer; private readonly EmitterSettings emitterSettings; public Serializer() : this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default) { } private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer"); this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings"); } public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { return new Serializer(valueSerializer, emitterSettings); } public void Serialize(TextWriter writer, object graph) { Serialize(new Emitter(writer, emitterSettings), graph); } public string Serialize(object graph) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph); return stringWriter.ToString(); } public void Serialize(TextWriter writer, object graph, Type type) { Serialize(new Emitter(writer, emitterSettings), graph, type); } public void Serialize(IEmitter emitter, object graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, graph, null); } public void Serialize(IEmitter emitter, object graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if ((object)type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } private void EmitDocument(IEmitter emitter, object graph, Type? type) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); valueSerializer.SerializeValue(emitter, graph, type); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: true)); emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } } public sealed class SerializerBuilder : BuilderSkeleton<SerializerBuilder> { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable<IYamlTypeConverter> typeConverters; private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<IYamlTypeConverter> typeConverters, LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { IEmitter emitter2 = emitter; Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List<IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor<Nothing> item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing)); } IObjectGraphVisitor<IEmitter> visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor<IEmitter> inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter2); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter2, v, t); } } } private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories; private readonly IDictionary<Type, TagName> tagMappings = new Dictionary<Type, TagName>(); private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; protected override SerializerBuilder Self => this; public SerializerBuilder() : base((ITypeResolver)new DynamicTypeResolver()) { typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> { { typeof(AnchorAssigner), (IEnumerable<IYamlTypeConverter> typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<AnchorAssigner>()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList<IEventEmitter, IEventEmitter> { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings) } }; objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention); } public SerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory, Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter { Func<IEventEmitter, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory2(inner))); return Self; } public SerializerBuilder WithEventEmitter<TEventEmitter>(WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter { WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory2(wrapped, inner))); return Self; } public SerializerBuilder WithoutEventEmitter<TEventEmitter>() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public SerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if ((object)eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override SerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if ((object)type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public SerializerBuilder WithoutTagMapping(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public SerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc) { loc.InsteadOf<TypeAssigningEventEmitter>(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> loc) { loc.OnBottom(); }); } public SerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public SerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public SerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w) { w.InsteadOf<YamlDotNet.Serialization.Converters.GuidConverter>(); }).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc) { loc.InsteadOf<TypeAssigningEventEmitter>(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { TObjectGraphVisitor objectGraphVisitor2 = objectGraphVisitor; if (objectGraphVisitor2 == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<IYamlTypeConverter> _) => objectGraphVisitor2)); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<Nothing> wrapped, IEnumerable<IYamlTypeConverter> _) => objectGraphVisitorFactory2(wrapped))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<Nothing> { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if ((object)objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>> w) { w.OnTop(); }); } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(args))); return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<IEmitter> wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(wrapped, args))); return this; } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if ((object)objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable<IYamlTypeConverter> typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } } public sealed class StreamFragment : IYamlConvertible { private readonly List<ParsingEvent> events = new List<ParsingEvent>(); public IList<ParsingEvent> Events => events; void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { events.Clear(); int num = 0; do { if (!parser.MoveNext()) { throw new InvalidOperationException("The parser has reached the end before deserialization completed."); } ParsingEvent current = parser.Current; events.Add(current); num += current.NestingIncrease; } while (num > 0); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { foreach (ParsingEvent @event in events) { emitter.Emit(@event); } } } public sealed class TagMappings { private readonly IDictionary<string, Type> mappings; public TagMappings() { mappings = new Dictionary<string, Type>(); } public TagMappings(IDictionary<string, Type> mappings) { this.mappings = new Dictionary<string, Type>(mappings); } public void Add(string tag, Type mapping) { mappings.Add(tag, mapping); } internal Type? GetMapping(string tag) { if (!mappings.TryGetValue(tag, out Type value)) { return null; } return value; } } public sealed class YamlAttributeOverrides { private struct AttributeKey { public readonly Type AttributeType; public readonly string PropertyName; public AttributeKey(Type attributeType, string propertyName) { AttributeType = attributeType; PropertyName = propertyName; } public override bool Equals(object? obj) { if (obj is AttributeKey attributeKey && AttributeType.Equals(attributeKey.AttributeType)) { return PropertyName.Equals(attributeKey.PropertyName); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(AttributeType.GetHashCode(), PropertyName.GetHashCode()); } } private sealed class AttributeMapping { public readonly Type RegisteredType; public readonly Attribute Attribute; public AttributeMapping(Type registeredType, Attribute attribute) { RegisteredType = registeredType; Attribute = attribute; } public override bool Equals(object? obj) { if (obj is AttributeMapping attributeMapping && RegisteredType.Equals(attributeMapping.RegisteredType)) { return Attribute.Equals(attributeMapping.Attribute); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(RegisteredType.GetHashCode(), Attribute.GetHashCode()); } public int Matches(Type matchType) { int num = 0; Type type = matchType; while ((object)type != null) { num++; if ((object)type == RegisteredType) { return num; } type = type.BaseType(); } if (matchType.GetInterfaces().Contains(RegisteredType)) { return num; } return 0; } } private readonly Dictionary<AttributeKey, List<AttributeMapping>> overrides = new Dictionary<AttributeKey, List<AttributeMapping>>(); public T? GetAttribute<T>(Type type, string member) where T : Attribute { if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out List<AttributeMapping> value)) { int num = 0; AttributeMapping attributeMapping = null; foreach (AttributeMapping item in value) { int num2 = item.Matches(type); if (num2 > num) { num = num2; attributeMapping = item; } } if (num > 0) { return (T)attributeMapping.Attribute; } } return null; } public void Add(Type type, string member, Attribute attribute) { AttributeMapping item = new AttributeMapping(type, attribute); AttributeKey key = new AttributeKey(attribute.GetType(), member); if (!overrides.TryGetValue(key, out List<AttributeMapping> value)) { value = new List<AttributeMapping>(); overrides.Add(key, value); } else if (value.Contains(item)) { throw new InvalidOperationException($"Attribute ({attribute}) already set for Type {type.FullName}, Member {member}"); } value.Add(item); } public YamlAttributeOverrides Clone() { YamlAttributeOverrides yamlAttributeOverrides = new YamlAttributeOverrides(); foreach (KeyValuePair<AttributeKey, List<AttributeMapping>> @override in overrides) { foreach (AttributeMapping item in @override.Value) { yamlAttributeOverrides.Add(item.RegisteredType, @override.Key.PropertyName, item.Attribute); } } return yamlAttributeOverrides; } public void Add<TClass>(Expression<Func<TClass, object>> propertyAccessor, Attribute attribute) { PropertyInfo propertyInfo = propertyAccessor.AsProperty(); Add(typeof(TClass), propertyInfo.Name, attribute); } } public sealed class YamlAttributeOverridesInspector : TypeInspectorSkeleton { public sealed class OverridePropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; private readonly YamlAttributeOverrides overrides; private readonly Type classType; public string Name => baseDescriptor.Name; public bool CanWrite => baseDescriptor.CanWrite; public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public int Order { get { return baseDescriptor.Order; } set { baseDescriptor.Order = value; } } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, YamlAttributeOverrides overrides, Type classType) { this.baseDescriptor = baseDescriptor; this.overrides = overrides; this.classType = classType; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T GetCustomAttribute<T>() where T : Attribute { return overrides.GetAttribute<T>(classType, Name) ?? baseDescriptor.GetCustomAttribute<T>(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } private readonly ITypeInspector innerTypeDescriptor; private readonly YamlAttributeOverrides overrides; public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, YamlAttributeOverrides overrides) { this.innerTypeDescriptor = innerTypeDescriptor; this.overrides = overrides; } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container) { Type type2 = type; IEnumerable<IPropertyDescriptor> enumerable = innerTypeDescriptor.GetProperties(type2, container); if (overrides != null) { enumerable = enumerable.Select((Func<IPropertyDescriptor, IPropertyDescriptor>)((IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type2))); } return enumerable; } } public sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor; } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container) { return from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute<YamlIgnoreAttribute>() == null select p).Select((Func<IPropertyDescriptor, IPropertyDescriptor>)delegate(IPropertyDescriptor p) { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p); YamlMemberAttribute customAttribute = p.GetCustomAttribute<YamlMemberAttribute>(); if (customAttribute != null) { if ((object)customAttribute.SerializeAs != null) { propertyDescriptor.TypeOverride = customAttribute.SerializeAs; } propertyDescriptor.Order = customAttribute.Order; propertyDescriptor.ScalarStyle = customAttribute.ScalarStyle; if (customAttribute.Alias != null) { propertyDescriptor.Name = customAttribute.Alias; } } return propertyDescriptor; }) orderby p.Order select p; } } internal static class YamlFormatter { public static readonly NumberFormatInfo NumberFormat = new NumberFormatInfo { CurrencyDecimalSeparator = ".", CurrencyGroupSeparator = "_", CurrencyGroupSizes = new int[1] { 3 }, CurrencySymbol = string.Empty, CurrencyDecimalDigits = 99, NumberDecimalSeparator = ".", NumberGroupSeparator = "_", NumberGroupSizes = new int[1] { 3 }, NumberDecimalDigits = 99, NaNSymbol = ".nan", PositiveInfinitySymbol = ".inf", NegativeInfinitySymbol = "-.inf" }; public static string FormatNumber(object number) { return Convert.ToString(number, NumberFormat); } public static string FormatNumber(double number) { return number.ToString("G17", NumberFormat); } public static string FormatNumber(float number) { return number.ToString("G17", NumberFormat); } public static string FormatBoolean(object boolean) { if (!boolean.Equals(true)) { return "false"; } return "true"; } public static string FormatDateTime(object dateTime) { return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture); } public static string FormatTimeSpan(object timeSpan) { return ((TimeSpan)timeSpan).ToString(); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class YamlIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class YamlMemberAttribute : Attribute { private DefaultValuesHandling? defaultValuesHandling; public string? Description { get; set; } public Type? SerializeAs { get; set; } public int Order { get; set; } public string? Alias { get; set; } public bool ApplyNamingConventions { get; set; } public ScalarStyle ScalarStyle { get; set; } public DefaultValuesHandling DefaultValuesHandling { get { return defaultValuesHandling.GetValueOrDefault(); } set { defaultValuesHandling = value; } } public bool IsDefaultValuesHandlingSpecified => defaultValuesHandling.HasValue; public YamlMemberAttribute() { ScalarStyle = ScalarStyle.Any; ApplyNamingConventions = true; } public YamlMemberAttribute(Type serializeAs) : this() { SerializeAs = serializeAs ?? throw new ArgumentNullException("serializeAs"); } } } namespace YamlDotNet.Serialization.ValueDeserializers { public sealed class AliasValueDeserializer : IValueDeserializer { private sealed class AliasState : Dictionary<AnchorName, ValuePromise>, IPostDeserializationCallback { public void OnDeserialization() { foreach (ValuePromise value in base.Values) { if (!value.HasValue) { YamlDotNet.Core.Events.AnchorAlias alias = value.Alias; throw new AnchorNotFoundException(alias.Start, alias.End, $"Anchor '{alias.Value}' not found"); } } } } private sealed class ValuePromise : IValuePromise { private object? value; public readonly YamlDotNet.Core.Events.AnchorAlias? Alias; public bool HasValue { get; private set; } public object? Value { get { if (!HasValue) { throw new InvalidOperationException("Value not set"); } return value; } set { if (HasValue) { throw new InvalidOperationException("Value already set"); } HasValue = true; this.value = value; this.ValueAvailable?.Invoke(value); } } public event Action<object?>? ValueAvailable; public ValuePromise(YamlDotNet.Core.Events.AnchorAlias alias) { Alias = alias; } public ValuePromise(object? value) { HasValue = true; this.value = value; } } private readonly IValueDeserializer innerDeserializer; public AliasValueDeserializer(IValueDeserializer innerDeserializer) { this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer"); } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { if (parser.TryConsume<YamlDotNet.Core.Events.AnchorAlias>(out var @event)) { if (!state.Get<AliasState>().TryGetValue(@event.Value, out ValuePromise value)) { throw new AnchorNotFoundException(@event.Start, @event.End, $"Alias ${@event.Value} cannot precede anchor declaration"); } if (!value.HasValue) { return value; } return value.Value; } AnchorName anchorName = AnchorName.Empty; if (parser.Accept<NodeEvent>(out var event2) && !event2.Anchor.IsEmpty) { anchorName = event2.Anchor; AliasState aliasState = state.Get<AliasState>(); if (!aliasState.ContainsKey(anchorName)) { aliasState[anchorName] = new ValuePromise(new YamlDotNet.Core.Events.AnchorAlias(anchorName)); } } object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (!anchorName.IsEmpty) { AliasState aliasState2 = state.Get<AliasState>(); if (!aliasState2.TryGetValue(anchorName, out ValuePromise value2)) { aliasState2.Add(anchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState2[anchorName] = new ValuePromise(obj); } } return obj; } } public sealed class NodeValueDeserializer : IValueDeserializer { private readonly IList<INodeDeserializer> deserializers; private readonly IList<INodeTypeResolver> typeResolvers; public NodeValueDeserializer(IList<INodeDeserializer> deserializers, IList<INodeTypeResolver> typeResolvers) { this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers"); this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers"); } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { IValueDeserializer nestedObjectDeserializer2 = nestedObjectDeserializer; SerializerState state2 = state; parser.Accept<NodeEvent>(out var @event); Type typeFromEvent = GetTypeFromEvent(@event, expectedType); try { foreach (INodeDeserializer deserializer in deserializers) { if (deserializer.Deserialize(parser, typeFromEvent, (IParser r, Type t) => nestedObjectDeserializer2.DeserializeValue(r, t, state2, nestedObjectDeserializer2), out object value)) { return YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(value, expectedType); } } } catch (YamlException) { throw; } catch (Exception innerException) { throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "Exception during deserialization", innerException); } throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "No node deserializer was able to deserialize the node into type " + expectedType.AssemblyQualifiedName); } private Type GetTypeFromEvent(NodeEvent? nodeEvent, Type currentType) { using (IEnumerator<INodeTypeResolver> enumerator = typeResolvers.GetEnumerator()) { while (enumerator.MoveNext() && !enumerator.Current.Resolve(nodeEvent, ref currentType)) { } } return currentType; } } } namespace YamlDotNet.Serialization.Utilities { public interface IPostDeserializationCallback { void OnDeserialization(); } internal sealed class ObjectAnchorCollection { private readonly IDictionary<string, object> objectsByAnchor = new Dictionary<string, object>(); private readonly IDictionary<object, string> anchorsByObject = new Dictionary<object, string>(); public object this[string anchor] { get { if (objectsByAnchor.TryGetValue(anchor, out object value)) { return value; } throw new AnchorNotFoundException("The anchor '" + anchor + "' does not exists"); } } public void Add(string anchor, object @object) { objectsByAnchor.Add(anchor, @object); if (@object != null) { anchorsByObject.Add(@object, anchor); } } public bool TryGetAnchor(object @object, [MaybeNullWhen(false)] out string? anchor) { return anchorsByObject.TryGetValue(@object, out anchor); } } internal static class ReflectionUtility { public static Type? GetImplementedGenericInterface(Type type, Type genericInterfaceType) { foreach (Type implementedInterface in GetImplementedInterfaces(type)) { if (implementedInterface.IsGenericType() && (object)implementedInterface.GetGenericTypeDefinition() == genericInterfaceType) { return implementedInterface; } } return null; } public static IEnumerable<Type> GetImplementedInterfaces(Type type) { if (type.IsInterface()) { yield return type; } Type[] interfaces = type.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { yield return interfaces[i]; } } } public sealed class SerializerState : IDisposable { private readonly IDictionary<Type, object> items = new Dictionary<Type, object>(); public T Get<T>() where T : class, new() { if (!items.TryGetValue(typeof(T), out object value)) { value = new T(); items.Add(typeof(T), value); } return (T)value; } public void OnDeserialization() { foreach (IPostDeserializationCallback item in items.Values.OfType<IPostDeserializationCallback>()) { item.OnDeserialization(); } } public void Dispose() { foreach (IDisposable item in items.Values.OfType<IDisposable>()) { item.Dispose(); } } } internal static class StringExtensions { private static string ToCamelOrPascalCase(string str, Func<char, char> firstLetterTransform) { string text = Regex.Replace(str, "([_\\-])(?<char>[a-z])", (Match match) => match.Groups["char"].Value.ToUpperInvariant(), RegexOptions.IgnoreCase); return firstLetterTransform(text[0]) + text.Substring(1); } public static string ToCamelCase(this string str) { return ToCamelOrPascalCase(str, char.ToLowerInvariant); } public static string ToPascalCase(this string str) { return ToCamelOrPascalCase(str, char.ToUpperInvariant); } public static string FromCamelCase(this string str, string separator) { string separator2 = separator; str = char.ToLower(str[0]) + str.Substring(1); str = Regex.Replace(str.ToCamelCase(), "(?<char>[A-Z])", (Match match) => separator2 + match.Groups["char"].Value.ToLowerInvariant()); return str; } } public static class TypeConverter { public static T ChangeType<T>(object? value) { return (T)ChangeType(value, typeof(T)); } public static T ChangeType<T>(object? value, IFormatProvider provider) { return (T)ChangeType(value, typeof(T), provider); } public static T ChangeType<T>(object? value, CultureInfo culture) { return (T)ChangeType(value, typeof(T), culture); } public static object? ChangeType(object? value, Type destinationType) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture); } public static object? ChangeType(object? value, Type destinationType, IFormatProvider provider) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider)); } public static object? ChangeType(object? value, Type destinationType, CultureInfo culture) { if (value == null || value.IsDbNull()) { if (!destinationType.IsValueType()) { return null; } return Activator.CreateInstance(destinationType); } Type type = value.GetType(); if ((object)destinationType == type || destinationType.IsAssignableFrom(type)) { return value; } if (destinationType.IsGenericType() && (object)destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type destinationType2 = destinationType.GetGenericArguments()[0]; object obj = ChangeType(value, destinationType2, culture); return Activator.CreateInstance(destinationType, obj); } if (destinationType.IsEnum()) { if (!(value is string value2)) { return value; } return Enum.Parse(destinationType, value2, ignoreCase: true); } if ((object)destinationType == typeof(bool)) { if ("0".Equals(value)) { return false; } if ("1".Equals(value)) { return true; } } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.CanConvertTo(destinationType)) { return converter.ConvertTo(null, culture, value, destinationType); } System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType); if (converter2 != null && converter2.CanConvertFrom(type)) { return converter2.ConvertFrom(null, culture, value); } Type[] array = new Type[2] { type, destinationType }; for (int i = 0; i < array.Length; i++) { foreach (MethodInfo publicStaticMethod2 in array[i].GetPublicStaticMethods()) { if (!publicStaticMethod2.IsSpecialName || (!(publicStaticMethod2.Name == "op_Implicit") && !(publicStaticMethod2.Name == "op_Explicit")) || !destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType)) { continue; } ParameterInfo[] parameters = publicStaticMethod2.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type)) { try { return publicStaticMethod2.Invoke(null, new object[1] { value }); } catch (TargetInvocationException ex) { throw ex.Unwrap(); } } } } if ((object)type == typeof(string)) { try { MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider)); if ((object)publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[2] { value, culture }); } publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string)); if ((object)publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[1] { value }); } } catch (TargetInvocationException ex2) { throw ex2.Unwrap(); } } if ((object)destinationType == typeof(TimeSpan)) { return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)); } return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); } } } namespace YamlDotNet.Serialization.TypeResolvers { public sealed class DynamicTypeResolver : ITypeResolver { public Type Resolve(Type staticType, object? actualValue) { if (actualValue == null) { return staticType; } return actualValue.GetType(); } } public sealed class StaticTypeResolver : ITypeResolver { public Type Resolve(Type staticType, object? actualValue) { return staticType; } } } namespace YamlDotNet.Serialization.TypeInspectors { public sealed class CachedTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly ConcurrentDictionary<Type, List<IPropertyDescriptor>> cache = new ConcurrentDictionary<Type, List<IPropertyDescriptor>>(); public CachedTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container) { object container2 = container; return cache.GetOrAdd(type, (Type t) => innerTypeDescriptor.GetProperties(t, container2).ToList()); } } public sealed class CompositeTypeInspector : TypeInspectorSkeleton { private readonly IEnumerable<ITypeInspector> typeInspectors; public CompositeTypeInspector(params ITypeInspector[] typeInspectors) : this((IEnumerable<ITypeInspector>)typeInspectors) { } public CompositeTypeInspector(IEnumerable<ITypeInspector> typeInspectors) { this.typeInspectors = typeInspectors?.ToList() ?? throw new ArgumentNullException("typeInspectors"); } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container) { Type type2 = type; object container2 = container; return typeInspectors.SelectMany((ITypeInspector i) => i.GetProperties(type2, container2)); } } public sealed class NamingConventionTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly INamingConvention namingConvention; public NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, INamingConvention namingConvention) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container) { return innerTypeDescriptor.GetProperties(type, container).Select(delegate(IPropertyDescriptor p) { YamlMemberAttribute customAttribute = p.GetCustomAttribute<YamlMemberAttribute>(); return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; }); } } public sealed class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } public sealed class ReadableFieldsTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly ITypeResolver typeResolver; public string Name => fieldInfo.Name; public Type Type => fieldInfo.FieldType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => !fieldInfo.IsInitOnly; public ScalarStyle ScalarStyle { get; set; } public ReflectionFieldDescriptor(FieldInfo fieldInfo, ITypeResolver typeResolver) { this.fieldInfo = fieldInfo; this.typeResolver = typeResolver; ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { fieldInfo.SetValue(target, value); } public T GetCustomAttribute<T>() where T : Attribute { return (T)fieldInfo.GetCustomAttributes(typeof(T), inherit: true).FirstOrDefault(); } public IObjectDescriptor Read(object target) { object value = fieldInfo.GetValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, value); return new ObjectDescriptor(value, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; public ReadableFieldsTypeInspector(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container) { return type.GetPublicFields().Select((Func<FieldInfo, IPropertyDescriptor>)((FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } public sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { propertyInfo.SetValue(target, value, null); } public T GetCustomAttribute<T>() where T : Attribute { return (T)propertyInfo.GetAllCustomAttributes<T>().FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public ReadablePropertiesTypeInspector(ITypeRes