Ejemplo n.º 1
0
        /// <inheritdoc />
        public T[] CreateValueArray(int length, T initialValue)
        {
            T[]  array;
            bool alreadyInitialised = false;
            bool initialIsDefault   = initialValue.Equals(default(T));

            if (!BufferSessions || (array = _InternalGetBufferedArray(length)) == null)
            {
                array = new T[length];
                alreadyInitialised = initialIsDefault;
            }

            if (BufferSessions)
            {
                _InternalAddToCurrentSession(array);
            }

            if (!alreadyInitialised)
            {
                if (initialIsDefault)
                {
                    Array.Clear(array, 0, array.Length);
                }
                else
                {
                    if (array.Length <= 8)
                    {
                        for (var i = 0; i < array.Length; i++)
                        {
                            array[i] = initialValue;
                        }
                    }
                    else
                    {
                        array[0] = initialValue;
                        array[1] = initialValue;
                        array[2] = initialValue;
                        array[3] = initialValue;
                        array[4] = initialValue;
                        array[5] = initialValue;
                        array[6] = initialValue;
                        array[7] = initialValue;

                        int arrayToFillHalfLength = array.Length / 2;
                        int copyLength;

                        for (copyLength = 8; copyLength < arrayToFillHalfLength; copyLength <<= 1)
                        {
                            Array.Copy(array, 0, array, copyLength, copyLength);
                        }

                        Array.Copy(array, 0, array, copyLength, array.Length - copyLength);
                    }
                }
            }

            OnValueArrayCreated(array, initialValue);

            return(array);
        }
    public static Mesh CreateMesh(GradationMaterial material, Vector2 drawSize, Color lightColor, Color darkColor)
    {
        var result = CreateMesh(material);

        if (material.keys.Any(x => x.color.a < 1.0f))
        {
            var cellSize    = new Vector2(32.0f / drawSize.x, 32.0f / drawSize.y);
            var checkerMesh = CreateCheckerMesh(new Rect(-1.0f, -1.0f, 2.0f, 2.0f), cellSize, Color.white, Color.gray);

            var vertices = new Vector3[result.vertices.Length + checkerMesh.vertices.Length];
            Array.Copy(checkerMesh.vertices, 0, vertices, 0, checkerMesh.vertices.Length);
            Array.Copy(result.vertices, 0, vertices, checkerMesh.vertices.Length, result.vertices.Length);

            var colors = new Color[result.colors.Length + checkerMesh.colors.Length];
            Array.Copy(checkerMesh.colors, 0, colors, 0, checkerMesh.colors.Length);
            Array.Copy(result.colors, 0, colors, checkerMesh.colors.Length, result.colors.Length);

            var indices = checkerMesh.GetIndices(0)
                          .Concat(result.GetIndices(0)
                                  .Select(x => x + checkerMesh.vertices.Length)
                                  )
                          .ToArray();

            result.Clear();
            result.vertices = vertices;
            result.colors   = colors;
            result.SetIndices(indices, MeshTopology.Triangles, 0);
        }
        return(result);
    }
Ejemplo n.º 3
0
        public void SizePrefixedBytesWorks()
        {
            var pw    = new PaddedWrapper();
            var data1 = new byte[10];
            var data2 = new byte[10];

            Array.Fill(data1, (byte)0xFF);
            Array.Fill(data2, (byte)0x11);

            var spb  = new SizePrefixedBytes();
            var spb2 = new SizePrefixedBytes();

            spb.data  = new byte[10 + sizeof(int)];
            spb2.data = new byte[10 + sizeof(int)];
            BitConverter.TryWriteBytes(spb.data, 10);
            BitConverter.TryWriteBytes(spb2.data, 10);
            Array.Copy(data1, 0, spb.data, sizeof(int), data1.Length);
            Array.Copy(data2, 0, spb2.data, sizeof(int), data1.Length);

            if (!pw.CanPackIn(spb2.data))
            {
                pw = pw.CopyToBigger(spb2.data.Length);
            }
            pw.initFrom(spb);
            pw.PackIn(spb2.data);
        }
Ejemplo n.º 4
0
        private void TestEmitPush2PublicKey()
        {
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitPush(new ContractParameter(ContractParameterType.PublicKey));
            byte[] tempArray = new byte[34];
            tempArray[0] = 0x21;
            Array.Copy(ECCurve.Secp256r1.G.EncodePoint(true), 0, tempArray, 1, 33);
            Assert.AreEqual(Encoding.Default.GetString(tempArray), Encoding.Default.GetString(sb.ToArray()));
        }
Ejemplo n.º 5
0
        private void TestEmitPush2PublicKey()
        {
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitPush(new ContractParameter(ContractParameterType.PublicKey));
            byte[] tempArray = new byte[35];
            tempArray[0] = (byte)OpCode.PUSHDATA1;
            tempArray[1] = 0x21;
            Array.Copy(ECCurve.Secp256r1.G.EncodePoint(true), 0, tempArray, 2, 33);
            CollectionAssert.AreEqual(tempArray, sb.ToArray());
        }
Ejemplo n.º 6
0
 public override int Read(byte[] dest, int timeoutMilliseconds)
 {
     lock (_readBufferLock)
     {
         int readAmt      = Math.Min(dest.Length, _readBuffer.Length);
         int numBytesRead = _connection.BulkTransfer(_readEndpoint, _readBuffer, readAmt, timeoutMilliseconds);
         if (numBytesRead < 0)
         {
             return(0);
         }
         Array.Copy(_readBuffer, 0, dest, 0, numBytesRead);
         return(numBytesRead);
     }
 }
Ejemplo n.º 7
0
    private byte[] GetStateData()
    {
        byte[] state = new byte[playerObjects.Count * (32 /*GUID*/ + 12 /*XYZ*/)];
        int    i     = 0;

        foreach (var player in playerObjects)
        {
            //Copy GUID Data
            Array.Copy(player.Key.ToByteArray(), 0, state, i * 44, 32);

            //Copy Position Data
            Vector3 pos     = player.Value.transform.position;
            byte[]  posData = NUUtilities.GetBytes(pos);
            Array.Copy(posData, 0, state, i * 44 + 32, 12);
        }
        return(state);
    }
Ejemplo n.º 8
0
        public override int Write(byte[] src, int timeoutMilliseconds)
        {
            int offset = 0;

            while (offset < src.Length)
            {
                int writeLength;
                int amtWritten;

                lock (_writeBufferLock)
                {
                    try
                    {
                        byte[] writeBuffer;

                        writeLength = Math.Min(src.Length - offset, _writeBuffer.Length);
                        if (offset == 0)
                        {
                            writeBuffer = src;
                        }
                        else
                        {
                            Array.Copy(src, offset, _writeBuffer, 0, writeLength);
                            writeBuffer = _writeBuffer;
                        }

                        amtWritten = _connection.BulkTransfer(_writeEndpoint, writeBuffer, writeLength, timeoutMilliseconds);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.ToString());
                        Debugger.Break();
                        throw;
                    }
                }

                if (amtWritten <= 0)
                {
                    throw new UsbSerialException(
                              $"Error writing {writeLength} bytes at offset {offset} length={src.Length}");
                }

                offset += amtWritten;
            }
            return(offset);
        }
    //Sorts from the least significant digit:
    // 272, 45, 75, 81, 501, 2, 24, 66 = out of order!
    // 2, 4, 5, 5, 1, 1, 2, 4, 6 = takes digit & sorts
    // 81, 501, 272, (0)2, 24, 45, 75, 66
    // 501, 02, 24, 45, 66, 272, 75, 81 = takes digit & sorts
    // 8, 0, 7, 0, 2, 4, 7, 6
    // 501, 02, 024, 045, 066, 272, 075, 081
    // [02, 024, 045, 066, 075, 081, 272, 501] = sorted!

    protected override IEnumerator Sort()
    {
        int nodeCount = nodes.Length; //how many nodes there are
        int i, j;

        Node[] temp = new Node[nodes.Length];

        //Bitshifting = moving between 1s, 10s and 0s
        //For = F O R
        //First Value
        //Operator (condition)
        //Rate
        for (int shift = 31; shift > -1; --shift)
        {
            //Reset j to 0
            j = 0;

            //Loop through whole array
            for (i = 0; i < nodeCount; ++i) //++i increments before loop, i++ increments after loop
            {
                //Determine if the bitshifted variable is above 0
                bool move = (nodes[i].Index << shift) >= 0;
                //Determining if there is an index that is above 0 - so move into next part of array

                //If shift equals 0
                if (shift == 0 ? !move : move)
                {
                    nodes[i - j] = nodes[i];
                }
                else
                {
                    temp[j++] = nodes[i];
                }
            }

            //Copy the data to the temp array
            Array.Copy(temp, 0, nodes, nodes.Length - j, j);

            // -- Visualisation -- //
            StartFrame(0, 1);
            yield return(null);

            EndFrame(0, 1);
            // -- End Visualisation -- //
        }
    }
Ejemplo n.º 10
0
        private static string GetBaseConversion(int value, char[] baseChars)
        {
            var i          = 32;
            var buffer     = new char[i];
            var targetBase = baseChars.Length;

            do
            {
                buffer[--i] = baseChars[value % targetBase];
                value       = value / targetBase;
            }while (value > 0);

            var result = new char[32 - i];

            Array.Copy(buffer, i, result, 0, 32 - i);

            return(new string(result));
        }
Ejemplo n.º 11
0
        public void TestEmitAppCall1()
        {
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitDynamicCall(UInt160.Zero, "AAAAA");
            byte[] tempArray = new byte[36];
            tempArray[0] = (byte)OpCode.NEWARRAY0;
            tempArray[1] = (byte)OpCode.PUSH15;                              //(byte)CallFlags.All;
            tempArray[2] = (byte)OpCode.PUSHDATA1;
            tempArray[3] = 5;                                                //operation.Length
            Array.Copy(Encoding.UTF8.GetBytes("AAAAA"), 0, tempArray, 4, 5); //operation.data
            tempArray[9]  = (byte)OpCode.PUSHDATA1;
            tempArray[10] = 0x14;                                            //scriptHash.Length
            Array.Copy(UInt160.Zero.ToArray(), 0, tempArray, 11, 20);        //operation.data
            uint api = ApplicationEngine.System_Contract_Call;

            tempArray[31] = (byte)OpCode.SYSCALL;
            Array.Copy(BitConverter.GetBytes(api), 0, tempArray, 32, 4);//api.data
            Assert.AreEqual(tempArray.ToHexString(), sb.ToArray().ToHexString());
        }
Ejemplo n.º 12
0
        public void TestEmitAppCall1()
        {
            //format:(byte)0x00+(byte)OpCode.NEWARRAY+(string)operation+(Uint160)scriptHash+(uint)InteropService.System_Contract_Call
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitAppCall(UInt160.Zero, "AAAAA");
            byte[] tempArray = new byte[34];
            tempArray[0] = 0x00;                                             //0
            tempArray[1] = 0xC5;                                             //OpCode.NEWARRAY
            tempArray[2] = 5;                                                //operation.Length
            Array.Copy(Encoding.UTF8.GetBytes("AAAAA"), 0, tempArray, 3, 5); //operation.data
            tempArray[8] = 0x14;                                             //scriptHash.Length
            Array.Copy(UInt160.Zero.ToArray(), 0, tempArray, 9, 20);         //operation.data
            uint api = InteropService.System_Contract_Call;

            tempArray[29] = 0x68;                                        //OpCode.SYSCALL
            Array.Copy(BitConverter.GetBytes(api), 0, tempArray, 30, 4); //api.data
            byte[] resultArray = sb.ToArray();
            Assert.AreEqual(Encoding.Default.GetString(tempArray), Encoding.Default.GetString(resultArray));
        }
Ejemplo n.º 13
0
        public void TestEmitAppCall1()
        {
            //format:(byte)0x10+(byte)OpCode.NEWARRAY+(string)operation+(Uint160)scriptHash+(uint)InteropService.System_Contract_Call
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitAppCall(UInt160.Zero, "AAAAA");
            byte[] tempArray = new byte[36];
            tempArray[0] = (byte)OpCode.PUSH0;
            tempArray[1] = (byte)OpCode.NEWARRAY;
            tempArray[2] = (byte)OpCode.PUSHDATA1;
            tempArray[3] = 5;                                                //operation.Length
            Array.Copy(Encoding.UTF8.GetBytes("AAAAA"), 0, tempArray, 4, 5); //operation.data
            tempArray[9]  = (byte)OpCode.PUSHDATA1;
            tempArray[10] = 0x14;                                            //scriptHash.Length
            Array.Copy(UInt160.Zero.ToArray(), 0, tempArray, 11, 20);        //operation.data
            uint api = InteropService.Contract.Call;

            tempArray[31] = (byte)OpCode.SYSCALL;
            Array.Copy(BitConverter.GetBytes(api), 0, tempArray, 32, 4);//api.data
            CollectionAssert.AreEqual(tempArray, sb.ToArray());
        }
Ejemplo n.º 14
0
        public void TestEmitAppCall3()
        {
            //format:(object[])args+(byte)OpCode.PACK+(string)operation+(Uint160)scriptHash+(uint)InteropService.System_Contract_Call
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitAppCall(UInt160.Zero, "AAAAA", true);
            byte[] tempArray = new byte[35];
            tempArray[0] = 0x51;                                             //arg
            tempArray[1] = 0x51;                                             //args.Length
            tempArray[2] = 0xC1;                                             //OpCode.PACK
            tempArray[3] = 0x05;                                             //operation.Length
            Array.Copy(Encoding.UTF8.GetBytes("AAAAA"), 0, tempArray, 4, 5); //operation.data
            tempArray[9] = 0x14;                                             //scriptHash.Length
            Array.Copy(UInt160.Zero.ToArray(), 0, tempArray, 10, 20);        //operation.data
            uint api = InteropService.System_Contract_Call;

            tempArray[30] = 0x68;                                        //OpCode.SYSCALL
            Array.Copy(BitConverter.GetBytes(api), 0, tempArray, 31, 4); //api.data
            byte[] resultArray = sb.ToArray();
            Assert.AreEqual(Encoding.Default.GetString(tempArray), Encoding.Default.GetString(resultArray));
        }
Ejemplo n.º 15
0
        public void TestEmitAppCall2()
        {
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitDynamicCall(UInt160.Zero, "AAAAA", new ContractParameter[] { new ContractParameter(ContractParameterType.Integer) });
            byte[] tempArray = new byte[38];
            tempArray[0] = (byte)OpCode.PUSH0;
            tempArray[1] = (byte)OpCode.PUSH1;
            tempArray[2] = (byte)OpCode.PACK;
            tempArray[3] = (byte)OpCode.PUSH15;                              //(byte)CallFlags.All;
            tempArray[4] = (byte)OpCode.PUSHDATA1;
            tempArray[5] = 0x05;                                             //operation.Length
            Array.Copy(Encoding.UTF8.GetBytes("AAAAA"), 0, tempArray, 6, 5); //operation.data
            tempArray[11] = (byte)OpCode.PUSHDATA1;
            tempArray[12] = 0x14;                                            //scriptHash.Length
            Array.Copy(UInt160.Zero.ToArray(), 0, tempArray, 13, 20);        //operation.data
            uint api = ApplicationEngine.System_Contract_Call;

            tempArray[33] = (byte)OpCode.SYSCALL;
            Array.Copy(BitConverter.GetBytes(api), 0, tempArray, 34, 4);//api.data
            Assert.AreEqual(tempArray.ToHexString(), sb.ToArray().ToHexString());
        }
Ejemplo n.º 16
0
        public void TestEmitAppCall3()
        {
            //format:(object[])args+(byte)OpCode.PACK+(string)operation+(Uint160)scriptHash+(uint)InteropService.System_Contract_Call
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitAppCall(UInt160.Zero, "AAAAA", true);
            byte[] tempArray = new byte[37];
            tempArray[0] = (byte)OpCode.PUSH1; //arg
            tempArray[1] = (byte)OpCode.PUSH1; //args.Length
            tempArray[2] = (byte)OpCode.PACK;
            tempArray[3] = (byte)OpCode.PUSHDATA1;
            tempArray[4] = 0x05;                                             //operation.Length
            Array.Copy(Encoding.UTF8.GetBytes("AAAAA"), 0, tempArray, 5, 5); //operation.data
            tempArray[10] = (byte)OpCode.PUSHDATA1;
            tempArray[11] = 0x14;                                            //scriptHash.Length
            Array.Copy(UInt160.Zero.ToArray(), 0, tempArray, 12, 20);        //operation.data
            uint api = InteropService.Contract.Call;

            tempArray[32] = (byte)OpCode.SYSCALL;
            Array.Copy(BitConverter.GetBytes(api), 0, tempArray, 33, 4);//api.data
            CollectionAssert.AreEqual(tempArray, sb.ToArray());
        }
Ejemplo n.º 17
0
        public void TestEmitAppCall2()
        {
            //format:(ContractParameter[])ContractParameter+(byte)OpCode.PACK+(string)operation+(Uint160)scriptHash+(uint)InteropService.System_Contract_Call
            ScriptBuilder sb = new ScriptBuilder();

            sb.EmitAppCall(UInt160.Zero, ContractParameterType.Any, "AAAAA", new ContractParameter[] { new ContractParameter(ContractParameterType.Integer) });
            byte[] tempArray = new byte[38];
            tempArray[0] = (byte)OpCode.PUSH0;
            tempArray[1] = (byte)OpCode.PUSH1;
            tempArray[2] = (byte)OpCode.PACK;
            tempArray[3] = (byte)OpCode.PUSHDATA1;
            tempArray[4] = 0x05;                                             //operation.Length
            Array.Copy(Encoding.UTF8.GetBytes("AAAAA"), 0, tempArray, 5, 5); //operation.data
            tempArray[10] = (byte)OpCode.PUSH0;
            tempArray[11] = (byte)OpCode.PUSHDATA1;
            tempArray[12] = 0x14;                                     //scriptHash.Length
            Array.Copy(UInt160.Zero.ToArray(), 0, tempArray, 13, 20); //operation.data
            uint api = ApplicationEngine.System_Contract_Call;

            tempArray[33] = (byte)OpCode.SYSCALL;
            Array.Copy(BitConverter.GetBytes(api), 0, tempArray, 34, 4);//api.data
            CollectionAssert.AreEqual(tempArray, sb.ToArray());
        }
Ejemplo n.º 18
0
    protected override IEnumerator Sort()
    {
        int nodeCount = nodes.Length;
        int i, j;

        Node[] temp = new Node[nodes.Length];

        for (int shift = 31; shift > -1; --shift)
        {
            // Reset j to zero
            j = 0;

            // Loop through the whole array
            for (i = 0; i < nodeCount; ++i)
            {
                // Determine if the bit shifted variable is above 0
                bool move = (nodes[i].Index << shift) >= 0;
                if (shift == 0 ? !move : move)
                {
                    nodes[i - j] = nodes[i];
                }
                else
                {
                    temp[j++] = nodes[i];
                }
            }

            // Copy the data to the temp array
            Array.Copy(temp, 0, nodes, nodes.Length - j, j);

            // Stupid visualisation
            StartFrame(0, 1);
            yield return(null);

            EndFrame(0, 1);
        }
    }
    private static Mesh CreateCheckerMesh(Rect r, Vector2 cellSize, Color lightColor, Color darkColor)
    {
        var result = new Mesh();

        var vertexXCount = Mathf.CeilToInt(r.width / cellSize.x) + 1;
        var vertexYCount = Mathf.CeilToInt(r.height / cellSize.y) + 1;
        var vertexCount  = vertexXCount * vertexYCount;

        var vertices = new Vector3[vertexCount + 4];

        vertices[0] = new Vector3(r.xMin, r.yMax, 0.0f);
        vertices[1] = new Vector3(r.xMax, r.yMax, 0.0f);
        vertices[2] = new Vector3(r.xMin, r.yMin, 0.0f);
        vertices[3] = new Vector3(r.xMax, r.yMin, 0.0f);
        for (int y = 0, yMax = vertexYCount; y < yMax; ++y)
        {
            for (int x = 0, xMax = vertexXCount; x < xMax; ++x)
            {
                var positon = new Vector3(r.xMax, r.yMin, 0.0f);
                if (x < (vertexXCount - 1))
                {
                    positon.x = cellSize.x * x + r.xMin;
                }
                if (y < (vertexYCount - 1))
                {
                    positon.y = r.yMax - cellSize.y * y;
                }
                var index = x + y * vertexXCount + 4;
                vertices[index] = positon;
            }
        }
        result.vertices = vertices;

        var colors = new Color[vertexCount + 4];

        for (int i = 0, iMax = 4; i < iMax; ++i)
        {
            colors[i] = lightColor;
        }
        for (int i = 4, iMax = vertexCount + 4; i < iMax; ++i)
        {
            colors[i] = darkColor;
        }
        result.colors = colors;

        var indices = new int[((vertexXCount - 1) * (vertexYCount - 1) / 2 + 1) * 6];

        {
            Array.Copy(new[] { 0, 1, 2, 1, 3, 2 }, indices, 6);
            var index = 6;
            for (int y = 0, yMax = vertexYCount - 1; y < yMax; ++y)
            {
                for (int x = 0, xMax = vertexXCount - 1; x < xMax; ++x)
                {
                    if (((x + y) & 0x01) == 1)
                    {
                        var upperLeftIndex  = x + y * vertexXCount + 4;
                        var upperRightIndex = upperLeftIndex + 1;
                        var lowerRightIndex = upperRightIndex + vertexXCount;
                        var lowerLeftIndex  = upperLeftIndex + vertexXCount;
                        indices[index++] = upperLeftIndex;
                        indices[index++] = upperRightIndex;
                        indices[index++] = lowerLeftIndex;
                        indices[index++] = upperRightIndex;
                        indices[index++] = lowerRightIndex;
                        indices[index++] = lowerLeftIndex;
                    }
                }
            }
        }
        result.SetIndices(indices, MeshTopology.Triangles, 0);

        return(result);
    }
Ejemplo n.º 20
0
        internal void CopyTo(byte[] array)
        {
            var store = (BitGeneStore)Values.Store();

            Array.Copy(store.Array, 0, array, 0, store.Array.Length);
        }
Ejemplo n.º 21
0
		/// <summary>
		/// 将指定的值复制到指定的缓冲字节组中
		/// </summary>
		/// <param name="value">要写入的值</param>
		/// <param name="buffer">目标缓冲数组</param>
		/// <param name="offset">数据偏移</param>
		/// <exception cref="System.ArgumentException">目标数组为空或者目标长度不足以写入值</exception>
		public static void CopyToBuffer(this double value, byte[] buffer, int offset)
		{
			if (buffer == null || buffer.Length < offset + 8) throw new ArgumentException();
			Array.Copy(BitConverter.GetBytes(value), 0, buffer, offset, 8);
		}
Ejemplo n.º 22
0
Archivo: For.cs Proyecto: lulzzz/sito
        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            Parser.Build(ref _initializer, 1, variables, codeContext, message, stats, opts);
            var initAsVds = _initializer as VariableDefinition;

            if ((opts & Options.SuppressUselessStatementsElimination) == 0)
            {
                if (initAsVds != null && initAsVds._initializers.Length == 1 && initAsVds.Kind == VariableKind.FunctionScope)
                {
                    _initializer = initAsVds._initializers[0];
                }
            }

            Parser.Build(ref _condition, 2, variables, codeContext | CodeContext.InLoop | CodeContext.InExpression, message, stats, opts);

            if (_post != null)
            {
                Parser.Build(ref _post, 1, variables, codeContext | CodeContext.Conditional | CodeContext.InLoop | CodeContext.InExpression, message, stats, opts);
                if (_post == null && message != null)
                {
                    message(MessageLevel.Warning, Position, Length, "Last expression of for-loop was removed. Maybe, it's a mistake.");
                }
            }

            Parser.Build(ref _body, Math.Max(1, expressionDepth), variables, codeContext | CodeContext.Conditional | CodeContext.InLoop, message, stats, opts);

            if (initAsVds != null && initAsVds.Kind != VariableKind.FunctionScope && initAsVds._variables.Any(x => x.captured))
            {
                var bodyAsCodeBlock = _body as CodeBlock;
                if (bodyAsCodeBlock != null)
                {
                    var newLines = new CodeNode[bodyAsCodeBlock._lines.Length + 1];
                    Array.Copy(bodyAsCodeBlock._lines, newLines, bodyAsCodeBlock._lines.Length);
                    newLines[newLines.Length - 1] = new PerIterationScopeInitializer(initAsVds._variables);
                    bodyAsCodeBlock._lines        = newLines;
                }
                else
                {
                    _body = bodyAsCodeBlock = new CodeBlock(new[] { _body, new PerIterationScopeInitializer(initAsVds._variables) });
                }

                bodyAsCodeBlock._suppressScopeIsolation = SuppressScopeIsolationMode.DoNotSuppress;

                for (var i = 0; i < initAsVds._variables.Length; i++)
                {
                    if (initAsVds._variables[i].captured)
                    {
                        initAsVds._variables[i].DefinitionScopeLevel = -1;
                    }
                }
            }

            if (_condition == null)
            {
                _condition = new Constant(Boolean.True);
            }
            else if ((_condition is Expression) &&
                     (_condition as Expression).ContextIndependent &&
                     !(bool)_condition.Evaluate(null))
            {
                _this = _initializer;
                return(false);
            }
            else if (_body == null || _body is Empty)
            {
                VariableReference variable = null;
                Constant          limit    = null;
                if (_condition is Less)
                {
                    variable = (_condition as Less).LeftOperand as VariableReference;
                    limit    = (_condition as Less).RightOperand as Constant;
                }
                else if (_condition is More)
                {
                    variable = (_condition as More).RightOperand as VariableReference;
                    limit    = (_condition as More).LeftOperand as Constant;
                }
                else if (_condition is NotEqual)
                {
                    variable = (_condition as Less).RightOperand as VariableReference;
                    limit    = (_condition as Less).LeftOperand as Constant;
                    if (variable == null && limit == null)
                    {
                        variable = (_condition as Less).LeftOperand as VariableReference;
                        limit    = (_condition as Less).RightOperand as Constant;
                    }
                }
                if (variable != null &&
                    limit != null &&
                    _post is Increment &&
                    ((_post as Increment).LeftOperand as VariableReference)._descriptor == variable._descriptor)
                {
                    if (variable.ScopeLevel >= 0 && variable._descriptor.DefinitionScopeLevel >= 0)
                    {
                        if ((_initializer as Assignment)?.LeftOperand is Variable && ((_initializer as Assignment).LeftOperand as Variable)._descriptor == variable._descriptor)
                        {
                            var value = (_initializer as Assignment).RightOperand;
                            if (value is Constant)
                            {
                                var vvalue = value.Evaluate(null);
                                var lvalue = limit.Evaluate(null);
                                if ((vvalue._valueType == JSValueType.Integer ||
                                     vvalue._valueType == JSValueType.Boolean ||
                                     vvalue._valueType == JSValueType.Double) &&
                                    (lvalue._valueType == JSValueType.Integer ||
                                     lvalue._valueType == JSValueType.Boolean ||
                                     lvalue._valueType == JSValueType.Double))
                                {
                                    _post.Eliminated      = true;
                                    _condition.Eliminated = true;

                                    if (!Less.Check(vvalue, lvalue))
                                    {
                                        _this = _initializer;
                                        return(false);
                                    }

                                    _this = new CodeBlock(new[] { _initializer, new Assignment(variable, limit) });
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 23
0
        internal static object CallDynamicInvokeMethod(
            object thisPtr,
            IntPtr methodToCall,
            object thisPtrDynamicInvokeMethod,
            IntPtr dynamicInvokeHelperMethod,
            IntPtr dynamicInvokeHelperGenericDictionary,
            object targetMethodOrDelegate,
            object[] parameters,
            BinderBundle binderBundle,
            bool wrapInTargetInvocationException,
            bool invokeMethodHelperIsThisCall = true,
            bool methodToCallIsThisCall       = true)
        {
            // This assert is needed because we've double-purposed "targetMethodOrDelegate" (which is actually a MethodBase anytime a custom binder is used)
            // as a way of obtaining the true parameter type which we need to pass to Binder.ChangeType(). (The type normally passed to DynamicInvokeParamHelperCore
            // isn't always the exact type (byref stripped off, enums converted to int, etc.)
            Debug.Assert(!(binderBundle != null && !(targetMethodOrDelegate is MethodBase)), "The only callers that can pass a custom binder are those servicing MethodBase.Invoke() apis.");

            bool          parametersNeedCopyBack = false;
            ArgSetupState argSetupState          = default(ArgSetupState);

            // Capture state of thread static invoke helper statics
            object[]     parametersOld = s_parameters;
            object[]     nullableCopyBackObjectsOld = s_nullableCopyBackObjects;
            int          curIndexOld = s_curIndex;
            object       targetMethodOrDelegateOld = s_targetMethodOrDelegate;
            BinderBundle binderBundleOld           = s_binderBundle;

            s_binderBundle = binderBundle;
            object[] customBinderProvidedParametersOld = s_customBinderProvidedParameters;
            s_customBinderProvidedParameters = null;

            try
            {
                // If the passed in array is not an actual object[] instance, we need to copy it over to an actual object[]
                // instance so that the rest of the code can safely create managed object references to individual elements.
                if (parameters != null && EETypePtr.EETypePtrOf <object[]>() != parameters.EETypePtr)
                {
                    s_parameters = new object[parameters.Length];
                    Array.Copy(parameters, s_parameters, parameters.Length);
                    parametersNeedCopyBack = true;
                }
                else
                {
                    s_parameters = parameters;
                }

                s_nullableCopyBackObjects = null;
                s_curIndex = 0;
                s_targetMethodOrDelegate = targetMethodOrDelegate;

                try
                {
                    object result = null;
                    if (invokeMethodHelperIsThisCall)
                    {
                        Debug.Assert(methodToCallIsThisCall == true);
                        result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, thisPtrDynamicInvokeMethod, thisPtr, methodToCall, ref argSetupState);
                        System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
                    }
                    else
                    {
                        if (dynamicInvokeHelperGenericDictionary != IntPtr.Zero)
                        {
                            result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, dynamicInvokeHelperGenericDictionary, thisPtr, methodToCall, ref argSetupState, methodToCallIsThisCall);
                            DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
                        }
                        else
                        {
                            result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, thisPtr, methodToCall, ref argSetupState, methodToCallIsThisCall);
                            DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
                        }
                    }

                    return(result);
                }
                catch (Exception e) when(wrapInTargetInvocationException && argSetupState.fComplete)
                {
                    throw new TargetInvocationException(e);
                }
                finally
                {
                    if (parametersNeedCopyBack)
                    {
                        Array.Copy(s_parameters, parameters, parameters.Length);
                    }

                    if (argSetupState.fComplete)
                    {
                        // Nullable objects can't take advantage of the ability to update the boxed value on the heap directly, so perform
                        // an update of the parameters array now.
                        if (argSetupState.nullableCopyBackObjects != null)
                        {
                            for (int i = 0; i < argSetupState.nullableCopyBackObjects.Length; i++)
                            {
                                if (argSetupState.nullableCopyBackObjects[i] != null)
                                {
                                    parameters[i] = DynamicInvokeBoxIntoNonNullable(argSetupState.nullableCopyBackObjects[i]);
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                // Restore state of thread static helper statics
                s_parameters = parametersOld;
                s_nullableCopyBackObjects = nullableCopyBackObjectsOld;
                s_curIndex = curIndexOld;
                s_targetMethodOrDelegate         = targetMethodOrDelegateOld;
                s_binderBundle                   = binderBundleOld;
                s_customBinderProvidedParameters = customBinderProvidedParametersOld;
            }
        }
Ejemplo n.º 24
0
        // This method is passed a set of methods and must choose the best
        // fit.  The methods all have the same number of arguments and the object
        // array args.  On exit, this method will choice the best fit method
        // and coerce the args to match that method.  By match, we mean all primitive
        // arguments are exact matchs and all object arguments are exact or subclasses
        // of the target.  If the target OR is an interface, the object must implement
        // that interface.  There are a couple of exceptions
        // thrown when a method cannot be returned.  If no method matchs the args and
        // ArgumentException is thrown.  If multiple methods match the args then 
        // an AmbiguousMatchException is thrown.
        // 
        // The most specific match will be selected.  
        // 
        public sealed override MethodBase BindToMethod(
            BindingFlags bindingAttr, MethodBase[] match, ref object?[] args,
            ParameterModifier[]? modifiers, CultureInfo? cultureInfo, string[]? names, out object? state)
        {
            if (match == null || match.Length == 0)
                throw new ArgumentException(SR.Arg_EmptyArray, nameof(match));

            MethodBase?[] candidates = (MethodBase[])match.Clone();

            int i;
            int j;

            state = null;

#region Map named parameters to candidate parameter positions
            // We are creating an paramOrder array to act as a mapping
            //  between the order of the args and the actual order of the
            //  parameters in the method.  This order may differ because
            //  named parameters (names) may change the order.  If names
            //  is not provided, then we assume the default mapping (0,1,...)
            int[][] paramOrder = new int[candidates.Length][];

            for (i = 0; i < candidates.Length; i++)
            {
                ParameterInfo[] par = candidates[i]!.GetParametersNoCopy();

                // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted
                paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length];

                if (names == null)
                {
                    // Default mapping
                    for (j = 0; j < args.Length; j++)
                        paramOrder[i][j] = j;
                }
                else
                {
                    // Named parameters, reorder the mapping.  If CreateParamOrder fails, it means that the method
                    // doesn't have a name that matchs one of the named parameters so we don't consider it any further.
                    if (!CreateParamOrder(paramOrder[i], par, names))
                        candidates[i] = null;
                }
            }
#endregion

            Type[] paramArrayTypes = new Type[candidates.Length];

            Type[] argTypes = new Type[args.Length];

#region Cache the type of the provided arguments
            // object that contain a null are treated as if they were typeless (but match either object 
            // references or value classes).  We mark this condition by placing a null in the argTypes array.
            for (i = 0; i < args.Length; i++)
            {
                if (args[i] != null)
                {
                    argTypes[i] = args[i]!.GetType(); //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388
                }
            }
#endregion


            // Find the method that matches...
            int CurIdx = 0;
            bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0);

            Type? paramArrayType;

#region Filter methods by parameter count and type
            for (i = 0; i < candidates.Length; i++)
            {
                paramArrayType = null;

                // If we have named parameters then we may have a hole in the candidates array.
                if (candidates[i] == null)
                    continue;

                // Validate the parameters.
                ParameterInfo[] par = candidates[i]!.GetParametersNoCopy(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644

#region Match method by parameter count
                if (par.Length == 0)
                {
#region No formal parameters
                    if (args.Length != 0)
                    {
                        if ((candidates[i]!.CallingConvention & CallingConventions.VarArgs) == 0) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
                            continue;
                    }

                    // This is a valid routine so we move it up the candidates list.
                    paramOrder[CurIdx] = paramOrder[i];
                    candidates[CurIdx++] = candidates[i];

                    continue;
#endregion
                }
                else if (par.Length > args.Length)
                {
#region Shortage of provided parameters
                    // If the number of parameters is greater than the number of args then 
                    // we are in the situation were we may be using default values.
                    for (j = args.Length; j < par.Length - 1; j++)
                    {
                        if (par[j].DefaultValue == System.DBNull.Value)
                            break;
                    }

                    if (j != par.Length - 1)
                        continue;

                    if (par[j].DefaultValue == System.DBNull.Value)
                    {
                        if (!par[j].ParameterType.IsArray)
                            continue;

                        if (!par[j].IsDefined(typeof(ParamArrayAttribute), true))
                            continue;

                        paramArrayType = par[j].ParameterType.GetElementType();
                    }
#endregion
                }
                else if (par.Length < args.Length)
                {
#region Excess provided parameters
                    // test for the ParamArray case
                    int lastArgPos = par.Length - 1;

                    if (!par[lastArgPos].ParameterType.IsArray)
                        continue;

                    if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true))
                        continue;

                    if (paramOrder[i][lastArgPos] != lastArgPos)
                        continue;

                    paramArrayType = par[lastArgPos].ParameterType.GetElementType();
#endregion
                }
                else
                {
#region Test for paramArray, save paramArray type
                    int lastArgPos = par.Length - 1;

                    if (par[lastArgPos].ParameterType.IsArray
                        && par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true)
                        && paramOrder[i][lastArgPos] == lastArgPos)
                    {
                        if (!par[lastArgPos].ParameterType.IsAssignableFrom(argTypes[lastArgPos]))
                            paramArrayType = par[lastArgPos].ParameterType.GetElementType();
                    }
#endregion
                }
#endregion

                Type pCls;
                int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length;

#region Match method by parameter type
                for (j = 0; j < argsToCheck; j++)
                {
#region Classic argument coersion checks
                    // get the formal type
                    pCls = par[j].ParameterType;

                    if (pCls.IsByRef)
                        pCls = pCls.GetElementType()!;

                    // the type is the same
                    if (pCls == argTypes[paramOrder[i][j]])
                        continue;

                    // a default value is available
                    if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing)
                        continue;

                    // the argument was null, so it matches with everything
                    if (args[paramOrder[i][j]] == null)
                        continue;

                    // the type is Object, so it will match everything
                    if (pCls == typeof(object))
                        continue;

                    // now do a "classic" type check
                    if (pCls.IsPrimitive)
                    {
                        if (argTypes[paramOrder[i][j]] == null || !CanChangePrimitive(args[paramOrder[i][j]]?.GetType(), pCls))
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (argTypes[paramOrder[i][j]] == null)
                            continue;

                        if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]]))
                        {
                            if (argTypes[paramOrder[i][j]].IsCOMObject)
                            {
                                if (pCls.IsInstanceOfType(args[paramOrder[i][j]]))
                                    continue;
                            }
                            break;
                        }
                    }
#endregion
                }

                if (paramArrayType != null && j == par.Length - 1)
                {
#region Check that excess arguments can be placed in the param array
                    for (; j < args.Length; j++)
                    {
                        if (paramArrayType.IsPrimitive)
                        {
                            if (argTypes[j] == null || !CanChangePrimitive(args[j]?.GetType(), paramArrayType))
                                break;
                        }
                        else
                        {
                            if (argTypes[j] == null)
                                continue;

                            if (!paramArrayType.IsAssignableFrom(argTypes[j]))
                            {
                                if (argTypes[j].IsCOMObject)
                                {
                                    if (paramArrayType.IsInstanceOfType(args[j]))
                                        continue;
                                }

                                break;
                            }
                        }
                    }
#endregion
                }
#endregion

                if (j == args.Length)
                {
#region This is a valid routine so we move it up the candidates list
                    paramOrder[CurIdx] = paramOrder[i];
                    paramArrayTypes[CurIdx] = paramArrayType!;
                    candidates[CurIdx++] = candidates[i];
#endregion
                }
            }
#endregion

            // If we didn't find a method 
            if (CurIdx == 0)
                throw new MissingMethodException(SR.MissingMember);

            if (CurIdx == 1)
            {
#region Found only one method
                if (names != null)
                {
                    state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null);
                    ReorderParams(paramOrder[0], args);
                }

                // If the parameters and the args are not the same length or there is a paramArray
                //  then we need to create a argument array.
                ParameterInfo[] parms = candidates[0]!.GetParametersNoCopy();

                if (parms.Length == args.Length)
                {
                    if (paramArrayTypes[0] != null)
                    {
                        object[] objs = new object[parms.Length];
                        int lastPos = parms.Length - 1;
                        Array.Copy(args, 0, objs, 0, lastPos);
                        objs[lastPos] = Array.CreateInstance(paramArrayTypes[0], 1);
                        ((Array)objs[lastPos]).SetValue(args[lastPos], 0);
                        args = objs;
                    }
                }
                else if (parms.Length > args.Length)
                {
                    object?[] objs = new object[parms.Length];

                    for (i = 0; i < args.Length; i++)
                        objs[i] = args[i];

                    for (; i < parms.Length - 1; i++)
                        objs[i] = parms[i].DefaultValue;

                    if (paramArrayTypes[0] != null)
                        objs[i] = Array.CreateInstance(paramArrayTypes[0], 0); // create an empty array for the 

                    else
                        objs[i] = parms[i].DefaultValue;

                    args = objs;
                }
                else
                {
                    if ((candidates[0]!.CallingConvention & CallingConventions.VarArgs) == 0)
                    {
                        object[] objs = new object[parms.Length];
                        int paramArrayPos = parms.Length - 1;
                        Array.Copy(args, 0, objs, 0, paramArrayPos);
                        objs[paramArrayPos] = Array.CreateInstance(paramArrayTypes[0], args.Length - paramArrayPos);
                        Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
                        args = objs;
                    }
                }
#endregion

                return candidates[0]!;
            }

            int currentMin = 0;
            bool ambig = false;
            for (i = 1; i < CurIdx; i++)
            {
#region Walk all of the methods looking the most specific method to invoke
                int newMin = FindMostSpecificMethod(candidates[currentMin]!, paramOrder[currentMin], paramArrayTypes[currentMin],
                                                    candidates[i]!, paramOrder[i], paramArrayTypes[i], argTypes, args);

                if (newMin == 0)
                {
                    ambig = true;
                }
                else if (newMin == 2)
                {
                    currentMin = i;
                    ambig = false;
                }
#endregion
            }

            if (ambig)
                throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);

            // Reorder (if needed)
            if (names != null)
            {
                state = new BinderState((int[])paramOrder[currentMin].Clone(), args.Length, paramArrayTypes[currentMin] != null);
                ReorderParams(paramOrder[currentMin], args);
            }

            // If the parameters and the args are not the same length or there is a paramArray
            //  then we need to create a argument array.
            ParameterInfo[] parameters = candidates[currentMin]!.GetParametersNoCopy();
            if (parameters.Length == args.Length)
            {
                if (paramArrayTypes[currentMin] != null)
                {
                    object[] objs = new object[parameters.Length];
                    int lastPos = parameters.Length - 1;
                    Array.Copy(args, 0, objs, 0, lastPos);
                    objs[lastPos] = Array.CreateInstance(paramArrayTypes[currentMin], 1);
                    ((Array)objs[lastPos]).SetValue(args[lastPos], 0);
                    args = objs;
                }
            }
            else if (parameters.Length > args.Length)
            {
                object?[] objs = new object[parameters.Length];

                for (i = 0; i < args.Length; i++)
                    objs[i] = args[i];

                for (; i < parameters.Length - 1; i++)
                    objs[i] = parameters[i].DefaultValue;

                if (paramArrayTypes[currentMin] != null)
                {
                    objs[i] = Array.CreateInstance(paramArrayTypes[currentMin], 0);
                }
                else
                {
                    objs[i] = parameters[i].DefaultValue;
                }

                args = objs;
            }
            else
            {
                if ((candidates[currentMin]!.CallingConvention & CallingConventions.VarArgs) == 0)
                {
                    object[] objs = new object[parameters.Length];
                    int paramArrayPos = parameters.Length - 1;
                    Array.Copy(args, 0, objs, 0, paramArrayPos);
                    objs[paramArrayPos] = Array.CreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos);
                    Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
                    args = objs;
                }
            }

            return candidates[currentMin]!;
        }
Ejemplo n.º 25
0
    public void getFullSpectrumThreaded()
    {
        try
        {
            // We only need to retain the samples for combined channels over the time domain
            float[] preProcessedSamples = new float[this.numTotalSamples];

            int   numProcessed           = 0;
            float combinedChannelAverage = 0f;
            for (int i = 0; i < multiChannelSamples.Length; i++)
            {
                combinedChannelAverage += multiChannelSamples[i];

                // Each time we have processed all channels samples for a point in time, we will store the average of the channels combined
                if ((i + 1) % this.numChannels == 0)
                {
                    preProcessedSamples[numProcessed] = combinedChannelAverage / this.numChannels;
                    numProcessed++;
                    combinedChannelAverage = 0f;
                }
            }

            Debug.Log("Combine Channels done");
            Debug.Log(preProcessedSamples.Length);

            // Once we have our audio sample data prepared, we can execute an FFT to return the spectrum data over the time domain
            int spectrumSampleSize = 1024;
            int iterations         = preProcessedSamples.Length / spectrumSampleSize;

            FFT fft = new FFT();
            fft.Initialize((System.UInt32)spectrumSampleSize);

            Debug.Log(string.Format("Processing {0} time domain samples for FFT", iterations));
            double[] sampleChunk = new double[spectrumSampleSize];
            for (int i = 0; i < iterations; i++)
            {
                // Grab the current 1024 chunk of audio sample data
                Array.Copy(preProcessedSamples, i * spectrumSampleSize, sampleChunk, 0, spectrumSampleSize);

                // Apply our chosen FFT Window
                double[] windowCoefs         = DSP.Window.Coefficients(DSP.Window.Type.Hanning, (uint)spectrumSampleSize);
                double[] scaledSpectrumChunk = DSP.Math.Multiply(sampleChunk, windowCoefs);
                double   scaleFactor         = DSP.Window.ScaleFactor.Signal(windowCoefs);

                // Perform the FFT and convert output (complex numbers) to Magnitude
                Complex[] fftSpectrum       = fft.Execute(scaledSpectrumChunk);
                double[]  scaledFFTSpectrum = DSPLib.DSP.ConvertComplex.ToMagnitude(fftSpectrum);
                scaledFFTSpectrum = DSP.Math.Multiply(scaledFFTSpectrum, scaleFactor);

                // These 1024 magnitude values correspond (roughly) to a single point in the audio timeline
                float curSongTime = getTimeFromIndex(i) * spectrumSampleSize;

                // Send our magnitude data off to our Spectral Flux Analyzer to be analyzed for peaks
                audPP.analyzeSpectrum(Array.ConvertAll(scaledFFTSpectrum, x => (float)x), curSongTime);
            }

            Debug.Log("Spectrum Analysis done");
            Debug.Log("Background Thread Completed");
            Debug.Log("Number of Points: " + audPP.spectralFluxSamples.Count);
            for (int i = 0; i < audPP.spectralFluxSamples.Count; i++)
            {
                if (audPP.spectralFluxSamples[i].time < 2)
                {
                    continue;
                }
                if (i % 20 == 0)
                {
                    times.Add(audPP.spectralFluxSamples[i].time);
                }
            }
            startSong = true;
        }
        catch (System.Exception e)
        {
            // Catch exceptions here since the background thread won't always surface the exception to the main thread
            Debug.Log(e.ToString());
        }
    }
Ejemplo n.º 26
0
 /// <summary>
 ///     <remark>2008-02-29 </remark>
 /// </summary>
 /// <param name="byteArray">The byte array.</param>
 /// <param name="offset">The offset.</param>
 /// <param name="length">The length.</param>
 public void Put(byte[] byteArray, int offset, int length)
 {
     byte[] temp = new byte[length];
     Array.Copy(byteArray, offset, temp, 0, length);
     Put(temp);
 }
Ejemplo n.º 27
0
        public static List <AdvertisementRecord> ParseScanRecord(Byte[] scanRecord)
        {
            List <AdvertisementRecord> records = new List <AdvertisementRecord>();

            if (scanRecord == null)
            {
                return(records);
            }

            Int32 index = 0;

            while (index < scanRecord.Length)
            {
                Byte length = scanRecord[index++];
                //Done once we run out of records
                // 1 byte for type and length-1 bytes for data
                if (length == 0)
                {
                    break;
                }

                Int32 type = scanRecord[index];
                //Done if our record isn't a valid type
                if (type == 0)
                {
                    break;
                }

                if (!Enum.IsDefined(typeof(AdvertisementRecordType), type))
                {
                    Trace.Message("Advertisment record type not defined: {0}", type);
                    break;
                }

                //data length is length -1 because type takes the first byte
                Byte[] data = new Byte[length - 1];
                Array.Copy(scanRecord, index + 1, data, 0, length - 1);

                // don't forget that data is little endian so reverse
                // Supplement to Bluetooth Core Specification 1
                // NOTE: all relevant devices are already little endian, so this is not necessary for any type except UUIDs
                //var record = new AdvertisementRecord((AdvertisementRecordType)type, data.Reverse().ToArray());

                switch ((AdvertisementRecordType)type)
                {
                case AdvertisementRecordType.ServiceDataUuid32Bit:
                case AdvertisementRecordType.SsUuids128Bit:
                case AdvertisementRecordType.SsUuids16Bit:
                case AdvertisementRecordType.SsUuids32Bit:
                case AdvertisementRecordType.UuidCom32Bit:
                case AdvertisementRecordType.UuidsComplete128Bit:
                case AdvertisementRecordType.UuidsComplete16Bit:
                case AdvertisementRecordType.UuidsIncomple16Bit:
                case AdvertisementRecordType.UuidsIncomplete128Bit:
                    Array.Reverse(data);
                    break;
                }

                AdvertisementRecord record = new AdvertisementRecord((AdvertisementRecordType)type, data);

                Trace.Message(record.ToString());

                records.Add(record);

                //Advance
                index += length;
            }

            return(records);
        }
Ejemplo n.º 28
0
        private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit)
        {
            Contract.Requires(param != null);

            // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
            // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
            // that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
            // For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
            // For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
            // class inherits from and return the respective ParameterInfo attributes

            List <Type> disAllowMultiple = new List <Type>();

            Object[] objAttr;

            if (type == null)
            {
                type = typeof(Attribute);
            }

            objAttr = param.GetCustomAttributes(type, false);

            for (int i = 0; i < objAttr.Length; i++)
            {
                Type objType = objAttr[i].GetType();
                AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
                if (attribUsage.AllowMultiple == false)
                {
                    disAllowMultiple.Add(objType);
                }
            }

            // Get all the attributes that have Attribute as the base class
            Attribute[] ret = null;
            if (objAttr.Length == 0)
            {
                ret = CreateAttributeArrayHelper(type, 0);
            }
            else
            {
                ret = (Attribute[])objAttr;
            }

            if (param.Member.DeclaringType == null) // This is an interface so we are done.
            {
                return(ret);
            }

            if (!inherit)
            {
                return(ret);
            }

            ParameterInfo baseParam = GetParentDefinition(param);

            while (baseParam != null)
            {
                objAttr = baseParam.GetCustomAttributes(type, false);

                int count = 0;
                for (int i = 0; i < objAttr.Length; i++)
                {
                    Type objType = objAttr[i].GetType();
                    AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);

                    if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false))
                    {
                        if (attribUsage.AllowMultiple == false)
                        {
                            disAllowMultiple.Add(objType);
                        }
                        count++;
                    }
                    else
                    {
                        objAttr[i] = null;
                    }
                }

                // Get all the attributes that have Attribute as the base class
                Attribute[] attributes = CreateAttributeArrayHelper(type, count);

                count = 0;
                for (int i = 0; i < objAttr.Length; i++)
                {
                    if (objAttr[i] != null)
                    {
                        attributes[count] = (Attribute)objAttr[i];
                        count++;
                    }
                }

                Attribute[] temp = ret;
                ret = CreateAttributeArrayHelper(type, temp.Length + count);
                Array.Copy(temp, ret, temp.Length);

                int offset = temp.Length;

                for (int i = 0; i < attributes.Length; i++)
                {
                    ret[offset + i] = attributes[i];
                }

                baseParam = GetParentDefinition(baseParam);
            }

            return(ret);
        }
Ejemplo n.º 29
0
        private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type? type, bool inherit)
        {
            Debug.Assert(param != null);

            // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
            // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
            // that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
            // For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
            // For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
            // class inherits from and return the respective ParameterInfo attributes

            List<Type> disAllowMultiple = new List<Type>();
            object?[] objAttr;

            if (type == null)
                type = typeof(Attribute);

            objAttr = param.GetCustomAttributes(type, false);

            for (int i = 0; i < objAttr.Length; i++)
            {
                Type objType = objAttr[i]!.GetType();
                AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
                if (attribUsage.AllowMultiple == false)
                    disAllowMultiple.Add(objType);
            }

            // Get all the attributes that have Attribute as the base class
            Attribute[] ret;
            if (objAttr.Length == 0)
                ret = CreateAttributeArrayHelper(type, 0);
            else
                ret = (Attribute[])objAttr;

            if (param.Member.DeclaringType is null) // This is an interface so we are done.
                return ret;

            if (!inherit)
                return ret;

            ParameterInfo? baseParam = GetParentDefinition(param);

            while (baseParam != null)
            {
                objAttr = baseParam.GetCustomAttributes(type, false);

                int count = 0;
                for (int i = 0; i < objAttr.Length; i++)
                {
                    Type objType = objAttr[i]!.GetType();
                    AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);

                    if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false))
                    {
                        if (attribUsage.AllowMultiple == false)
                            disAllowMultiple.Add(objType);
                        count++;
                    }
                    else
                        objAttr[i] = null;
                }

                // Get all the attributes that have Attribute as the base class
                Attribute[] attributes = CreateAttributeArrayHelper(type, count);

                count = 0;
                for (int i = 0; i < objAttr.Length; i++)
                {
                    if (objAttr[i] != null)
                    {
                        attributes[count] = (Attribute)objAttr[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644)
                        count++;
                    }
                }

                Attribute[] temp = ret;
                ret = CreateAttributeArrayHelper(type, temp.Length + count);
                Array.Copy(temp, 0, ret, 0, temp.Length);

                int offset = temp.Length;

                for (int i = 0; i < attributes.Length; i++)
                    ret[offset + i] = attributes[i];

                baseParam = GetParentDefinition(baseParam);
            }

            return ret;
        }
Ejemplo n.º 30
0
 public DynamicArray(T[] src)
 {
     count = src.Length;
     array = new T[count];
     Arr.Copy(src, array, count);
 }