public int Search(ArrayReader reader, int target) { int left = 0; int right = 1; while (reader.Get(right) < target) { right *= 2; } while (left < right - 1) { int mid = left + (right - left) / 2; if (target == reader.Get(mid)) { return(mid); } if (target < reader.Get(mid)) { right = mid - 1; } else { left = mid + 1; } } if (target == reader.Get(left)) { return(left); } if (target == reader.Get(right)) { return(right); } return(-1); }
/// <summary> /// Load field vào store /// </summary> private void LoadField2Store() { if (columnList == null) { columnList = GridController.GetInstance().GetColumnInfo(this.ID, TableName, 1); } ArrayReader arrReader = new ArrayReader(); arrReader.IDProperty = this.PrimaryKey;//Util.GetInstance().GetPrimaryKeyOfTable(this.TableName); if (columnList.FirstOrDefault() != null) { foreach (GridPanelColumnInfo columnInfo in columnList) { RecordField field = new RecordField(); field.Name = columnInfo.ColumnName; arrReader.Fields.Add(field); } } else { DataTable datatable = DataController.DataHandler.GetInstance().ExecuteDataTable("select top 1 * from " + TableName); foreach (DataColumn item in datatable.Columns) { RecordField field = new RecordField(); field.Name = item.ColumnName; arrReader.Fields.Add(field); } } Store1.Reader.Add(arrReader); }
private void CNetwork_OnReceived(object sender, NetReceivedEventArgs <byte[]> e) { reader = new ArrayReader(e.Data, e.Data.Length); FROM_SERVER header = (FROM_SERVER)reader.ReadShort(); switch (header) { case FROM_SERVER.LOGIN_STATUS: break; case FROM_SERVER.CLIENT_HELLO: var version = reader.ReadShort(); var patch = reader.ReadMapleString(); if (version != (short)GameConstants.MAJOR_VERSION && patch != GameConstants.MINOR_VERSION) { Disconnect(NetStoppedReason.Exception); Environment.Exit(0); } break; default: Console.WriteLine("[Unhandled] Packet received: {0}", ByteArrayToString(e.Data)); break; } }
public CommandExecutionContext GetFromArgs() { try { var argumentsReader = new ArrayReader <string>(_args); var commandConfig = ParseCommands(_rootCommandConfig, argumentsReader); var defaultCommandConfig = FindDefaultCommandConfig(commandConfig, argumentsReader); var commandArguments = ReadCommandArguments(defaultCommandConfig, argumentsReader); return(GetCommandExecutionContext(commandConfig, defaultCommandConfig, commandArguments)); } catch (ArgumentValueException e) { if (!_cliConfig.IsExceptionHandlingEnabled) { throw; } return(PrepareHelpCommandExecutionContext(_rootCommandConfig, e.Message)); } catch (TooManyParametersException e) { if (!_cliConfig.IsExceptionHandlingEnabled) { throw; } return(PrepareHelpCommandExecutionContext(_rootCommandConfig, e.Message)); } }
private CommandArgs ReadCommandArguments(CommandConfig commandConfig, ArrayReader <string> argumentsReader) { var options = commandConfig.Options; var optionValues = new Dictionary <string, ArrayAggregator>(); var parameterSeries = commandConfig.ParameterSeries; var parameters = new ArrayReader <Parameter>(commandConfig.Parameters.ToArray()); var commandArgs = InitDefaultCommandArgs(commandConfig); while (argumentsReader.HasData()) { var arg = argumentsReader.Read(); if (!ReadOpt(options, commandArgs, optionValues, argumentsReader, arg) && !ReadParam(commandArgs, parameters, arg) && !ReadParamSeries(parameterSeries, commandArgs, arg)) { throw new TooManyParametersException(arg); } } foreach (var(optionName, optionValue) in optionValues) { commandArgs.AddOptionValueProvider( optionName, new ConstValueProvider( optionValue.GetArray( options.Single(o => o.Name == optionName).ValueType) ) ); } return(commandArgs); }
public int Search(ArrayReader reader, int target) { int left = 0, right = 1; while (reader.Get(right) < target) { left = right; right <<= 1; } while (left <= right) { var mid = left + (right - left) / 2; var value = reader.Get(mid); if (value == target) { return(mid); } else if (value > target) { right = mid - 1; } else { left = mid + 1; } } return(-1); }
private static void Execute(AccelerationDevice device, CancellationToken cancellationToken) { using (var kernel = GetKernel(device)) { using (var cb = new HardwareConstantBuffer <int>(device)) using (var bIn = new HardwareInputBuffer(device, typeof(int), 10)) using (var bOut = new HardwareOutputBuffer(device, typeof(int), 10)) { kernel.ThreadGroupCount = new Vector3 <uint>(10, 1, 1); kernel.Constants[0] = cb; kernel.Resources[0] = bIn; kernel.Outputs[0] = bOut; cb.Structure = 2; var inData = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var outData = new int[inData.Length]; var bInArrayView = new ArrayWriter <int>(bIn); var bOutArrayView = new ArrayReader <int>(bOut); bInArrayView.Write(inData); kernel.Execute(); bOutArrayView.Read(outData); using (WithColor(ConsoleColor.White, ConsoleColor.DarkBlue)) { Console.WriteLine($"[ {string.Join(", ", inData)} ] => [ {string.Join(", ", outData)} ]"); } } } }
public void TestWithPointers() { var path = Path.Combine("..", "..", "TestData", "MaxMind-DB", "test-data", "maps-with-pointers.raw"); using (var database = new ArrayReader(path)) { var decoder = new Decoder(database, 0); var node = decoder.Decode(0).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value1")); node = decoder.Decode(22).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value2")); node = decoder.Decode(37).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value1")); node = decoder.Decode(50).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value2")); node = decoder.Decode(55).Node; Assert.That(node.Value<string>("long_key"), Is.EqualTo("long_value1")); node = decoder.Decode(57).Node; Assert.That(node.Value<string>("long_key2"), Is.EqualTo("long_value2")); } }
public int BruteForce(ArrayReader reader, int target) { int left = 0, right = 10000; while (left <= right) { int mid = left + (right - left) / 2; int element = reader.Get(mid); if (element == Int32.MaxValue) { right = mid - 1; continue; } if (element == target) { return(mid); } else if (element < target) { left = mid + 1; } else { right = mid - 1; } } return(-1); }
public T[][] GetParamArr2 <T>(object key) { Object[][] input = (Object[][])GetParam(key); ArrayReader <T> reader = new ArrayReader <T>(); return(reader.read2(input)); }
public int Search(ArrayReader reader, int target) { int left = 0; int right = 1; while(reader.get(right) < target) { left = right; right <<= 1; } while(left <= right) { var mid = left + ((right - left) >> 1); var temp = reader.get(mid); if (temp == target) { return mid; } else if (temp < target) { left = mid + 1; } else { right = mid - 1; } } return -1; }
public CNetwork(string ip, int port) { client = new NetObjectClient(); IP = ip; Port = port; writer = new ArrayWriter(); reader = new ArrayReader(buffer); }
private AnyValue(ValueType valueType, bool boolVal, double numberVal, string stringVal, ArrayReader arrayVal, ObjectReader objectVal) { Type = valueType; BoolValue = boolVal; NumberValue = numberVal; StringValue = stringVal; ArrayValue = arrayVal; ObjectValue = objectVal; }
private CommandConfig FindDefaultCommandConfig(CommandConfig commandConfig, ArrayReader <string> argumentsReader) { while (HasDefaultCommand(commandConfig)) { commandConfig = GetDefaultCommandConfig(commandConfig); } InitBaseOptions(ref commandConfig); return(commandConfig); }
private bool ReadParam(CommandArgs commandArgs, ArrayReader <Parameter> parameters, string arg) { if (!parameters.HasData()) { return(false); } var parameter = parameters.Read(); commandArgs.AddParameterValueProvider(parameter.Name, new ConstValueProvider(_valueConverter.ConvertValueToExpectedType(arg, parameter.ValueType, parameter.Converter))); return(true); }
public void ReturnsNullWhenNoMoreItemsOnNullableType() { // This test needs an array with nullable type so it // initializes its own instance: var nullableData = new int?[] { 1, 2, 3, 4 }; var nullableArrayReader = new ArrayReader <int?>(nullableData); // Read to the end: while (nullableArrayReader.Read()) { } Assert.AreEqual(null, nullableArrayReader.Peek()); }
private Result OnReceive(RedisRequest request, PipeStream pipeStream) { if (mReader == null) { if (pipeStream.TryReadLine(out string line)) { if (line[0] == '-') { throw new RedisException(line.Substring(1)); } var count = int.Parse(line.Substring(1)); if (count == 0) { return new Result { ResultType = ResultType.Arrays } } ; mReader = new ArrayReader(this, count, (client, cmd, stream, length, level) => { return(stream.ReadString(length)); }); } else { return(null); } } if (mReader.Read(pipeStream, request.Client) == ArrayReader.Status.End) { Result result = new Result(); result.ResultType = ResultType.Arrays; var data = mReader.Items; foreach (var item in data) { RadiusItem ritem = new RadiusItem(); List <ArrayDataItem> baseinfo = (List <ArrayDataItem>)item.Value; List <ArrayDataItem> locationInfo = (List <ArrayDataItem>)baseinfo[2].Value; ritem.Name = (string)baseinfo[0].Value; ritem.Value = double.Parse((string)baseinfo[1].Value); ritem.Longitude = Double.Parse((string)locationInfo[0].Value); ritem.Latitude = Double.Parse((string)locationInfo[1].Value); result.Data.Add(new ResultItem { Type = ResultType.Object, Data = ritem }); } return(result); } return(null); } }
private CommandConfig ParseCommands(CommandConfig commandConfig, ArrayReader <string> argumentsReader) { while (argumentsReader.HasData() && ArgIsCommand(commandConfig, argumentsReader.Current())) { if (argumentsReader.HasData() && ArgIsCommand(commandConfig, argumentsReader.Current())) { commandConfig = GetSubCommandConfig(commandConfig, argumentsReader.Read()); } } InitBaseOptions(ref commandConfig); return(commandConfig); }
public static int Search(ArrayReader reader, int key) { // TODO: Write your code here int tempEnd = 1; int tempStart = 0; while (reader.Get(tempEnd) < key) { tempStart = tempEnd; tempEnd *= 2; if (reader.Get(tempEnd) == key) { return(tempEnd); } } return(BinarySearch(reader, key, tempStart, tempEnd)); }
public void Test_ArrayReader() { const string raw = "[10 20 -5 -0.5] [/NestedArrays [/NestedArray1 [/NestedArray2 [/NestedArray3]]]] [/Name1/Name2/Name3] []"; var stream = new MemoryStream(Encoding.ASCII.GetBytes(raw)); var reader = new ArrayReader(stream, null); var obj = reader.Read(); Assert.IsNotNull(obj); Assert.AreEqual(4, obj.Values.Count); Assert.AreEqual(10, ((IntegerObject) obj[0]).Value); Assert.AreEqual(20, ((IntegerObject) obj[1]).Value); Assert.AreEqual(-5, ((IntegerObject) obj[2]).Value); Assert.AreEqual(-0.5f, ((RealObject) obj[3]).Value); obj = reader.Read(); Assert.IsNotNull(obj); Assert.AreEqual(2, obj.Values.Count); Assert.AreEqual("NestedArrays", ((NameObject) obj[0]).Value); obj = (ArrayObject) obj[1]; Assert.AreEqual(2, obj.Values.Count); Assert.AreEqual("NestedArray1", ((NameObject) obj[0]).Value); obj = (ArrayObject) obj[1]; Assert.AreEqual(2, obj.Values.Count); Assert.AreEqual("NestedArray2", ((NameObject) obj[0]).Value); obj = (ArrayObject) obj[1]; Assert.AreEqual(1, obj.Values.Count); Assert.AreEqual("NestedArray3", ((NameObject) obj[0]).Value); obj = reader.Read(); Assert.IsNotNull(obj); Assert.AreEqual(3, obj.Values.Count); Assert.AreEqual("Name1", ((NameObject) obj[0]).Value); Assert.AreEqual("Name2", ((NameObject) obj[1]).Value); Assert.AreEqual("Name3", ((NameObject) obj[2]).Value); obj = reader.Read(); Assert.IsNotNull(obj); Assert.AreEqual(0, obj.Values.Count); stream.Dispose(); }
public void Should_AttainDifferentWeight_ForWordsWithDifferentFrequency() { var reader = new ArrayReader(new[] { "a", "b", "a" }); var preprocessor = new WordPreprocessor( reader, new IPreprocessingRule[] { new LoweringRule() }); preprocessor .GetPreprocessedWordsFromFile("") .Select(weightedWord => weightedWord.Weight) .ToHashSet() .Count() .Should() .Be(2); }
public int Search(ArrayReader reader, int target) { int left = 0, right = 1; while (reader.Get(right) < target) { left = right; right *= 2; } // [-1, 0, 3, 5, 9, 12] target = 9 // l r // l r // l r // l r // To keep logarithmic time complexity, let's extend it twice as far. // If the reader[right] < target, then we can ignore all left side of the "right" index and move the search boundary to the right. while (left <= right) { int mid = left + (right - left) / 2; int element = reader.Get(mid); if (element == target) { return(mid); } else if (element < target) { left = mid + 1; } else { right = mid - 1; } } return(-1); }
private Result OnReceive(RedisRequest request, PipeStream pipeStream) { if (mReader == null) { if (pipeStream.TryReadLine(out string line)) { var count = int.Parse(line.Substring(1)); mReader = new ArrayReader(this, count, (client, cmd, stream, length, level) => { return(stream.ReadString(length)); }); } else { return(null); } } if (mReader.Read(pipeStream, request.Client) == ArrayReader.Status.End) { var items = mReader.Items; Result data = new Result(); foreach (var item in items) { List <ArrayDataItem> childs = (List <ArrayDataItem>)item.Value; GeoLocation location = new GeoLocation(); if (childs.Count > 0) { location.Longitude = double.Parse((string)childs[0].Value); location.Latitude = double.Parse((string)childs[1].Value); } data.Data.Add(new ResultItem { Type = ResultType.Object, Data = location }); } return(data); } return(null); }
private static int BinarySearch(ArrayReader reader, int key, int start, int end) { while (start <= end) { int mid = start + (end - start) / 2; if (reader.Get(mid) == key) { return(mid); } if (reader.Get(mid) > key) { end = mid - 1; } else { start = mid + 1; } } return(-1); }
private Task ConsoleOutputAsync(Stream stream) { return(Task.Run(async delegate { var ansiParser = new AnsiParser(); var sr = new StreamReader(stream, Encoding.UTF8); do { int offset = 0; var buffer = new char[1024]; int readChars = await sr.ReadAsync(buffer, offset, buffer.Length - offset); File.WriteAllText("dbg.txt", new string(buffer)); if (readChars > 0) { var reader = new ArrayReader <char>(buffer, 0, readChars); var codes = ansiParser.Parse(reader); ReceiveOutput(codes); } } while (!sr.EndOfStream); ; })); }
/** * @param reader: An instance of ArrayReader can read number by index. * @param target: An integer * @return : An integer which is the index of the target number */ public int SearchBigSortedArray(ArrayReader reader, int target) { // Algorithm: // 1. get the index that ArrayReader.get(index) >= target in // O(logk) // 2. Binary search the target between 0 and index int index = 1; while (reader.get(index - 1) < target) { index = index * 2; } int start = 0, end = index - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (reader.get(mid) < target) { start = mid; } else { end = mid; } } if (reader.get(start) == target) { return(start); } if (reader.get(end) == target) { return(end); } return(-1); }
public override string ReadValue(ArrayReader <string> args, string arg) { return(arg.Split(new[] { EqualitySign }, 2)[1]); }
internal ContentTypeReader[] LoadAssetReaders(ContentReader reader) { #pragma warning disable 0219, 0649 /* Trick to prevent the linker removing the code, but not actually execute the code * FIXME: Do we really need this in FNA? */ if (falseflag) { /* Dummy variables required for it to work on iDevices ** DO NOT DELETE ** * This forces the classes not to be optimized out when deploying to iDevices */ ByteReader hByteReader = new ByteReader(); SByteReader hSByteReader = new SByteReader(); DateTimeReader hDateTimeReader = new DateTimeReader(); DecimalReader hDecimalReader = new DecimalReader(); BoundingSphereReader hBoundingSphereReader = new BoundingSphereReader(); BoundingFrustumReader hBoundingFrustumReader = new BoundingFrustumReader(); RayReader hRayReader = new RayReader(); ListReader<char> hCharListReader = new ListReader<Char>(); ListReader<Rectangle> hRectangleListReader = new ListReader<Rectangle>(); ArrayReader<Rectangle> hRectangleArrayReader = new ArrayReader<Rectangle>(); ListReader<Vector3> hVector3ListReader = new ListReader<Vector3>(); ListReader<StringReader> hStringListReader = new ListReader<StringReader>(); ListReader<int> hIntListReader = new ListReader<Int32>(); SpriteFontReader hSpriteFontReader = new SpriteFontReader(); Texture2DReader hTexture2DReader = new Texture2DReader(); CharReader hCharReader = new CharReader(); RectangleReader hRectangleReader = new RectangleReader(); StringReader hStringReader = new StringReader(); Vector2Reader hVector2Reader = new Vector2Reader(); Vector3Reader hVector3Reader = new Vector3Reader(); Vector4Reader hVector4Reader = new Vector4Reader(); CurveReader hCurveReader = new CurveReader(); IndexBufferReader hIndexBufferReader = new IndexBufferReader(); BoundingBoxReader hBoundingBoxReader = new BoundingBoxReader(); MatrixReader hMatrixReader = new MatrixReader(); BasicEffectReader hBasicEffectReader = new BasicEffectReader(); VertexBufferReader hVertexBufferReader = new VertexBufferReader(); AlphaTestEffectReader hAlphaTestEffectReader = new AlphaTestEffectReader(); EnumReader<Microsoft.Xna.Framework.Graphics.SpriteEffects> hEnumSpriteEffectsReader = new EnumReader<Graphics.SpriteEffects>(); ArrayReader<float> hArrayFloatReader = new ArrayReader<float>(); ArrayReader<Vector2> hArrayVector2Reader = new ArrayReader<Vector2>(); ListReader<Vector2> hListVector2Reader = new ListReader<Vector2>(); ArrayReader<Matrix> hArrayMatrixReader = new ArrayReader<Matrix>(); EnumReader<Microsoft.Xna.Framework.Graphics.Blend> hEnumBlendReader = new EnumReader<Graphics.Blend>(); NullableReader<Rectangle> hNullableRectReader = new NullableReader<Rectangle>(); EffectMaterialReader hEffectMaterialReader = new EffectMaterialReader(); ExternalReferenceReader hExternalReferenceReader = new ExternalReferenceReader(); SoundEffectReader hSoundEffectReader = new SoundEffectReader(); SongReader hSongReader = new SongReader(); } #pragma warning restore 0219, 0649 /* The first content byte i read tells me the number of * content readers in this XNB file. */ int numberOfReaders = reader.Read7BitEncodedInt(); ContentTypeReader[] newReaders = new ContentTypeReader[numberOfReaders]; BitArray needsInitialize = new BitArray(numberOfReaders); contentReaders = new Dictionary<Type, ContentTypeReader>(numberOfReaders); /* Lock until we're done allocating and initializing any new * content type readers... this ensures we can load content * from multiple threads and still cache the readers. */ lock (locker) { /* For each reader in the file, we read out the * length of the string which contains the type * of the reader, then we read out the string. * Finally we instantiate an instance of that * reader using reflection. */ for (int i = 0; i < numberOfReaders; i += 1) { /* This string tells us what reader we * need to decode the following data. */ string originalReaderTypeString = reader.ReadString(); Func<ContentTypeReader> readerFunc; if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc)) { newReaders[i] = readerFunc(); needsInitialize[i] = true; } else { // Need to resolve namespace differences string readerTypeString = originalReaderTypeString; readerTypeString = PrepareType(readerTypeString); Type l_readerType = Type.GetType(readerTypeString); if (l_readerType != null) { ContentTypeReader typeReader; if (!contentReadersCache.TryGetValue(l_readerType, out typeReader)) { try { typeReader = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader; } catch (TargetInvocationException ex) { /* If you are getting here, the Mono runtime * is most likely not able to JIT the type. * In particular, MonoTouch needs help * instantiating types that are only defined * in strings in Xnb files. */ throw new InvalidOperationException( "Failed to get default constructor for ContentTypeReader. " + "To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " + "with the following failed type string: " + originalReaderTypeString, ex ); } needsInitialize[i] = true; contentReadersCache.Add(l_readerType, typeReader); } newReaders[i] = typeReader; } else { throw new ContentLoadException( "Could not find ContentTypeReader Type. " + "Please ensure the name of the Assembly that " + "contains the Type matches the assembly in the full type name: " + originalReaderTypeString + " (" + readerTypeString + ")" ); } } contentReaders.Add(newReaders[i].TargetType, newReaders[i]); /* I think the next 4 bytes refer to the "Version" of the type reader, * although it always seems to be zero. */ reader.ReadInt32(); } // Initialize any new readers. for (int i = 0; i < newReaders.Length; i += 1) { if (needsInitialize.Get(i)) { newReaders[i].Initialize(this); } } } // lock (locker) return newReaders; }
/// <summary> /// Initializes an array value. /// </summary> /// <returns>an <c>AnyValue</c></returns> public static AnyValue Array(ArrayReader value) => new AnyValue(ValueType.Array, false, 0, null, value, new ObjectReader());
public override string ReadValue(ArrayReader <string> args, string arg) { return(args.Read()); }
internal ContentTypeReader[] LoadAssetReaders() { if (ContentTypeReaderManager.falseflag) { ByteReader byteReader = new ByteReader(); SByteReader sbyteReader = new SByteReader(); DateTimeReader dateTimeReader = new DateTimeReader(); DecimalReader decimalReader = new DecimalReader(); BoundingSphereReader boundingSphereReader = new BoundingSphereReader(); BoundingFrustumReader boundingFrustumReader = new BoundingFrustumReader(); RayReader rayReader = new RayReader(); ListReader<char> listReader1 = new ListReader<char>(); ListReader<Rectangle> listReader2 = new ListReader<Rectangle>(); ArrayReader<Rectangle> arrayReader1 = new ArrayReader<Rectangle>(); ListReader<Vector3> listReader3 = new ListReader<Vector3>(); ListReader<StringReader> listReader4 = new ListReader<StringReader>(); ListReader<int> listReader5 = new ListReader<int>(); SpriteFontReader spriteFontReader = new SpriteFontReader(); Texture2DReader texture2Dreader = new Texture2DReader(); CharReader charReader = new CharReader(); RectangleReader rectangleReader = new RectangleReader(); StringReader stringReader = new StringReader(); Vector2Reader vector2Reader = new Vector2Reader(); Vector3Reader vector3Reader = new Vector3Reader(); Vector4Reader vector4Reader = new Vector4Reader(); CurveReader curveReader = new CurveReader(); IndexBufferReader indexBufferReader = new IndexBufferReader(); BoundingBoxReader boundingBoxReader = new BoundingBoxReader(); MatrixReader matrixReader = new MatrixReader(); BasicEffectReader basicEffectReader = new BasicEffectReader(); VertexBufferReader vertexBufferReader = new VertexBufferReader(); AlphaTestEffectReader testEffectReader = new AlphaTestEffectReader(); EnumReader<SpriteEffects> enumReader1 = new EnumReader<SpriteEffects>(); ArrayReader<float> arrayReader2 = new ArrayReader<float>(); ArrayReader<Vector2> arrayReader3 = new ArrayReader<Vector2>(); ListReader<Vector2> listReader6 = new ListReader<Vector2>(); ArrayReader<Matrix> arrayReader4 = new ArrayReader<Matrix>(); EnumReader<Blend> enumReader2 = new EnumReader<Blend>(); NullableReader<Rectangle> nullableReader = new NullableReader<Rectangle>(); EffectMaterialReader effectMaterialReader = new EffectMaterialReader(); ExternalReferenceReader externalReferenceReader = new ExternalReferenceReader(); } int length = this._reader.Read7BitEncodedInt(); this.contentReaders = new ContentTypeReader[length]; for (int index = 0; index < length; ++index) { string str = this._reader.ReadString(); Func<ContentTypeReader> func; if (ContentTypeReaderManager.typeCreators.TryGetValue(str, out func)) { this.contentReaders[index] = func(); } else { string typeName = ContentTypeReaderManager.PrepareType(str); Type type = Type.GetType(typeName); if (type != (Type) null) { try { this.contentReaders[index] = ContentExtensions.GetDefaultConstructor(type).Invoke((object[]) null) as ContentTypeReader; } catch (TargetInvocationException ex) { throw new InvalidOperationException("Failed to get default constructor for ContentTypeReader. To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() with the following failed type string: " + str); } } else throw new ContentLoadException("Could not find matching content reader of type " + str + " (" + typeName + ")"); } this._reader.ReadInt32(); } return this.contentReaders; }
internal ContentTypeReader[] LoadAssetReaders(ContentReader reader) { #pragma warning disable 0219, 0649 // Trick to prevent the linker removing the code, but not actually execute the code if (falseflag) { // Dummy variables required for it to work on iDevices ** DO NOT DELETE ** // This forces the classes not to be optimized out when deploying to iDevices var hByteReader = new ByteReader(); var hSByteReader = new SByteReader(); var hDateTimeReader = new DateTimeReader(); var hDecimalReader = new DecimalReader(); var hBoundingSphereReader = new BoundingSphereReader(); var hBoundingFrustumReader = new BoundingFrustumReader(); var hRayReader = new RayReader(); var hCharListReader = new ListReader<Char>(); var hRectangleListReader = new ListReader<Rectangle>(); var hRectangleArrayReader = new ArrayReader<Rectangle>(); var hVector3ListReader = new ListReader<Vector3>(); var hStringListReader = new ListReader<StringReader>(); var hIntListReader = new ListReader<Int32>(); var hSpriteFontReader = new SpriteFontReader(); var hTexture2DReader = new Texture2DReader(); var hCharReader = new CharReader(); var hRectangleReader = new RectangleReader(); var hStringReader = new StringReader(); var hVector2Reader = new Vector2Reader(); var hVector3Reader = new Vector3Reader(); var hVector4Reader = new Vector4Reader(); var hCurveReader = new CurveReader(); var hIndexBufferReader = new IndexBufferReader(); var hBoundingBoxReader = new BoundingBoxReader(); var hMatrixReader = new MatrixReader(); var hBasicEffectReader = new BasicEffectReader(); var hVertexBufferReader = new VertexBufferReader(); var hAlphaTestEffectReader = new AlphaTestEffectReader(); var hEnumSpriteEffectsReader = new EnumReader<Graphics.SpriteEffects>(); var hArrayFloatReader = new ArrayReader<float>(); var hArrayVector2Reader = new ArrayReader<Vector2>(); var hListVector2Reader = new ListReader<Vector2>(); var hArrayMatrixReader = new ArrayReader<Matrix>(); var hEnumBlendReader = new EnumReader<Graphics.Blend>(); var hNullableRectReader = new NullableReader<Rectangle>(); var hEffectMaterialReader = new EffectMaterialReader(); var hExternalReferenceReader = new ExternalReferenceReader(); var hSoundEffectReader = new SoundEffectReader(); var hSongReader = new SongReader(); var hModelReader = new ModelReader(); var hInt32Reader = new Int32Reader(); // At the moment the Video class doesn't exist // on all platforms... Allow it to compile anyway. #if ANDROID || IOS || MONOMAC || (WINDOWS && !OPENGL) || (WINRT && !WINDOWS_PHONE) var hVideoReader = new VideoReader(); #endif } #pragma warning restore 0219, 0649 // The first content byte i read tells me the number of content readers in this XNB file var numberOfReaders = reader.Read7BitEncodedInt(); var contentReaders = new ContentTypeReader[numberOfReaders]; var needsInitialize = new BitArray(numberOfReaders); _contentReaders = new Dictionary<Type, ContentTypeReader>(numberOfReaders); // Lock until we're done allocating and initializing any new // content type readers... this ensures we can load content // from multiple threads and still cache the readers. lock (_locker) { // For each reader in the file, we read out the length of the string which contains the type of the reader, // then we read out the string. Finally we instantiate an instance of that reader using reflection for (var i = 0; i < numberOfReaders; i++) { // This string tells us what reader we need to decode the following data // string readerTypeString = reader.ReadString(); string originalReaderTypeString = reader.ReadString(); Func<ContentTypeReader> readerFunc; if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc)) { contentReaders[i] = readerFunc(); needsInitialize[i] = true; } else { //System.Diagnostics.Debug.WriteLine(originalReaderTypeString); // Need to resolve namespace differences string readerTypeString = originalReaderTypeString; readerTypeString = PrepareType(readerTypeString); var l_readerType = Type.GetType(readerTypeString); if (l_readerType != null) { ContentTypeReader typeReader; if (!_contentReadersCache.TryGetValue(l_readerType, out typeReader)) { try { typeReader = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader; } catch (TargetInvocationException ex) { // If you are getting here, the Mono runtime is most likely not able to JIT the type. // In particular, MonoTouch needs help instantiating types that are only defined in strings in Xnb files. throw new InvalidOperationException( "Failed to get default constructor for ContentTypeReader. To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " + "with the following failed type string: " + originalReaderTypeString, ex); } needsInitialize[i] = true; _contentReadersCache.Add(l_readerType, typeReader); } contentReaders[i] = typeReader; } else throw new ContentLoadException( "Could not find ContentTypeReader Type. Please ensure the name of the Assembly that contains the Type matches the assembly in the full type name: " + originalReaderTypeString + " (" + readerTypeString + ")"); } var targetType = contentReaders[i].TargetType; if (targetType != null) _contentReaders.Add(targetType, contentReaders[i]); // I think the next 4 bytes refer to the "Version" of the type reader, // although it always seems to be zero reader.ReadInt32(); } // Initialize any new readers. for (var i = 0; i < contentReaders.Length; i++) { if (needsInitialize.Get(i)) contentReaders[i].Initialize(this); } } // lock (_locker) return contentReaders; }
//------------------------------------------------------------------------------------- internal static void Customize(byte[] body, DynamicILInfo ilInfo, Dictionary<int, DiscoverMemberInfo> schema) { BindingFlags bf = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static; ArrayReader ar = new ArrayReader(body); while(ar.CanRead) { int offset = ar.Position; OpCode opCode = OpCodes.Nop; //int token = 0; Byte code = ar.ReadByte(); if(code != 0xFE) opCode = OneByteOpCodes[code]; else opCode = TwoByteOpCodes[ar.ReadByte()]; switch(opCode.OperandType) { #region ... case OperandType.InlineNone: break; //The operand is an 8-bit integer branch target. case OperandType.ShortInlineBrTarget: ar.ReadSByte(); break; //The operand is a 32-bit integer branch target. case OperandType.InlineBrTarget: ar.ReadInt32(); break; //The operand is an 8-bit integer: 001F ldc.i4.s, FE12 unaligned. case OperandType.ShortInlineI: ar.ReadByte(); break; //The operand is a 32-bit integer. case OperandType.InlineI: ar.ReadInt32(); break; //The operand is a 64-bit integer. case OperandType.InlineI8: ar.ReadInt64(); break; //The operand is a 32-bit IEEE floating point number. case OperandType.ShortInlineR: ar.ReadSingle(); break; //The operand is a 64-bit IEEE floating point number. case OperandType.InlineR: ar.ReadDouble(); break; //The operand is an 8-bit integer containing the ordinal of a local variable or an argument case OperandType.ShortInlineVar: ar.ReadByte(); break; //The operand is 16-bit integer containing the ordinal of a local variable or an argument. case OperandType.InlineVar: ar.ReadUInt16(); break; #endregion ... //The operand is a 32-bit metadata string token. case OperandType.InlineString: { #region ... int token = ar.ReadInt32(); string s = new String(schema[token].Name.ToCharArray()); ar.OverwriteInt32(ilInfo.GetTokenFor(s), offset + opCode.Size); #endregion ... } break; //The operand is a 32-bit metadata signature token. case OperandType.InlineSig: { #region ... throw new Exception("НАДО ПРОВЕРИТЬ InlineSig !!!"); //int token = ar.ReadInt32(); //OverwriteInt32(ilInfo.GetTokenFor(inlineSigInstruction.Signature), //inlineSigInstruction.Offset + inlineSigInstruction.OpCode.Size); #endregion ... } //break; //The operand is a 32-bit metadata token. case OperandType.InlineMethod: { #region ... int token = ar.ReadInt32(); MethodBase mi; Type t = schema[token].DeclaringType; // ?? dstType; if(schema[token].Name.StartsWith(".ctor")) mi = t.GetConstructor(bf, null, schema[token].ParametersTypes, null); else mi = t.GetMethod(schema[token].Name, bf, null, schema[token].ParametersTypes, null); if(mi == null) throw new PulsarException("Не удалось определить MethodBase для операнда {0}:{1}", opCode, opCode.OperandType); ar.OverwriteInt32(ilInfo.GetTokenFor(mi.MethodHandle, t.TypeHandle), offset + opCode.Size); #endregion ... } break; //The operand is a 32-bit metadata token. case OperandType.InlineField: { #region ... int token = ar.ReadInt32(); FieldInfo fi = schema[token].DeclaringType.GetField(schema[token].Name, bf | BindingFlags.FlattenHierarchy); if(fi == null) throw new PulsarException("Не удалось определить FieldInfo для операнда {0}:{1}", opCode, opCode.OperandType); ar.OverwriteInt32(ilInfo.GetTokenFor(fi.FieldHandle), offset + opCode.Size); #endregion ... } break; //The operand is a 32-bit metadata token. case OperandType.InlineType: { #region ... int token = ar.ReadInt32(); Type t = schema[token].DeclaringType; ar.OverwriteInt32(ilInfo.GetTokenFor(t.TypeHandle), offset + opCode.Size); #endregion ... } break; //The operand is a FieldRef, MethodRef, or TypeRef token. case OperandType.InlineTok: { #region ... throw new Exception("НАДО ПРОВЕРИТЬ InlineTok !!!"); //int token = ar.ReadInt32(); // MemberInfo mi = inlineTokInstruction.Member; //int token = 0; //if(mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) //{ // Type type = mi as Type; // token = ilInfo.GetTokenFor(type.TypeHandle); //} //else if(mi.MemberType == MemberTypes.Method || mi.MemberType == MemberTypes.Constructor) //{ // MethodBase m = mi as MethodBase; // token = ilInfo.GetTokenFor(m.MethodHandle, m.DeclaringType.TypeHandle); //} //else if(mi.MemberType == MemberTypes.Field) //{ // FieldInfo f = mi as FieldInfo; // //CLR BUG: token = ilInfo.GetTokenFor(f.FieldHandle, f.DeclaringType.TypeHandle); // token = ilInfo.GetTokenFor(f.FieldHandle); //} //OverwriteInt32(token, // inlineTokInstruction.Offset + inlineTokInstruction.OpCode.Size); #endregion ... } //break; //The operand is the 32-bit integer argument to a switch instruction. case OperandType.InlineSwitch: { #region ... throw new Exception("НАДО ПРОВЕРИТЬ InlineSwitch !!!"); //Int32 cases = ar.ReadInt32(); //Int32[] deltas = new Int32[cases]; //for(Int32 i = 0; i < cases; i++) // deltas[i] = ar.ReadInt32(); #endregion ... } //break; default: throw new BadImageFormatException("Unexpected OperandType " + opCode.OperandType); } } }
//------------------------------------------------------------------------------------- internal static Dictionary<int, DiscoverMemberInfo> Discover(byte[] body, MethodInfo mi, Type dstType) { Dictionary<int, DiscoverMemberInfo> res = new Dictionary<int, DiscoverMemberInfo>(); ArrayReader ar = new ArrayReader(body); while(ar.CanRead) { int offset = ar.Position; OpCode opCode = OpCodes.Nop; //int token = 0; Byte code = ar.ReadByte(); if(code != 0xFE) opCode = OneByteOpCodes[code]; else opCode = TwoByteOpCodes[ar.ReadByte()]; switch(opCode.OperandType) { #region ... case OperandType.InlineNone: break; //The operand is an 8-bit integer branch target. case OperandType.ShortInlineBrTarget: ar.ReadSByte(); break; //The operand is a 32-bit integer branch target. case OperandType.InlineBrTarget: ar.ReadInt32(); break; //The operand is an 8-bit integer: 001F ldc.i4.s, FE12 unaligned. case OperandType.ShortInlineI: ar.ReadByte(); break; //The operand is a 32-bit integer. case OperandType.InlineI: ar.ReadInt32(); break; //The operand is a 64-bit integer. case OperandType.InlineI8: ar.ReadInt64(); break; //The operand is a 32-bit IEEE floating point number. case OperandType.ShortInlineR: ar.ReadSingle(); break; //The operand is a 64-bit IEEE floating point number. case OperandType.InlineR: ar.ReadDouble(); break; //The operand is an 8-bit integer containing the ordinal of a local variable or an argument case OperandType.ShortInlineVar: ar.ReadByte(); break; //The operand is 16-bit integer containing the ordinal of a local variable or an argument. case OperandType.InlineVar: ar.ReadUInt16(); break; #endregion ... //The operand is a 32-bit metadata string token. case OperandType.InlineString: { #region ... int token = ar.ReadInt32(); if(res.ContainsKey(token)) break; string s = mi.Module.ResolveString(token); res.Add(token, new DiscoverMemberInfo(s)); #endregion ... } break; //The operand is a 32-bit metadata signature token. case OperandType.InlineSig: { #region ... throw new Exception("НАДО ПРОВЕРИТЬ InlineSig !!!"); //int token = ar.ReadInt32(); //if(res.ContainsKey(token)) // break; #endregion ... } //break; //The operand is a 32-bit metadata token. case OperandType.InlineMethod: { #region ... int token = ar.ReadInt32(); if(res.ContainsKey(token)) break; MethodBase mb = mi.Module.ResolveMethod(token); if(mb == null) throw new PulsarException("Не удалось определить MethodBase для операнда {0}:{1}", opCode, opCode.OperandType); DiscoverMemberInfo dmi = new DiscoverMemberInfo(); dmi.Name = mb.Name; dmi.GenericArguments = (mb.IsConstructor) ? null : mb.GetGenericArguments(); //dmi.DeclaringTypeGenericArguments = (mb.DeclaringType ?? typeof(Type)).GetGenericArguments(); dmi.ParametersTypes = dmi.GetParametesTypes(mb.GetParameters()); if(mi.DeclaringType.Equals(mb.DeclaringType)) dmi.DeclaringType = dstType; else dmi.DeclaringType = mb.DeclaringType; res.Add(token, dmi); #endregion ... } break; //The operand is a 32-bit metadata token. case OperandType.InlineField: { #region ... int token = ar.ReadInt32(); if(res.ContainsKey(token)) break; FieldInfo fi = mi.Module.ResolveField(token); if(fi == null) throw new PulsarException("Не удалось определить FieldInfo для операнда {0}:{1}", opCode, opCode.OperandType); DiscoverMemberInfo dmi = new DiscoverMemberInfo(); dmi.Name = fi.Name; if(mi.DeclaringType.Equals(fi.DeclaringType)) dmi.DeclaringType = dstType; else dmi.DeclaringType = fi.DeclaringType; res.Add(token, dmi); #endregion ... } break; //The operand is a 32-bit metadata token. case OperandType.InlineType: { #region ... int token = ar.ReadInt32(); if(res.ContainsKey(token)) break; Type t = mi.Module.ResolveType(token, null, null); if(t == null) throw new PulsarException("Не удалось определить Type для операнда {0}:{1}", opCode, opCode.OperandType); DiscoverMemberInfo dmi = new DiscoverMemberInfo(); dmi.Name = t.FullName; dmi.DeclaringType = t; dmi.GenericArguments = t.GetGenericArguments(); res.Add(token, dmi); #endregion ... } break; //The operand is a FieldRef, MethodRef, or TypeRef token. case OperandType.InlineTok: { #region ... throw new Exception("НАДО ПРОВЕРИТЬ InlineTok !!!"); //int token = ar.ReadInt32(); //if(res.ContainsKey(token)) // break; // MemberInfo mi = inlineTokInstruction.Member; //int token = 0; //if(mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) //{ // Type type = mi as Type; // token = ilInfo.GetTokenFor(type.TypeHandle); //} //else if(mi.MemberType == MemberTypes.Method || mi.MemberType == MemberTypes.Constructor) //{ // MethodBase m = mi as MethodBase; // token = ilInfo.GetTokenFor(m.MethodHandle, m.DeclaringType.TypeHandle); //} //else if(mi.MemberType == MemberTypes.Field) //{ // FieldInfo f = mi as FieldInfo; // //CLR BUG: token = ilInfo.GetTokenFor(f.FieldHandle, f.DeclaringType.TypeHandle); // token = ilInfo.GetTokenFor(f.FieldHandle); //} //OverwriteInt32(token, // inlineTokInstruction.Offset + inlineTokInstruction.OpCode.Size); #endregion ... } // break; //The operand is the 32-bit integer argument to a switch instruction. case OperandType.InlineSwitch: { #region ... throw new Exception("НАДО ПРОВЕРИТЬ InlineSwitch !!!"); //Int32 cases = ar.ReadInt32(); //Int32[] deltas = new Int32[cases]; //for(Int32 i = 0; i < cases; i++) // deltas[i] = ar.ReadInt32(); #endregion ... } //break; default: throw new BadImageFormatException("Unexpected OperandType " + opCode.OperandType); } } return res; }
internal ContentTypeReader[] LoadAssetReaders() { #pragma warning disable 0219, 0649 // Trick to prevent the linker removing the code, but not actually execute the code if (falseflag) { // Dummy variables required for it to work on iDevices ** DO NOT DELETE ** // This forces the classes not to be optimized out when deploying to iDevices var hByteReader = new ByteReader(); var hSByteReader = new SByteReader(); var hDateTimeReader = new DateTimeReader(); var hDecimalReader = new DecimalReader(); var hBoundingSphereReader = new BoundingSphereReader(); var hBoundingFrustumReader = new BoundingFrustumReader(); var hRayReader = new RayReader(); var hCharListReader = new ListReader<Char>(); var hRectangleListReader = new ListReader<Rectangle>(); var hRectangleArrayReader = new ArrayReader<Rectangle>(); var hVector3ListReader = new ListReader<Vector3>(); var hStringListReader = new ListReader<StringReader>(); var hIntListReader = new ListReader<Int32>(); var hSpriteFontReader = new SpriteFontReader(); var hTexture2DReader = new Texture2DReader(); var hCharReader = new CharReader(); var hRectangleReader = new RectangleReader(); var hStringReader = new StringReader(); var hVector2Reader = new Vector2Reader(); var hVector3Reader = new Vector3Reader(); var hVector4Reader = new Vector4Reader(); var hCurveReader = new CurveReader(); var hIndexBufferReader = new IndexBufferReader(); var hBoundingBoxReader = new BoundingBoxReader(); var hMatrixReader = new MatrixReader(); var hBasicEffectReader = new BasicEffectReader(); var hVertexBufferReader = new VertexBufferReader(); var hAlphaTestEffectReader = new AlphaTestEffectReader(); var hEnumSpriteEffectsReader = new EnumReader<Graphics.SpriteEffects>(); var hArrayFloatReader = new ArrayReader<float>(); var hArrayVector2Reader = new ArrayReader<Vector2>(); var hListVector2Reader = new ListReader<Vector2>(); var hArrayMatrixReader = new ArrayReader<Matrix>(); var hEnumBlendReader = new EnumReader<Graphics.Blend>(); var hNullableRectReader = new NullableReader<Rectangle>(); var hEffectMaterialReader = new EffectMaterialReader(); var hExternalReferenceReader = new ExternalReferenceReader(); var hSoundEffectReader = new SoundEffectReader(); var hSongReader = new SongReader(); } #pragma warning restore 0219, 0649 int numberOfReaders; // The first content byte i read tells me the number of content readers in this XNB file numberOfReaders = _reader.Read7BitEncodedInt(); contentReaders = new ContentTypeReader[numberOfReaders]; // For each reader in the file, we read out the length of the string which contains the type of the reader, // then we read out the string. Finally we instantiate an instance of that reader using reflection for (int i = 0; i < numberOfReaders; i++) { // This string tells us what reader we need to decode the following data // string readerTypeString = reader.ReadString(); string originalReaderTypeString = _reader.ReadString(); Func<ContentTypeReader> readerFunc; if (typeCreators.TryGetValue(originalReaderTypeString, out readerFunc)) { contentReaders[i] = readerFunc(); } else { //System.Diagnostics.Debug.WriteLine(originalReaderTypeString); // Need to resolve namespace differences string readerTypeString = originalReaderTypeString; readerTypeString = PrepareType(readerTypeString); var l_readerType = Type.GetType(readerTypeString); if (l_readerType != null) { try { contentReaders[i] = l_readerType.GetDefaultConstructor().Invoke(null) as ContentTypeReader; } catch (TargetInvocationException ex) { // If you are getting here, the Mono runtime is most likely not able to JIT the type. // In particular, MonoTouch needs help instantiating types that are only defined in strings in Xnb files. throw new InvalidOperationException( "Failed to get default constructor for ContentTypeReader. To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() " + "with the following failed type string: " + originalReaderTypeString); } } else throw new ContentLoadException( "Could not find ContentTypeReader Type. Please ensure the name of the Assembly that contains the Type matches the assembly in the full type name: " + originalReaderTypeString + " (" + readerTypeString + ")"); } // I think the next 4 bytes refer to the "Version" of the type reader, // although it always seems to be zero int typeReaderVersion = _reader.ReadInt32(); } return contentReaders; }
internal ContentTypeReader[] LoadAssetReaders() { #pragma warning disable 0219, 0649 // Trick to prevent the linker removing the code, but not actually execute the code if (falseflag) { // Dummy variables required for it to work on iDevices ** DO NOT DELETE ** // This forces the classes not to be optimized out when deploying to iDevices var hByteReader = new ByteReader(); var hSByteReader = new SByteReader(); var hDateTimeReader = new DateTimeReader(); var hDecimalReader = new DecimalReader(); var hBoundingSphereReader = new BoundingSphereReader(); var hBoundingFrustumReader = new BoundingFrustumReader(); var hRayReader = new RayReader(); var hCharListReader = new ListReader<Char>(); var hRectangleListReader = new ListReader<Rectangle>(); var hRectangleArrayReader = new ArrayReader<Rectangle>(); var hVector3ListReader = new ListReader<Vector3>(); var hStringListReader = new ListReader<StringReader>(); var hSpriteFontReader = new SpriteFontReader(); var hTexture2DReader = new Texture2DReader(); var hCharReader = new CharReader(); var hRectangleReader = new RectangleReader(); var hStringReader = new StringReader(); var hVector2Reader = new Vector2Reader(); var hVector3Reader = new Vector3Reader(); var hVector4Reader = new Vector4Reader(); var hCurveReader = new CurveReader(); var hIndexBufferReader = new IndexBufferReader(); var hBoundingBoxReader = new BoundingBoxReader(); var hMatrixReader = new MatrixReader(); var hBasicEffectReader = new BasicEffectReader(); var hVertexBufferReader = new VertexBufferReader(); var hAlphaTestEffectReader = new AlphaTestEffectReader(); } #pragma warning restore 0219, 0649 int numberOfReaders; // The first content byte i read tells me the number of content readers in this XNB file numberOfReaders = _reader.Read7BitEncodedInt(); contentReaders = new ContentTypeReader[numberOfReaders]; // For each reader in the file, we read out the length of the string which contains the type of the reader, // then we read out the string. Finally we instantiate an instance of that reader using reflection for (int i = 0; i < numberOfReaders; i++) { // This string tells us what reader we need to decode the following data // string readerTypeString = reader.ReadString(); string originalReaderTypeString = _reader.ReadString(); // Need to resolve namespace differences string readerTypeString = originalReaderTypeString; readerTypeString = PrepareType(readerTypeString); Type l_readerType = Type.GetType(readerTypeString); if(l_readerType !=null) contentReaders[i] = (ContentTypeReader)Activator.CreateInstance(l_readerType,true); else throw new ContentLoadException("Could not find matching content reader of type " + originalReaderTypeString + " (" + readerTypeString + ")"); // I think the next 4 bytes refer to the "Version" of the type reader, // although it always seems to be zero int typeReaderVersion = _reader.ReadInt32(); } return contentReaders; }
private bool ReadOpt(IEnumerable <PrefixedDefaultValueArgument> options, CommandArgs commandArgs, Dictionary <string, ArrayAggregator> optionValues, ArrayReader <string> args, string arg) { var opt = options.FirstOrDefault( option => ArgMatcher.GetMatcher(_cliConfig.Dialect).IsOptionMatching(option, arg) ); if (opt == null) { return(false); } if (!opt.RequireValue) { if (opt.ValueType == typeof(bool)) { commandArgs.AddOptionValueProvider(opt.Name, new ConstValueProvider(!(bool)opt.DefaultValue)); } return(true); } var optionValue = OptionReader .GetReader(_cliConfig.Dialect.OptionValueMode) .ReadValue(args, arg); if (opt.ValueType.IsArray) { if (optionValues.ContainsKey(opt.Name)) { optionValues[opt.Name].Add(_valueConverter.ConvertValueToExpectedType(optionValue, opt.ValueType.GetElementType(), opt.Converter)); } else if (opt.ValueType.IsArray) { optionValues.Add(opt.Name, new ArrayAggregator(_valueConverter.ConvertValueToExpectedType(optionValue, opt.ValueType.GetElementType(), opt.Converter))); } } else { commandArgs.AddOptionValueProvider(opt.Name, new ConstValueProvider(_valueConverter.ConvertValueToExpectedType(optionValue, opt.ValueType, opt.Converter))); } return(true); }
public TerminalCode[] Parse(ArrayReader <char> reader) { _terminalCodes.Clear(); while (reader.TryRead(out char ch)) { int code = ch; // if (0xD800 <= code && code <= 0xDBFF) // { // // we got a surrogate high // // get surrogate low (next 2 bytes) // if (!reader.TryPeek(out char low)) // { // // end of data stream, save surrogate high // // this._terminal.surrogate_high = ch; // continue; // } // code = ((code - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; // // ch += low; // } // // surrogate low - already handled above // if (0xDC00 <= code && code <= 0xDFFF) // { // continue; // } switch (_state) { case ParserState.Normal: if (!NormalStateHandler(ch)) { Emit(ch); } break; case ParserState.Escaped: if (!EscapedStateHandler(ch)) { switch (ch) { // ESC (,),*,+,-,. Designate G0-G2 Character Set. case '(': // <-- this seems to get all the attention // this._terminal.gcharset = 0; _state = ParserState.Charset; break; case ')': case '-': // this._terminal.gcharset = 1; _state = ParserState.Charset; break; case '*': case '.': // this._terminal.gcharset = 2; _state = ParserState.Charset; break; case '+': // this._terminal.gcharset = 3; _state = ParserState.Charset; break; // Designate G3 Character Set (VT300). // A = ISO Latin-1 Supplemental. // Not implemented. case '/': // _terminal.gcharset = 3; _state = ParserState.Charset; // _position-- break; // ESC N // Single Shift Select of G2 Character Set // ( SS2 is 0x8e). This affects next character only. case 'N': break; // ESC O // Single Shift Select of G3 Character Set // ( SS3 is 0x8f). This affects next character only. case 'O': break; // ESC n // Invoke the G2 Character Set as GL (LS2). case 'n': // this._terminal.setgLevel(2); break; // ESC o // Invoke the G3 Character Set as GL (LS3). case 'o': // this._terminal.setgLevel(3); break; // ESC | // Invoke the G3 Character Set as GR (LS3R). case '|': // this._terminal.setgLevel(3); break; // ESC } // Invoke the G2 Character Set as GR (LS2R). case '}': // this._terminal.setgLevel(2); break; // ESC ~ // Invoke the G1 Character Set as GR (LS1R). case '~': // this._terminal.setgLevel(1); break; // ESC 7 Save Cursor (DECSC). case '7': Emit(TerminalCodeType.SaveCursor); _state = ParserState.Normal; break; // ESC 8 Restore Cursor (DECRC). case '8': Emit(TerminalCodeType.RestoreCursor); _state = ParserState.Normal; break; // ESC # 3 DEC line height/width case '#': _state = ParserState.Normal; // _position++; break; // ESC H Tab Set (HTS is 0x88). case 'H': Emit(TerminalCodeType.TabSet); _state = ParserState.Normal; break; // ESC = Application Keypad (DECKPAM). case '=': // this._terminal.log('Serial port requested application keypad.'); // this._terminal.applicationKeypad = true; // this._terminal.viewport.syncScrollArea(); _state = ParserState.Normal; break; // ESC > Normal Keypad (DECKPNM). case '>': // this._terminal.log('Switching back to normal keypad.'); // this._terminal.applicationKeypad = false; // this._terminal.viewport.syncScrollArea(); _state = ParserState.Normal; break; default: _state = ParserState.Normal; // _terminal.error('Unknown ESC control: %s.', ch); break; } } break; case ParserState.Charset: // if (ch in CHARSETS) // { // cs = CHARSETS[ch]; // if (ch === '/') // { // ISOLatin is actually /A // this.skipNextChar(); // } // } // else // { // cs = DEFAULT_CHARSET; // } // this._terminal.setgCharset(this._terminal.gcharset, cs); // this._terminal.gcharset = null; _state = ParserState.Normal; break; case ParserState.Osc: // OSC Ps ; Pt ST // OSC Ps ; Pt BEL // Set Text Parameters. if (ch == C0.ESC || ch == C0.BEL) { if (ch == C0.ESC) { _position++; } _params.Add(_currentParam); switch ((int)_params[0]) { case 0: case 1: case 2: if (_params.Count >= 1 && _params[1] != null) { Emit(new TerminalCode(TerminalCodeType.SetTitle, (string)_params[1])); } break; case 3: // set X property break; case 4: case 5: // change dynamic colors break; case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: // change dynamic ui colors break; case 46: // change log file break; case 50: // dynamic font break; case 51: // emacs shell break; case 52: // manipulate selection data break; case 104: case 105: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: // reset colors break; } _params.Clear(); _currentParam = 0; _state = ParserState.Normal; } else { if (_params.Count == 0) { if (ch >= '0' && ch <= '9') { _currentParam = ((int)_currentParam * 10) + ch - 48; } else if (ch == ';') { _params.Add(_currentParam); _currentParam = ""; } } else { _currentParam = (string)_currentParam + ch; } } break; case ParserState.CsiParam: if (!CsiParamStateHandler(ch)) { FinaliseParam(); _state = ParserState.Csi; goto case ParserState.Csi; } break; case ParserState.Csi: if (!CsiStateHandler(ch)) { throw new Exception($"Unknown CSI code: {ch}"); } _state = ParserState.Normal; _prefix = ""; _postfix = ""; break; case ParserState.Dcs: if (ch == C0.ESC || ch == C0.BEL) { if (ch == C0.ESC) { // _position++; } switch (_prefix) { // User-Defined Keys (DECUDK) case "": break; // Request Status String (DECRQSS). // test: echo -e '\eP$q"p\e\\' case "$q": { string pt = (string)_currentParam; bool valid = false; switch (pt) { // DECSCA case "\"q": pt = "0\"q"; break; // DECSCL case "\"p": pt = "61\"p"; break; // DECSTBM case "r": // pt = "" // + (this._terminal.scrollTop + 1) // + ";" // + (this._terminal.scrollBottom + 1) // + "r"; break; // SGR case "m": pt = "0m"; break; default: throw new Exception($"Unknown DCS Pt: {pt}."); pt = ""; break; } // this._terminal.send(C0.ESC + 'P' + +valid + '$r' + pt + C0.ESC + '\\'); break; } // Set Termcap/Terminfo Data (xterm, experimental). case "+p": break; // Request Termcap/Terminfo String (xterm, experimental) // Regular xterm does not even respond to this sequence. // This can cause a small glitch in vim. // test: echo -ne '\eP+q6b64\e\\' case "+q": { string pt = (string)_currentParam; bool valid = false; // this._terminal.send(C0.ESC + 'P' + +valid + '+r' + pt + C0.ESC + '\\'); break; } default: throw new Exception($"Unknown DCS prefix: {_prefix}"); break; } _currentParam = 0; _prefix = ""; _state = ParserState.Normal; } else if (_currentParam == null) { if (_prefix.Length == 0 && ch != '$' && ch != '+') { _currentParam = ch; } else if (_prefix.Length == 2) { _currentParam = ch; } else { _prefix += ch; } } else { _currentParam = (string)_currentParam + ch; } break; case ParserState.Ignore: // For PM and APC. if (ch == C0.ESC || ch == C0.BEL) { if (ch == C0.ESC) { _position++; } _state = ParserState.Normal; } break; } } FinialiseEmit(); return(_terminalCodes.ToArray()); }
public void Setup() { _data = new int[] { 100, 200, 300, 400 }; _arrayReader = new ArrayReader <int>(_data); }