/* Copyright (c) 2017 Ahmed Kh. Zamil Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using Esiur.Core; using Esiur.Resource; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Collections; using Esiur.Protocol; namespace Esiur.Data; #nullable enable public static class Codec { //delegate AsyncReply AsyncParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence); delegate object AsyncParser(ParsedTdu tdu, EpConnection connection, uint[] requestSequence); delegate object SyncParser(ParsedTdu tdu, Warehouse warehouse); static AsyncParser[][] FixedAsyncParsers = new AsyncParser[][] { new AsyncParser[]{ DataDeserializer.NullParserAsync, DataDeserializer.BooleanFalseParserAsync, DataDeserializer.BooleanTrueParserAsync, DataDeserializer.NotModifiedParserAsync, DataDeserializer.InfinityParserAsync, }, new AsyncParser[]{ DataDeserializer.UInt8ParserAsync, DataDeserializer.Int8ParserAsync, DataDeserializer.Char8ParserAsync, DataDeserializer.LocalResourceParser8Async, DataDeserializer.ResourceParser8Async, }, new AsyncParser[]{ DataDeserializer.UInt16ParserAsync, DataDeserializer.Int16ParserAsync, DataDeserializer.Char16ParserAsync, DataDeserializer.LocalResourceParser16Async, DataDeserializer.ResourceParser16Async, }, new AsyncParser[]{ DataDeserializer.UInt32ParserAsync, DataDeserializer.Int32ParserAsync, DataDeserializer.Float32ParserAsync, DataDeserializer.LocalResourceParser32Async, DataDeserializer.ResourceParser32Async, }, new AsyncParser[]{ DataDeserializer.UInt64ParserAsync, DataDeserializer.Int64ParserAsync, DataDeserializer.Float64ParserAsync, DataDeserializer.DateTimeParserAsync, }, new AsyncParser[] { DataDeserializer.UInt128ParserAsync, // uint 128 DataDeserializer.Int128ParserAsync, // int 128 DataDeserializer.Decimal128ParserAsync, DataDeserializer.UUIDParserAsync } }; static AsyncParser[] DynamicAsyncParsers = new AsyncParser[] { DataDeserializer.RawDataParserAsync, DataDeserializer.StringParserAsync, DataDeserializer.ListParserAsync, DataDeserializer.ResourceListParserAsync, DataDeserializer.RecordListParserAsync, DataDeserializer.ResourceLinkParserAsync, }; static AsyncParser[] TypedAsyncParsers = new AsyncParser[] { DataDeserializer.TypedParserAsync, }; static AsyncParser[] ExtendedAsyncParsers = new AsyncParser[] { }; static SyncParser[][] FixedParsers = new SyncParser[][] { new SyncParser[]{ DataDeserializer.NullParser, DataDeserializer.BooleanFalseParser, DataDeserializer.BooleanTrueParser, DataDeserializer.NotModifiedParser, DataDeserializer.InfinityParser, }, new SyncParser[]{ DataDeserializer.UInt8Parser, DataDeserializer.Int8Parser, DataDeserializer.Char8Parser, DataDeserializer.LocalResourceParser8, DataDeserializer.ResourceParser8, }, new SyncParser[]{ DataDeserializer.UInt16Parser, DataDeserializer.Int16Parser, DataDeserializer.Char16Parser, DataDeserializer.LocalResourceParser16, DataDeserializer.ResourceParser16, }, new SyncParser[]{ DataDeserializer.UInt32Parser, DataDeserializer.Int32Parser, DataDeserializer.Float32Parser, DataDeserializer.LocalResourceParser32, DataDeserializer.ResourceParser32, }, new SyncParser[]{ DataDeserializer.UInt64Parser, DataDeserializer.Int64Parser, DataDeserializer.Float64Parser, DataDeserializer.DateTimeParser, }, new SyncParser[] { DataDeserializer.UInt128Parser, // uint 128 DataDeserializer.Int128Parser, // int 128 DataDeserializer.Decimal128Parser, DataDeserializer.UUIDParser } }; static SyncParser[] DynamicParsers = new SyncParser[] { DataDeserializer.RawDataParser, DataDeserializer.StringParser, DataDeserializer.ListParser, DataDeserializer.ResourceListParser, DataDeserializer.RecordListParser, DataDeserializer.ResourceLinkParser, // @TODO: Map and MapList parsers to be added }; static SyncParser[] TypedParsers = new SyncParser[] { DataDeserializer.TypedParser, //DataDeserializer.RecordParser, //DataDeserializer.TypedListParser, //DataDeserializer.TypedMapParser, //DataDeserializer.TupleParser, //DataDeserializer.EnumParser, //DataDeserializer.ConstantParser, }; static SyncParser[] ExtendedParsers = new SyncParser[] { }; /// /// Parse a value /// /// Bytes array /// Zero-indexed offset. /// Output the number of bytes parsed /// EpConnection is required in case a structure in the array holds items at the other end. /// DataType, in case the data is not prepended with DataType /// Value public static AsyncReply> ParseAsync(byte[] data, uint offset, EpConnection connection, uint[] requestSequence) { var rt = new AsyncReply>(); ParsedTdu.ParseAsync(data, offset, (uint)data.Length, connection).Then(tdu => { if (tdu.Class == TduClass.Invalid) throw new NullReferenceException("DataType can't be parsed."); object result; if (tdu.Class == TduClass.Fixed) { result = FixedAsyncParsers[tdu.Exponent][tdu.Index](tdu, connection, requestSequence); } else if (tdu.Class == TduClass.Dynamic) { result = DynamicAsyncParsers[tdu.Index](tdu, connection, requestSequence); } else if (tdu.Class == TduClass.Typed) { result = TypedAsyncParsers[tdu.Index](tdu, connection, requestSequence); } else // if (tt.Class == TDUClass.Extension) { result = ExtendedAsyncParsers[tdu.Index](tdu, connection, requestSequence); } if (result is AsyncReply asyncReply) { asyncReply.Then(value => { rt.Trigger(new ParseResult(value, (uint)tdu.TotalLength)); }); } else { rt.Trigger(new ParseResult(result, (uint)tdu.TotalLength)); } }); return rt; } public static object ParseAsync(ParsedTdu tdu, EpConnection connection, uint[] requestSequence) { if (tdu.Class == TduClass.Invalid) throw new NullReferenceException("DataType can't be parsed."); if (tdu.Class == TduClass.Fixed) { return FixedAsyncParsers[tdu.Exponent][tdu.Index](tdu, connection, requestSequence); } else if (tdu.Class == TduClass.Dynamic) { return DynamicAsyncParsers[tdu.Index](tdu, connection, requestSequence); } else if (tdu.Class == TduClass.Typed) { return TypedAsyncParsers[tdu.Index](tdu, connection, requestSequence); } else // if (tt.Class == TDUClass.Extension) { return ExtendedAsyncParsers[tdu.Index](tdu, connection, requestSequence); } } public static object Parse(PlainTdu plainTdu, EpConnection connection, uint[] requestSequence) { var parsedTdu = ParsedTdu.Parse(plainTdu.Data, plainTdu.TduOffset, (uint)plainTdu.Ends, connection); if (parsedTdu is ParsedTdu tdu) { if (tdu.Class == TduClass.Invalid) throw new NullReferenceException("TDU can't be parsed."); if (tdu.Class == TduClass.Fixed) { return FixedAsyncParsers[tdu.Exponent][tdu.Index](tdu, connection, requestSequence); } else if (tdu.Class == TduClass.Dynamic) { return DynamicAsyncParsers[tdu.Index](tdu, connection, requestSequence); } else if (tdu.Class == TduClass.Typed) { return TypedAsyncParsers[tdu.Index](tdu, connection, requestSequence); } else // if (tt.Class == TDUClass.Extension) { return ExtendedAsyncParsers[tdu.Index](tdu, connection, requestSequence); } } else if (parsedTdu is AsyncReply asyncReply) { var rt = new AsyncReply(); asyncReply.Then(tdu => { if (tdu.Class == TduClass.Invalid) throw new NullReferenceException("TDU can't be parsed."); object result; if (tdu.Class == TduClass.Fixed) { result = FixedAsyncParsers[tdu.Exponent][tdu.Index](tdu, connection, requestSequence); } else if (tdu.Class == TduClass.Dynamic) { result = DynamicAsyncParsers[tdu.Index](tdu, connection, requestSequence); } else if (tdu.Class == TduClass.Typed) { result = TypedAsyncParsers[tdu.Index](tdu, connection, requestSequence); } else // if (tt.Class == TDUClass.Extension) { result = ExtendedAsyncParsers[tdu.Index](tdu, connection, requestSequence); } if (result is AsyncReply resultReply) { resultReply.Then(rt.Trigger) .Error(rt.TriggerError); } else { rt.Trigger(result); } }); return rt; } throw new NotImplementedException(); } public static object ParseSync(PlainTdu plainTdu, Warehouse warehouse) { var tdu = ParsedTdu.ParseSync(plainTdu.Data, plainTdu.TduOffset, plainTdu.Ends, warehouse); if (tdu.Class == TduClass.Invalid) { throw new Exception("Invalid TDU."); } else if (tdu.Class == TduClass.Fixed) { return FixedParsers[tdu.Exponent][tdu.Index](tdu, warehouse); } else if (tdu.Class == TduClass.Dynamic) { return DynamicParsers[tdu.Index](tdu, warehouse); } else if (tdu.Class == TduClass.Typed) { return TypedParsers[tdu.Index](tdu, warehouse); } else // Extension { return ExtendedParsers[tdu.Index](tdu, warehouse); } } public static object ParseSync(ParsedTdu tdu, Warehouse warehouse) { if (tdu.Class == TduClass.Fixed) { return FixedParsers[tdu.Exponent][tdu.Index](tdu, warehouse); } else if (tdu.Class == TduClass.Dynamic) { return DynamicParsers[tdu.Index](tdu, warehouse); } else if (tdu.Class == TduClass.Typed) { return TypedParsers[tdu.Index](tdu, warehouse); } else // Extension { return ExtendedParsers[tdu.Index](tdu, warehouse); } } /// /// Synchronously parses a single value from its IIP wire representation. /// /// Buffer containing the encoded value. /// Zero-based offset of the value within . /// Warehouse used to resolve typed structures (records, enums, ...). /// A tuple of (number of bytes consumed, decoded value). public static (uint, object) ParseSync(byte[] data, uint offset, Warehouse warehouse) { var tdu = ParsedTdu.ParseSync(data, offset, (uint)data.Length, warehouse); if (tdu.Class == TduClass.Invalid) throw new NullReferenceException("DataType can't be parsed."); if (tdu.Class == TduClass.Fixed) { return ((uint)tdu.TotalLength, FixedParsers[tdu.Exponent][tdu.Index](tdu, warehouse)); } else if (tdu.Class == TduClass.Dynamic) { return ((uint)tdu.TotalLength, DynamicParsers[tdu.Index](tdu, warehouse)); } else if (tdu.Class == TduClass.Typed) { return ((uint)tdu.TotalLength, TypedParsers[tdu.Index](tdu, warehouse)); } else { return ((uint)tdu.TotalLength, ExtendedParsers[tdu.Index](tdu, warehouse)); } } /// /// Check if a resource is local to a given connection. /// /// Resource to check. /// EpConnection to check if the resource is local to it. /// True, if the resource owner is the given connection, otherwise False. public static bool IsLocalResource(IResource resource, EpConnection connection) { if (resource == null) throw new NullReferenceException("Resource is null."); if (resource is EpResource) if (((EpResource)(resource)).ResourceConnection == connection) return true; return false; } public delegate Tdu Composer(object value, Warehouse warehouse, EpConnection connection); public static Dictionary Composers = new Dictionary() { // Fixed [typeof(bool)] = DataSerializer.BoolComposer, [typeof(bool?)] = DataSerializer.BoolComposer, [typeof(NotModified)] = DataSerializer.NotModifiedComposer, [typeof(byte)] = DataSerializer.UInt8Composer, [typeof(byte?)] = DataSerializer.UInt8Composer, [typeof(sbyte)] = DataSerializer.Int8Composer, [typeof(sbyte?)] = DataSerializer.Int8Composer, [typeof(char)] = DataSerializer.Char16Composer, [typeof(char?)] = DataSerializer.Char16Composer, [typeof(short)] = DataSerializer.Int16Composer, [typeof(short?)] = DataSerializer.Int16Composer, [typeof(ushort)] = DataSerializer.UInt16Composer, [typeof(ushort?)] = DataSerializer.UInt16Composer, [typeof(int)] = DataSerializer.Int32Composer, [typeof(int?)] = DataSerializer.Int32Composer, [typeof(uint)] = DataSerializer.UInt32Composer, [typeof(uint?)] = DataSerializer.UInt32Composer, [typeof(float)] = DataSerializer.Float32Composer, [typeof(float?)] = DataSerializer.Float32Composer, [typeof(long)] = DataSerializer.Int64Composer, [typeof(long?)] = DataSerializer.Int64Composer, [typeof(ulong)] = DataSerializer.UInt64Composer, [typeof(ulong?)] = DataSerializer.UInt64Composer, [typeof(double)] = DataSerializer.Float64Composer, [typeof(double?)] = DataSerializer.Float64Composer, [typeof(DateTime)] = DataSerializer.DateTimeComposer, [typeof(DateTime?)] = DataSerializer.DateTimeComposer, [typeof(decimal)] = DataSerializer.Decimal128Composer, [typeof(decimal?)] = DataSerializer.Decimal128Composer, [typeof(byte[])] = DataSerializer.RawDataComposerFromArray, //[typeof(byte?[])] = DataSerializer.RawDataComposerFromArray, [typeof(List)] = DataSerializer.RawDataComposerFromList, //[typeof(List)] = DataSerializer.RawDataComposerFromList, [typeof(string)] = DataSerializer.StringComposer, [typeof(ResourceLink)] = DataSerializer.ResourceLinkComposer, [typeof(Uuid)] = DataSerializer.UUIDComposer, // Special [typeof(object[])] = DataSerializer.ListComposer, [typeof(List)] = DataSerializer.ListComposer, [typeof(VarList)] = DataSerializer.ListComposer, [typeof(IResource[])] = DataSerializer.ResourceListComposer, [typeof(IResource?[])] = DataSerializer.ResourceListComposer, [typeof(List)] = DataSerializer.ResourceListComposer, [typeof(List)] = DataSerializer.ResourceListComposer, [typeof(VarList)] = DataSerializer.ResourceListComposer, [typeof(VarList)] = DataSerializer.ResourceListComposer, [typeof(IRecord[])] = DataSerializer.RecordListComposer, [typeof(IRecord?[])] = DataSerializer.RecordListComposer, [typeof(List)] = DataSerializer.RecordListComposer, [typeof(List)] = DataSerializer.RecordListComposer, [typeof(VarList)] = DataSerializer.RecordListComposer, [typeof(VarList)] = DataSerializer.RecordListComposer, [typeof(Map)] = DataSerializer.MapComposer, [typeof(Map)] = DataSerializer.MapComposer, [typeof(Map)] = DataSerializer.MapComposer, [typeof(Map)] = DataSerializer.MapComposer, [typeof(PropertyValue[])] = DataSerializer.PropertyValueArrayComposer // Typed // [typeof(bool[])] = (value, con) => DataSerializer.TypedListComposer((IEnumerable)value, typeof(bool), con), // [typeof(bool?[])] = (value, con) => (TransmissionDataUnitIdentifier.TypedList, new byte[] { (byte)value }), // [typeof(List)] = (value, con) => (TransmissionDataUnitIdentifier.TypedList, new byte[] { (byte)value }), // [typeof(List)] = (value, con) => (TransmissionDataUnitIdentifier.TypedList, new byte[] { (byte)value }), // [typeof(byte?[])] = (value, con) => (TransmissionDataUnitIdentifier.TypedList, new byte[] { (byte)value }), // [typeof(List)] = (value, con) => (TransmissionDataUnitIdentifier.TypedList, new byte[] { (byte)value }), }; internal static Tdu ComposeInternal(object valueOrSource, Warehouse warehouse, EpConnection connection) { if (valueOrSource == null) return new Tdu(TduIdentifier.Null, null, 0, null, null); var type = valueOrSource.GetType(); if (type.IsGenericType) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(PropertyContext<>)) { valueOrSource = ((IPropertyContext)valueOrSource).GetValue(connection); } else if (genericType == typeof(Func<>)) { var args = genericType.GetGenericArguments(); if (args.Length == 2 && args[0] == typeof(EpConnection)) { //Func a; //a.Invoke() } } } if (valueOrSource is IUserType) valueOrSource = ((IUserType)valueOrSource).Get(); if (valueOrSource == null) return new Tdu(TduIdentifier.Null, null, 0, null, null); type = valueOrSource.GetType(); if (Composers.ContainsKey(type)) { return Composers[type](valueOrSource, warehouse, connection); } else { if (Codec.ImplementsInterface(type, typeof(IResource))) { return DataSerializer.ResourceComposer(valueOrSource, warehouse, connection); } else if (Codec.ImplementsInterface(type, typeof(IRecord))) { return DataSerializer.RecordComposer(valueOrSource, warehouse, connection); } else if (type.IsGenericType) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(List<>) || genericType == typeof(VarList<>) || genericType == typeof(IList<>)) { var args = type.GetGenericArguments(); //if (Composers.ContainsKey(args[0])) //{ return DataSerializer.TypedListComposer((IEnumerable)valueOrSource, args[0], warehouse, connection); //} } else if (genericType == typeof(Map<,>)) { var args = type.GetGenericArguments(); return DataSerializer.TypedMapComposer(valueOrSource, args[0], args[1], warehouse, connection); } else if (genericType == typeof(Dictionary<,>)) { var args = type.GetGenericArguments(); return DataSerializer.TypedDictionaryComposer(valueOrSource, args[0], args[1], warehouse, connection); } else if (genericType == typeof(ValueTuple<,>) || genericType == typeof(ValueTuple<,,>) || genericType == typeof(ValueTuple<,,,>) || genericType == typeof(ValueTuple<,,,,>) || genericType == typeof(ValueTuple<,,,,,>) || genericType == typeof(ValueTuple<,,,,,,>) ) { return DataSerializer.TupleComposer(valueOrSource, warehouse, connection); } } else if (type.IsArray) { var elementType = type.GetElementType(); //if (Composers.ContainsKey(elementType)) //{ return DataSerializer.TypedListComposer((IEnumerable)valueOrSource, elementType, warehouse, connection); //} } else if (type.IsEnum) { return DataSerializer.EnumComposer(valueOrSource, warehouse, connection); } } return new Tdu(TduIdentifier.Null, null, 0, null, null); } /// /// Compose a variable /// /// Value to compose. /// EpConnection is required to check locality. /// If True, prepend the DataType at the beginning of the output. /// Array of bytes in the network byte order. /// /// Encodes a value to its self-describing IIP wire representation (a type-prefixed TDU). /// /// The value to encode (may be null, which encodes as the Null TDU). /// Warehouse used to resolve type definitions for typed structures. /// Connection context, required when the value references remote resources; may be null for plain data. /// The encoded bytes, including the leading type identifier. public static byte[] Compose(object valueOrSource, Warehouse warehouse, EpConnection connection) { var tdu = ComposeInternal(valueOrSource, warehouse, connection); return tdu.Composed; } public static bool IsAnonymous(Type type) { // Detect anonymous types var info = type.GetTypeInfo(); var hasCompilerGeneratedAttribute = info.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Count() > 0; var nameContainsAnonymousType = type.FullName.Contains("AnonymousType"); return hasCompilerGeneratedAttribute && nameContainsAnonymousType; } public static Type? GetGenericType(Type type, Type ifaceType, int argument = 0) { if (ifaceType.IsAssignableFrom(type)) { var col = type.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == ifaceType) .FirstOrDefault()? .GetGenericArguments() .FirstOrDefault() ?? null; return col; } else return null; } /// /// Check if a type implements an interface /// /// Sub-class type. /// Super-interface type. /// True, if implements . public static bool ImplementsInterface(Type type, Type iface) { while (type != null) { if (type == typeof(object)) return false; if (type == iface) return true; #if NETSTANDARD if (type.GetTypeInfo().GetInterfaces().Contains(iface)) return true; type = type.GetTypeInfo().BaseType; #else if (type.GetInterfaces().Contains(iface)) return true; type = type.BaseType; #endif } return false; } public static bool InheritsClass(Type type, Type parent) => type.IsSubclassOf(parent); /// /// Check if a type inherits another type. /// /// Child type. /// Parent type. /// True, if inherits . private static bool HasParentType(Type childType, Type parentType) { while (childType != null) { if (childType == parentType) return true; #if NETSTANDARD childType = childType.GetTypeInfo().BaseType; #else childType = childType.BaseType; #endif } return false; } }