Exemplo n.º 1
0
        /// <summary>
        /// A helper method for creating an object that represents a total count
        /// of objects that the cmdlet would return without paging
        /// (this can be more than the size of the page specified in the <see cref="First"/> cmdlet parameter).
        /// </summary>
        /// <param name="totalCount">a total count of objects that the cmdlet would return without paging</param>
        /// <param name="accuracy">
        /// accuracy of the <paramref name="totalCount"/> parameter.  
        /// <c>1.0</c> means 100% accurate;
        /// <c>0.0</c> means that total count is unknown;
        /// anything in-between means that total count is estimated
        /// </param>
        /// <returns>An object that represents a total count of objects that the cmdlet would return without paging</returns>
        public PSObject NewTotalCount(UInt64 totalCount, double accuracy)
        {
            PSObject result = new PSObject(totalCount);

            string toStringMethodBody = string.Format(
                CultureInfo.CurrentCulture,
                @"
                    $totalCount = $this.PSObject.BaseObject
                    switch ($this.Accuracy) {{
                        {{ $_ -ge 1.0 }} {{ '{0}' -f $totalCount }}
                        {{ $_ -le 0.0 }} {{ '{1}' -f $totalCount }}
                        default          {{ '{2}' -f $totalCount }}
                    }}
                ",
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportAccurateTotalCountTemplate),
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportUnknownTotalCountTemplate),
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportEstimatedTotalCountTemplate));
            PSScriptMethod toStringMethod = new PSScriptMethod("ToString", ScriptBlock.Create(toStringMethodBody));
            result.Members.Add(toStringMethod);

            accuracy = Math.Max(0.0, Math.Min(1.0, accuracy));
            PSNoteProperty statusProperty = new PSNoteProperty("Accuracy", accuracy);
            result.Members.Add(statusProperty);

            return result;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Converts a <see cref="UInt64"/> to big endian notation.
        /// </summary>
        /// <param name="input">The <see cref="UInt64"/> to convert.</param>
        /// <returns>The converted <see cref="UInt64"/>.</returns>
        public static UInt64 BigEndian(UInt64 input)
        {
            if (!BitConverter.IsLittleEndian)
                return input;

            return Swap(input);
        }
Exemplo n.º 3
0
 public static int[] generate(UInt64 n, UInt64 start)
 {
     int[] ReturnArray = new int[n];
     IntPtr d = primesieve_generate_n_primes(n, start, 2);
     Marshal.Copy(d, ReturnArray, (int)0, (int)n);
     return ReturnArray;
 }
Exemplo n.º 4
0
		public override void Write(UInt64 val)
		{
			val = Utilities.SwapBytes(val);
			base.Write(val);

			if (AutoFlush) Flush();
		}
Exemplo n.º 5
0
        public static byte[] UInt64(UInt64 i, Endianness e = Endianness.Machine)
        {
            byte[] bytes = BitConverter.GetBytes(i);

            if (NeedsFlipping(e)) Array.Reverse(bytes);

            return bytes;
        }
Exemplo n.º 6
0
		public static UInt64 SwapBytes(UInt64 x)
		{
			// swap adjacent 32-bit blocks
			x = (x >> 32) | (x << 32);
			// swap adjacent 16-bit blocks
			x = ((x & 0xFFFF0000FFFF0000) >> 16) | ((x & 0x0000FFFF0000FFFF) << 16);
			// swap adjacent 8-bit blocks
			return ((x & 0xFF00FF00FF00FF00) >> 8) | ((x & 0x00FF00FF00FF00FF) << 8);
		}
Exemplo n.º 7
0
        public User(string login, UInt64 passwordHash, Int32 ID)
        {
            pLogin = login;
            pPassword = new Password(passwordHash);
            pID = ID;

            pStaticAddressess = new List<UnifiedAddress>();
            pDynamicAddressess = new List<UnifiedAddress>();
            pCurrentAddress = null;
        }
Exemplo n.º 8
0
 public int GetHammingDistance(UInt64 firstValue, UInt64 secondValue)
 {
     UInt64 hammingBits = firstValue ^ secondValue;
       int hammingValue = 0;
       for (int i = 0; i < HashSize; i++) {
     if (IsBitSet(hammingBits, i)) {
       hammingValue += 1;
     }
       }
       return hammingValue;
 }
Exemplo n.º 9
0
        /// <summary>
        /// 将指定的无符号整数转换为字节数组
        /// </summary>
        /// <param name="value">无符号整数</param>
        /// <param name="length">需要的元素个数</param>
        /// <param name="maxLength">该无符号整数最多能转换的元素个数</param>
        /// <returns></returns>
        private static byte[] GetByteArray(UInt64 value, byte length, byte maxLength)
        {
            if (length < 1 || length > maxLength)
            {
                length = maxLength;
            }

            byte[] byteArray = new byte[length];

            for (int i = 0; i < length; i++)
            {
                byteArray[i] = (byte)(value >> ((length - 1 - i) * 8));
            }

            return byteArray;
        }
Exemplo n.º 10
0
        private bool checkMessage(Socket socket, byte[] buffer, int msgSize)
        {
            long currentTime = SystemUtils.currentTimeMillis();

            if ((buffer [2] & 1) == 0)               /* I format frame */

            {
                if (firstIMessageReceived == false)
                {
                    firstIMessageReceived = true;
                    lastConfirmationTime  = currentTime;                    /* start timeout T2 */
                }

                if (msgSize < 7)
                {
                    DebugLog("I msg too small!");
                    return(false);
                }

                int frameSendSequenceNumber = ((buffer [3] * 0x100) + (buffer [2] & 0xfe)) / 2;
                int frameRecvSequenceNumber = ((buffer [5] * 0x100) + (buffer [4] & 0xfe)) / 2;

                DebugLog("Received I frame: N(S) = " + frameSendSequenceNumber + " N(R) = " + frameRecvSequenceNumber);

                /* check the receive sequence number N(R) - connection will be closed on an unexpected value */
                if (frameSendSequenceNumber != receiveSequenceNumber)
                {
                    DebugLog("Sequence error: Close connection!");
                    return(false);
                }

                if (CheckSequenceNumber(frameRecvSequenceNumber) == false)
                {
                    return(false);
                }

                receiveSequenceNumber = (receiveSequenceNumber + 1) % 32768;
                unconfirmedReceivedIMessages++;

                try {
                    ASDU asdu = new ASDU(parameters, buffer, 6, msgSize);

                    if (asduReceivedHandler != null)
                    {
                        asduReceivedHandler(asduReceivedHandlerParameter, asdu);
                    }
                }
                catch (ASDUParsingException e) {
                    DebugLog("ASDU parsing failed: " + e.Message);
                    return(false);
                }
            }
            else if ((buffer [2] & 0x03) == 0x01)                 /* S format frame */
            {
                int seqNo = (buffer[4] + buffer[5] * 0x100) / 2;

                DebugLog("Recv S(" + seqNo + ") (own sendcounter = " + sendSequenceNumber + ")");

                if (CheckSequenceNumber(seqNo) == false)
                {
                    return(false);
                }
            }
            else if ((buffer [2] & 0x03) == 0x03)                 /* U format frame */

            {
                uMessageTimeout = 0;

                if (buffer [2] == 0x43)                   // Check for TESTFR_ACT message
                {
                    statistics.RcvdTestFrActCounter++;
                    DebugLog("RCVD TESTFR_ACT");
                    DebugLog("SEND TESTFR_CON");
                    socket.Send(TESTFR_CON_MSG);
                    statistics.SentMsgCounter++;
                    if (sentMessageHandler != null)
                    {
                        sentMessageHandler(sentMessageHandlerParameter, TESTFR_CON_MSG, 6);
                    }
                }
                else if (buffer [2] == 0x83)     /* TESTFR_CON */
                {
                    DebugLog("RCVD TESTFR_CON");
                    statistics.RcvdTestFrConCounter++;
                    outStandingTestFRConMessages = 0;
                }
                else if (buffer [2] == 0x07)                     /* STARTDT ACT */
                {
                    DebugLog("RCVD STARTDT_ACT");
                    socket.Send(STARTDT_CON_MSG);
                    statistics.SentMsgCounter++;
                    if (sentMessageHandler != null)
                    {
                        sentMessageHandler(sentMessageHandlerParameter, STARTDT_CON_MSG, 6);
                    }
                }
                else if (buffer [2] == 0x0b)     /* STARTDT_CON */
                {
                    DebugLog("RCVD STARTDT_CON");

                    if (connectionHandler != null)
                    {
                        connectionHandler(connectionHandlerParameter, ConnectionEvent.STARTDT_CON_RECEIVED);
                    }
                }
                else if (buffer [2] == 0x23)                     /* STOPDT_CON */
                {
                    DebugLog("RCVD STOPDT_CON");

                    if (connectionHandler != null)
                    {
                        connectionHandler(connectionHandlerParameter, ConnectionEvent.STOPDT_CON_RECEIVED);
                    }
                }
            }
            else
            {
                DebugLog("Unknown message type");
                return(false);
            }

            ResetT3Timeout();

            return(true);
        }
Exemplo n.º 11
0
 private static BigInteger GenerateRandomBigIntegerGreaterThan(UInt64 value, Random random)
 {
     return (GenerateRandomPositiveBigInteger(random) + value) + 1;
 }
Exemplo n.º 12
0
        public NCA3(BinaryReader br)
        {
            RSASig_0 = br.ReadBytes(0x100);
            RSASig_1 = br.ReadBytes(0x100);
            if ((Magic = new string(br.ReadChars(4))) != "NCA3")
            {
                throw new ApplicationException("Magic NCA3 not found!");
            }
            IsGameCard  = br.ReadBoolean();
            ContentType = br.ReadByte();
            CryptoType  = br.ReadByte();
            KaekIndex   = br.ReadByte();
            Size        = br.ReadUInt64();
            TitleID     = br.ReadUInt64();
            br.ReadBytes(4); //padding?
            SDKVersion  = br.ReadUInt32();
            CryptoType2 = br.ReadByte();
            br.ReadBytes(15); //padding?
            RightsID = br.ReadBytes(0x10);

            List <SectionTableEntry> SectionTableEntries = new List <SectionTableEntry>();

            for (var i = 0; i < 4; i++)
            {
                SectionTableEntries.Add(new SectionTableEntry(br));
            }

            HashTable = new List <byte[]>();
            for (var i = 0; i < 4; i++)
            {
                HashTable.Add(br.ReadBytes(0x20));
            }

            var keyblob = AES.DecryptKeyArea(br, KaekIndex, CryptoType) ?? new byte[0x10];

            KeyArea = new List <byte[]>();
            for (var i = 0; i < 4; i++)
            {
                byte[] temp = new byte[0x10];
                Array.Copy(keyblob, (i * 0x10), temp, 0, 0x10);
                KeyArea.Add(temp);
            }

            //Section header block
            br.BaseStream.Position = 0x400;
            br.ReadBytes(3); //???
            var fsType     = br.ReadByte();
            var cryptoType = br.ReadByte();

            br.ReadBytes(3);

            //dont really need this stuff. Might finish later for completion
            UInt64 offsetRel      = 0;
            UInt64 pfs0ActualSize = 0;

            if (fsType == 2)
            {
                //PFS0 superblock
                br.ReadBytes(0x38);
                offsetRel      = br.ReadUInt64();
                pfs0ActualSize = br.ReadUInt64();
            }
            else if (fsType == 3)
            {
                //ROMFS superblock
                br.ReadBytes(0xE8);
            }

            br.BaseStream.Position = SectionTableEntries[0].MediaOffset;

            int contSize = (int)(SectionTableEntries[0].MediaEndOffset - SectionTableEntries[0].MediaOffset);

            byte[] iv = new byte[0x10];
            Array.Copy(BitConverter.GetBytes(SectionTableEntries[0].MediaOffset >> 4), 0, iv, 0, 4);
            Array.Reverse(iv);
            var dec_cont = AES.CTRMode(br, contSize, KeyArea[cryptoType == 3 ? 2 : 0], iv);

            dec_cont.ReadBytes((int)offsetRel);
            pfs0 = new PFS0(dec_cont);
        }
Exemplo n.º 13
0
 private void ValidateResult(Vector128 <UInt64> result, [CallerMemberName] string method = "")
 {
     UInt64[] resultElements = new UInt64[ElementCount];
     Unsafe.WriteUnaligned(ref Unsafe.As <UInt64, byte>(ref resultElements[0]), result);
     ValidateResult(resultElements, method);
 }
Exemplo n.º 14
0
 public static string ToString(UInt64 value)
 {
     return value.ToString(null, NumberFormatInfo.InvariantInfo);
 }
Exemplo n.º 15
0
 private void ResetT3Timeout()
 {
     nextT3Timeout = (UInt64)SystemUtils.currentTimeMillis() + (UInt64)(parameters.T3 * 1000);
 }
Exemplo n.º 16
0
    public override void RecvProcess()
    {
        UInt64 Sub      = TCPClient.Instance.GetProtocol() & (UInt64)FULL_CODE.SUB;
        UInt64 Protocol = TCPClient.Instance.GetProtocol() & (UInt64)FULL_CODE.PROTOCOL;

        Debug.Log(string.Format("temp = {0:x}", Protocol));

        int    result;
        string msg;
        int    num;

        RecvBuffer buffer;

        buffer = TCPClient.Instance.UnPackingData();
        UnPackingData(buffer, out result);

        switch ((LOBBY_RESULT)result)
        {
        case LOBBY_RESULT.NOT_READY:
            UnPackingData(buffer, out msg);
            print(msg);
            break;

        case LOBBY_RESULT.READY:
            UnPackingData(buffer, out num, out msg);
            Static_Data.m_number    = num;
            Static_Data.m_FixNumber = num;
            print(num);

            var CharacterManager = GameObject.Find("CharacterSelect").GetComponent <CharacterSelectManager>();
            CharacterManager.MatchComplete();
            break;

        case LOBBY_RESULT.UPDATE_NUMBER:
            UnPackingData(buffer, out num, 0);

            print("Update Number : " + num);
            Static_Data.m_number = num;

            var ohter = GameObject.Find("Other");
            ohter.SetActive(false);
            break;

        case LOBBY_RESULT.VALVE_COMPLETE:
            var Player = GameObject.Find("GameManager").GetComponent <GameManager>().ClientPlayer.GetComponent <PlayerControl>();
            try
            {
                Player.SteamSceneStart();
            }
            catch
            {
                print("Not Player Control");
            }
            break;
        }

        /*
         * switch ((STATE)Sub)
         * {
         *  case STATE.ENTER:
         *      buffer = TCPClient.Instance.UnPackingData();
         *      UnPackingData(buffer, out result);
         *
         *      switch ((LOBBY_RESULT)result)
         *      {
         *          case LOBBY_RESULT.NOT_READY:
         *              UnPackingData(buffer, out msg);
         *              print(msg);
         *              break;
         *
         *          case LOBBY_RESULT.READY:
         *              UnPackingData(buffer, out num, out msg);
         *              print(msg);
         *              Static_Data.m_number = num;
         *
         *              var CharacterManager = GameObject.Find("CharacterSelect").GetComponent<CharacterSelectManager>();
         *              CharacterManager.MatchComplete();
         *              break;
         *
         *          case LOBBY_RESULT.UPDATE_NUMBER:
         *              UnPackingData(buffer, out num, 0);
         *
         *              print("Update Number : " + num);
         *              Static_Data.m_number = num;
         *              break;
         *      }
         *      break;
         *
         *  default:
         *      buffer = TCPClient.Instance.UnPackingData();
         *      UnPackingData(buffer, out result);
         *
         *      switch ((LOBBY_RESULT)result)
         *      {
         *          case LOBBY_RESULT.UPDATE_NUMBER:
         *              UnPackingData(buffer, out num, 0);
         *
         *              print("Update Number : " + num);
         *              Static_Data.m_number = num;
         *              break;
         *      }
         *      break;
         * }
         */
    }
Exemplo n.º 17
0
        public void Seek(UInt64 position)
        {
            if (position > Int64.MaxValue)
            {
                ArgumentException ex = new ArgumentException(SR.IO_CannotSeekBeyondInt64MaxValue);
                ex.SetErrorCode(HResults.E_INVALIDARG);
                throw ex;
            }

            // Commented due to a reported CCRewrite bug. Should uncomment when fixed:
            //Contract.EndContractBlock();

            Stream str = EnsureNotDisposed();
            Int64 pos = unchecked((Int64)position);

            Debug.Assert(str != null);
            Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not.");
            Debug.Assert(0 <= pos && pos <= Int64.MaxValue, "Unexpected pos=" + pos + ".");

            str.Seek(pos, SeekOrigin.Begin);
        }
Exemplo n.º 18
0
    public void Match_Leave()
    {
        UInt64 Protocol = (UInt64)CLASS_STATE.LOBBY_STATE | (UInt64)STATE.LEAVE;

        TCPClient.Instance.PackingData(Protocol);
    }
Exemplo n.º 19
0
    public void ValveComplete()
    {
        UInt64 Protocol = (UInt64)CLASS_STATE.LOBBY_STATE | (UInt64)STATE.VALVE;

        TCPClient.Instance.PackingData(Protocol, PackingData(Static_Data.m_number));
    }
Exemplo n.º 20
0
    public void Match_Message()
    {
        UInt64 Protocol = (UInt64)CLASS_STATE.LOBBY_STATE | (UInt64)STATE.ENTER;

        TCPClient.Instance.PackingData(Protocol);
    }
Exemplo n.º 21
0
        static object CheckForLiterals(string value, Type t)
        {
            object ret = FromNode(value);

            if (ret != null)
            {
                return(ret);
            }

            if (InstanceOf(t, typeof(byte)))
            {
                return(Byte.Parse(value, CultureInfo.InvariantCulture));
            }
            if (InstanceOf(t, typeof(sbyte)))
            {
                return(SByte.Parse(value, CultureInfo.InvariantCulture));
            }

            if (InstanceOf(t, typeof(short)))
            {
                return(Int16.Parse(value, CultureInfo.InvariantCulture));
            }
            if (InstanceOf(t, typeof(ushort)))
            {
                return(UInt16.Parse(value, CultureInfo.InvariantCulture));
            }

            if (InstanceOf(t, typeof(int)))
            {
                return(Int32.Parse(value, CultureInfo.InvariantCulture));
            }
            if (InstanceOf(t, typeof(uint)))
            {
                return(UInt32.Parse(value, CultureInfo.InvariantCulture));
            }

            if (InstanceOf(t, typeof(long)))
            {
                return(Int64.Parse(value, CultureInfo.InvariantCulture));
            }
            if (InstanceOf(t, typeof(ulong)))
            {
                return(UInt64.Parse(value, CultureInfo.InvariantCulture));
            }

            if (InstanceOf(t, typeof(float)))
            {
                return(Single.Parse(value, CultureInfo.InvariantCulture));
            }
            if (InstanceOf(t, typeof(double)))
            {
                return(Double.Parse(value, CultureInfo.InvariantCulture));
            }
            if (InstanceOf(t, typeof(decimal)))
            {
                return(Decimal.Parse(value, CultureInfo.InvariantCulture));
            }

            if (InstanceOf(t, typeof(DateTime)))
            {
                return(DateTime.Parse(value, CultureInfo.InvariantCulture));
            }
            if (InstanceOf(t, typeof(TimeSpan)))
            {
                return(TimeSpan.Parse(value, CultureInfo.InvariantCulture));
            }

            if (InstanceOf(t, typeof(string)))
            {
                return(value);
            }

            if (InstanceOf(t, typeof(Delegate)))
            {
                return(CreateDelegate(value));
            }

            return(null);
        }
Exemplo n.º 22
0
 public InMovieAs(string asCharater, UInt64 oid)
 {
     character = asCharater;
     movie     = new Movie(oid);
 }
Exemplo n.º 23
0
 private static void VerifyUInt64ExplicitCastFromBigInteger(UInt64 value, BigInteger bigInteger)
 {
     Assert.Equal(value, (UInt64)bigInteger);
 }
Exemplo n.º 24
0
        private static object ConvertNumericLiteral(ErrorContext errCtx, string numericString)
        {
            var k = numericString.IndexOfAny(_numberSuffixes);

            if (-1 != k)
            {
                var suffix     = numericString.Substring(k).ToUpperInvariant();
                var numberPart = numericString.Substring(0, numericString.Length - suffix.Length);
                switch (suffix)
                {
                case "U":
                {
                    UInt32 value;
                    if (!UInt32.TryParse(numberPart, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "unsigned int");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "L":
                {
                    long value;
                    if (!Int64.TryParse(numberPart, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "long");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "UL":
                case "LU":
                {
                    UInt64 value;
                    if (!UInt64.TryParse(numberPart, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "unsigned long");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "F":
                {
                    Single value;
                    if (!Single.TryParse(numberPart, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "float");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "M":
                {
                    Decimal value;
                    if (
                        !Decimal.TryParse(
                            numberPart, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture,
                            out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "decimal");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "D":
                {
                    Double value;
                    if (!Double.TryParse(numberPart, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "double");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;
                }
            }

            //
            // If hit this point, try default conversion
            //
            return(DefaultNumericConversion(numericString, errCtx));
        }
Exemplo n.º 25
0
 /// <summary>
 /// Push long
 /// </summary>
 /// <param name="value"></param>
 public void PushIntoStack(UInt64 value)
 {
     PushObjIntoQueue(value);
 }
Exemplo n.º 26
0
 private static Category GetCategory(UInt64 typeCodeData)
 {
     return((Category)((typeCodeData >> 56) & 0xFF));
 }
Exemplo n.º 27
0
        private static bool VerifyCtorByteArray(byte[] value, UInt64 expectedValue)
        {
            bool ret = true;
            BigInteger bigInteger;

            bigInteger = new BigInteger(value);

            if (!bigInteger.Equals(expectedValue))
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to UInt64 {1}", bigInteger, expectedValue);
                ret = false;
            }
            if (!expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("UInt64.ToString() and BigInteger.ToString()");
                ret = false;
            }
            if (expectedValue != (UInt64)bigInteger)
            {
                Console.WriteLine("BigInteger casted to a UInt64");
                ret = false;
            }

            if (expectedValue != UInt64.MaxValue)
            {
                if ((UInt64)(expectedValue + 1) != (UInt64)(bigInteger + 1))
                {
                    Console.WriteLine("BigInteger added to 1");
                    ret = false;
                }
            }

            if (expectedValue != UInt64.MinValue)
            {
                if ((UInt64)(expectedValue - 1) != (UInt64)(bigInteger - 1))
                {
                    Console.WriteLine("BigInteger subtracted by 1");
                    ret = false;
                }
            }

            Assert.True(VerifyCtorByteArray(value), " Verification Failed");
            return ret;
        }
Exemplo n.º 28
0
 /// <summary>
 /// Constructor of the <see cref="Device"/> object. Don't use this constructor, use <see cref="Platform.GetDevices(DeviceType)"/> method instead.
 /// </summary>
 /// <param name="handle"></param>
 /// <param name="platform"></param>
 public Device(IntPtr handle, Platform platform)
 {
     Handle = handle;
     Platform = platform;
     AddressBits = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_ADDRESS_BITS);
     Available = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_AVAILABLE) != 0;
     CompilerAvailable = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_COMPILER_AVAILABLE) != 0;
     DoubleFloatingPointConfig = (FloatingPointConfig)GetInfo<UInt32>(DeviceInfo.CL_DEVICE_DOUBLE_FP_CONFIG);
     LittleEndian = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_ENDIAN_LITTLE) != 0;
     ErrorCorrectionSupport = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_ERROR_CORRECTION_SUPPORT) != 0;
     ExecutionCapabilities = (ExecutionCapabilities)GetInfo<UInt32>(DeviceInfo.CL_DEVICE_EXECUTION_CAPABILITIES);
     Extensions = GetStringInfo(DeviceInfo.CL_DEVICE_EXTENSIONS);
     GlobalMemoryCachelineSize = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE);
     GlobalMemoryCacheSize = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_GLOBAL_MEM_CACHE_SIZE);
     GlobalMemoryCacheType = (MemoryCacheType)GetInfo<UInt32>(DeviceInfo.CL_DEVICE_GLOBAL_MEM_CACHE_TYPE);
     GlobalMemorySize = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_GLOBAL_MEM_SIZE);
     Image2DMaxHeight = 0;
     if (AddressBits == 32)
         Image2DMaxHeight = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_IMAGE2D_MAX_HEIGHT);
     else if (AddressBits == 64)
         Image2DMaxHeight = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_IMAGE2D_MAX_HEIGHT);
     Image2DMaxWidth = 0;
     if (AddressBits == 32)
         Image2DMaxWidth = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_IMAGE2D_MAX_WIDTH);
     else if (AddressBits == 64)
         Image2DMaxWidth = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_IMAGE2D_MAX_WIDTH);
     Image3DMaxDepth = 0;
     if (AddressBits == 32)
         Image3DMaxDepth = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_IMAGE3D_MAX_DEPTH);
     else if (AddressBits == 64)
         Image3DMaxDepth = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_IMAGE3D_MAX_DEPTH);
     Image3DMaxHeight = 0;
     if (AddressBits == 32)
         Image3DMaxHeight = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_IMAGE3D_MAX_HEIGHT);
     else if (AddressBits == 64)
         Image3DMaxHeight = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_IMAGE3D_MAX_HEIGHT);
     Image3DMaxWidth = 0;
     if (AddressBits == 32)
         Image3DMaxWidth = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_IMAGE3D_MAX_WIDTH);
     else if (AddressBits == 64)
         Image3DMaxWidth = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_IMAGE3D_MAX_WIDTH);
     ImageSupport = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_IMAGE_SUPPORT) != 0;
     LocalMemorySize = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_LOCAL_MEM_SIZE);
     LocalMemoryType = (LocalMemoryType)GetInfo<UInt32>(DeviceInfo.CL_DEVICE_LOCAL_MEM_TYPE);
     MaxClockFrequency = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_CLOCK_FREQUENCY);
     MaxComputeUnits = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_COMPUTE_UNITS);
     MaxConstantArguments = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_CONSTANT_ARGS);
     MaxConstantBufferSize = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE);
     MaxMemoryAllocationSize = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_MAX_MEM_ALLOC_SIZE);
     MaxParameterSize = 0;
     if (AddressBits == 32)
         MaxParameterSize = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_PARAMETER_SIZE);
     else if (AddressBits == 64)
         MaxParameterSize = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_MAX_PARAMETER_SIZE);
     MaxReadImageArguments = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_READ_IMAGE_ARGS);
     MaxSamplers = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_SAMPLERS);
     MaxWorkGroupSize = 0;
     if (AddressBits == 32)
         MaxWorkGroupSize = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_WORK_GROUP_SIZE);
     else if (AddressBits == 64)
         MaxWorkGroupSize = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_MAX_WORK_GROUP_SIZE);
     MaxWorkItemDimensions = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS);
     MaxWorkItemSizes = new UInt64[0];
     if (AddressBits == 32)
     {
         UInt32[] sizes = GetArrayInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_WORK_ITEM_SIZES);
         MaxWorkItemSizes = new UInt64[MaxWorkItemDimensions];
         for (int i = 0; i < MaxWorkItemSizes.Length; i++)
             MaxWorkItemSizes[i] = sizes[i];
     }
     else if (AddressBits == 64)
     {
         UInt64[] sizes = GetArrayInfo<UInt64>(DeviceInfo.CL_DEVICE_MAX_WORK_ITEM_SIZES);
         MaxWorkItemSizes = new UInt64[MaxWorkItemDimensions];
         for (int i = 0; i < MaxWorkItemSizes.Length; i++)
             MaxWorkItemSizes[i] = sizes[i];
     }
     MaxWriteImageArguments = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MAX_WRITE_IMAGE_ARGS);
     MemoryBaseAddressAlignment = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MEM_BASE_ADDR_ALIGN);
     MinDataTypeAlignmentSize = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE);
     Name = GetStringInfo(DeviceInfo.CL_DEVICE_NAME);
     PreferredVectorWidthChar = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR);
     PreferredVectorWidthDouble = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE);
     PreferredVectorWidthFloat = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT);
     PreferredVectorWidthInt = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT);
     PreferredVectorWidthLong = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG);
     PreferredVectorWidthShort = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT);
     PreferredVectorWidthHalf = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF);
     Profile = GetStringInfo(DeviceInfo.CL_DEVICE_PROFILE);
     ProfilingTimerResolution = 0;
     if (AddressBits == 32)
         ProfilingTimerResolution = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_PROFILING_TIMER_RESOLUTION);
     else if (AddressBits == 64)
         ProfilingTimerResolution = GetInfo<UInt64>(DeviceInfo.CL_DEVICE_PROFILING_TIMER_RESOLUTION);
     QueueProperties = (CommandQueueProperties)GetInfo<UInt32>(DeviceInfo.CL_DEVICE_QUEUE_PROPERTIES);
     SingleFloatingPointConfig = (FloatingPointConfig)GetInfo<UInt32>(DeviceInfo.CL_DEVICE_SINGLE_FP_CONFIG);
     Type = (DeviceType)GetInfo<UInt32>(DeviceInfo.CL_DEVICE_TYPE);
     Vendor = GetStringInfo(DeviceInfo.CL_DEVICE_VENDOR);
     VendorID = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_VENDOR_ID);
     Version = GetStringInfo(DeviceInfo.CL_DEVICE_VERSION);
     DriverVersion = GetStringInfo(DeviceInfo.CL_DRIVER_VERSION);
     HostUnifiedMemory = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_HOST_UNIFIED_MEMORY) != 0;
     NativeVectorWidthChar = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR);
     NativeVectorWidthDouble = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE);
     NativeVectorWidthFloat = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT);
     NativeVectorWidthInt = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_NATIVE_VECTOR_WIDTH_INT);
     NativeVectorWidthLong = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG);
     NativeVectorWidthShort = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT);
     NativeVectorWidthHalf = GetInfo<UInt32>(DeviceInfo.CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF);
     OpenCLCVersion = GetStringInfo(DeviceInfo.CL_DEVICE_OPENCL_C_VERSION);
 }
Exemplo n.º 29
0
 public static string ToString(UInt64 value)
 {
     return value.ToString();
 }  
Exemplo n.º 30
0
 public static extern void kth_core_hash_list_nth_out(IntPtr list, UInt64 n, ref hash_t out_hash);
Exemplo n.º 31
0
 public static extern int FreeModel(UInt64 model);
Exemplo n.º 32
0
 internal static unsafe IntPtr ConvertUInt64ByrefToPtr(ref UInt64 value) {
     fixed (UInt64 *x = &value) {
         AssertByrefPointsToStack(new IntPtr(x));
         return new IntPtr(x);
     }
 }
Exemplo n.º 33
0
        private object ConvertStringToValue(string value, Type destinationType, ConversionOptions options)
        {
            /* Enum      */ if (destinationType.IsEnum && value != null)
            {
                return(Enum.Parse(destinationType, value));
            }
            /* Enum?     */             //TODO nullable enum
            /* Guid      */ if (destinationType == typeof(Guid))
            {
                return(value == null ? Guid.Empty : Guid.Parse(value));
            }
            /* Guid?     */ if (destinationType == typeof(Guid?    ))
            {
                return(string.IsNullOrWhiteSpace(value) ? (Guid?)null : (Guid.Parse(value)));
            }
            /* TimeSpan  */ if (destinationType == typeof(TimeSpan))
            {
                return(TimeSpan.Parse(value, options.Culture));
            }
            /* TimeSpan? */ if (destinationType == typeof(TimeSpan?))
            {
                return(string.IsNullOrEmpty(value) ? (TimeSpan?)null : TimeSpan.Parse(value, options.Culture));
            }

            switch (Type.GetTypeCode(destinationType))
            {
            case TypeCode.Empty: return(null);

            case TypeCode.Byte: return(Byte.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.SByte: return(SByte.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.Int16: return(Int16.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.Int32: return(Int32.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.Int64: return(Int64.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.UInt16: return(UInt16.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.UInt32: return(UInt32.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.UInt64: return(UInt64.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.Single: return(StringToSingle(value, options));

            case TypeCode.Double: return(StringToDouble(value, options));

            case TypeCode.Boolean: return(StringToBool(value, value, options));

            case TypeCode.String: return((String )value);

            case TypeCode.Decimal: return(Decimal.Parse(value, options.UseHex ? NumberStyles.AllowHexSpecifier : NumberStyles.Integer, options.Culture));

            case TypeCode.Char: return(Char.Parse(value));

            case TypeCode.DateTime: return(DateTime.Parse(value, options.Culture));

            case TypeCode.DBNull:
//				case TypeCode.Object:
//					if (targetType == typeof (CanError)) return new CanError((UInt16)ConvertStringToValue(value, typeof (UInt16), useHex));
//					else throw new InvalidCastException();
            default:
                throw new InvalidCastException();
            }
        }
Exemplo n.º 34
0
 public void reqRemoveRole(UInt64 dbid)
 {
     KBEngine.Event.fireIn("reqRemoveRole", new object[] { dbid });
 }
Exemplo n.º 35
0
        private void Receive_ZC_Data(byte[] ZCData)
        {
            using (MemoryStream receStreamZC = new MemoryStream(ZCData))
                using (BinaryReader reader = new BinaryReader(receStreamZC))
                {
                    ZC_Count += 1;
                    UInt16 ZCCycle             = reader.ReadUInt16();
                    UInt16 ZCPackageType       = reader.ReadUInt16();
                    byte   ZCSendID            = reader.ReadByte();
                    byte   ZCReceiveID         = reader.ReadByte();
                    UInt16 ZCDataLength        = reader.ReadUInt16();
                    UInt16 ZCNID_ZC            = reader.ReadUInt16();
                    UInt16 ZCNID_Train         = reader.ReadUInt16();
                    byte   ZCInfoType          = reader.ReadByte();
                    byte   ZCStopEnsure        = reader.ReadByte();
                    UInt64 ZCNID_DataBase      = reader.ReadUInt64();
                    UInt16 ZCNID_ARButton      = reader.ReadUInt16();
                    byte   ZCQ_ARButtonStatus  = reader.ReadByte();
                    UInt16 ZCNID_LoginZCNext   = reader.ReadUInt16();
                    byte   ZCN_Length          = reader.ReadByte();
                    byte   MAEndType           = reader.ReadByte();
                    byte   headSectionOrSwitch = reader.ReadByte();
                    headID = reader.ReadByte();
                    UInt32 ZCD_D_MAHeadOff = reader.ReadUInt32();
                    byte   ZCQ_MAHeadDir   = reader.ReadByte();
                    tailSectionOrSwitch = reader.ReadByte(); //1是直轨,2是道岔
                    tailID   = reader.ReadByte();            //MA终点的ID
                    MAEndOff = reader.ReadUInt32();
                    byte MAEndDir = reader.ReadByte();
                    obstacleNum = reader.ReadByte();

                    obstacleID    = new string[obstacleNum];
                    obstacleState = new byte[obstacleNum];

                    if (obstacleNum != 0) //障碍物等于0和不等于0会发送不同的包
                    {
                        string State        = "";
                        string ID           = "";
                        byte[] obstacleType = new byte[obstacleNum];
                        obstacleID    = new string[obstacleNum]; //障碍物ID会用到
                        obstacleState = new byte[obstacleNum];   //障碍物状态会用到
                        byte[] obstacleLogicState = new byte[obstacleNum];
                        for (int i = 0; i < obstacleNum; i++)
                        {
                            obstacleType[i]       = reader.ReadByte();
                            obstacleID[i]         = (reader.ReadUInt16()).ToString();
                            obstacleState[i]      = reader.ReadByte();
                            obstacleLogicState[i] = reader.ReadByte();
                            State = State + obstacleState[i] + " ";
                            ID    = ID + obstacleID[i] + " ";
                        }
                    }

                    byte   ZCN_TSR       = reader.ReadByte();
                    UInt32 ZCQ_ZC        = reader.ReadUInt32();
                    byte   ZCEB_Type     = reader.ReadByte();
                    byte   ZCEB_DEV_Typ  = reader.ReadByte();
                    UInt16 ZCEB_DEV_Name = reader.ReadUInt16();

                    ZCSendEB(tailSectionOrSwitch, tailID, MAEndOff, MAEndDir); //ZC发送EB消息
                }
        }
 public override void WriteUInt64Text(UInt64 value)
 {
     int count = XmlConverter.ToChars(value, chars, 0);
     if (text)
         writer.WriteText(chars, 0, count);
     else
         writer.WriteUInt64Text(value);
     signingWriter.WriteText(chars, 0, count);
 }
        private static void VerifyUInt64ImplicitCastToComplex(UInt64 value)
        {
            Complex c_cast = value;

            Support.VerifyRealImaginaryProperties(c_cast, value, 0.0,
                string.Format("UInt64ImplicitCast ({0})", value));
            
            if (value != UInt64.MaxValue)
            {
                Complex c_cast_plus = c_cast + 1;
                Support.VerifyRealImaginaryProperties(c_cast_plus, value + 1, 0.0,
                    string.Format("PLuS + UInt64ImplicitCast ({0})", value));
            }

            if (value != UInt64.MinValue)
            {
                Complex c_cast_minus = c_cast - 1;
                Support.VerifyRealImaginaryProperties(c_cast_minus, value - 1, 0.0,
                    string.Format("Minus - UInt64ImplicitCast + 1 ({0})", value));
            }
        }
Exemplo n.º 38
0
 internal static Exception TryToUInt64(string s, out UInt64 result) {
     if (!UInt64.TryParse(s, NumberStyles.AllowLeadingWhite|NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) {
         return new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "UInt64"));
     }
     return null;
 }
Exemplo n.º 39
0
 private static void VerifyUInt64ExplicitCastFromBigInteger(UInt64 value)
 {
     BigInteger bigInteger = new BigInteger(value);
     VerifyUInt64ExplicitCastFromBigInteger(value, bigInteger);
 }
            internal unsafe static Boolean TryParseUInt64(String s, NumberStyles style, IFormatProvider provider, out UInt64 result)
            {
                NumberFormatInfo info = provider == null ? NumberFormatInfo.CurrentInfo : NumberFormatInfo.GetInstance(provider);

                NumberBuffer number = new NumberBuffer();
                result = 0;

                if (!TryStringToNumber(s, style, ref number, info, false))
                {
                    return false;
                }

                if ((style & NumberStyles.AllowHexSpecifier) != 0)
                {
                    if (!HexNumberToUInt64(ref number, ref result))
                    {
                        return false;
                    }
                }
                else
                {
                    if (!NumberToUInt64(ref number, ref result))
                    {
                        return false;
                    }
                }
                return true;
            }
Exemplo n.º 41
0
        /// <summary>
        /// Called when we receive a message from the server
        /// </summary>
        void IConnection.OnMessage(IServerMessage msg)
        {
            if (this.State == ConnectionStates.Closed)
            {
                return;
            }

            // Store messages that we receive while we are connecting
            if (this.State == ConnectionStates.Connecting)
            {
                if (BufferedMessages == null)
                {
                    BufferedMessages = new List <IServerMessage>();
                }

                BufferedMessages.Add(msg);

                return;
            }

            LastMessageReceivedAt = DateTime.UtcNow;

            switch (msg.Type)
            {
            case MessageTypes.Multiple:
                LastReceivedMessage = msg as MultiMessage;

                // Not received in the reconnect process, so we can't rely on it
                if (LastReceivedMessage.IsInitialization)
                {
                    HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Init");
                }

                if (LastReceivedMessage.GroupsToken != null)
                {
                    GroupsToken = LastReceivedMessage.GroupsToken;
                }

                if (LastReceivedMessage.ShouldReconnect)
                {
                    HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Should Reconnect");

                    Reconnect();

                    // Should we return here not processing the messages that may come with it?
                    //return;
                }

                if (LastReceivedMessage.Data != null)
                {
                    for (int i = 0; i < LastReceivedMessage.Data.Count; ++i)
                    {
                        (this as IConnection).OnMessage(LastReceivedMessage.Data[i]);
                    }
                }

                break;

            case MessageTypes.MethodCall:
                MethodCallMessage methodCall = msg as MethodCallMessage;

                Hub hub = this[methodCall.Hub];

                if (hub != null)
                {
                    (hub as IHub).OnMethod(methodCall);
                }
                else
                {
                    HTTPManager.Logger.Warning("SignalR Connection", string.Format("Hub \"{0}\" not found!", methodCall.Hub));
                }

                break;

            case MessageTypes.Result:
            case MessageTypes.Failure:
            case MessageTypes.Progress:
                UInt64 id = (msg as IHubMessage).InvocationId;
                hub = FindHub(id);
                if (hub != null)
                {
                    (hub as IHub).OnMessage(msg);
                }
                else
                {
                    HTTPManager.Logger.Warning("SignalR Connection", string.Format("No Hub found for Progress message! Id: {0}", id.ToString()));
                }
                break;

            case MessageTypes.Data:
                if (OnNonHubMessage != null)
                {
                    OnNonHubMessage(this, (msg as DataMessage).Data);
                }
                break;

            case MessageTypes.KeepAlive:
                break;

            default:
                HTTPManager.Logger.Warning("SignalR Connection", "Unknown message type received: " + msg.Type.ToString());
                break;
            }
        }
Exemplo n.º 42
0
 /// <summary>
 /// Write long
 /// </summary>
 /// <param name="value"></param>
 public void WriteByte(UInt64 value)
 {
     byte[] bytes = BitConverter.GetBytes(value);
     WriteByte(bytes);
 }
Exemplo n.º 43
0
 private static bool IsBitSet(UInt64 b, int pos)
 {
     UInt64 iOne = 1;
       return (b & (iOne << pos)) != 0;
 }
Exemplo n.º 44
0
        /// <summary>
        /// Creates an Uri instance from the given parameters.
        /// </summary>
        Uri IConnection.BuildUri(RequestTypes type, TransportBase transport)
        {
            lock (SyncRoot)
            {
                // make sure that the queryBuilder is reseted
                queryBuilder.Length = 0;

                UriBuilder uriBuilder = new UriBuilder(Uri);

                if (!uriBuilder.Path.EndsWith("/"))
                {
                    uriBuilder.Path += "/";
                }

                this.RequestCounter %= UInt64.MaxValue;

                switch (type)
                {
                case RequestTypes.Negotiate:
                    uriBuilder.Path += "negotiate";
                    goto default;

                case RequestTypes.Connect:
#if !BESTHTTP_DISABLE_WEBSOCKET
                    if (transport != null && transport.Type == TransportTypes.WebSocket)
                    {
                        uriBuilder.Scheme = HTTPProtocolFactory.IsSecureProtocol(Uri) ? "wss" : "ws";
                    }
#endif

                    uriBuilder.Path += "connect";
                    goto default;

                case RequestTypes.Start:
                    uriBuilder.Path += "start";
                    goto default;

                case RequestTypes.Poll:
                    uriBuilder.Path += "poll";
                    if (this.LastReceivedMessage != null)
                    {
                        queryBuilder.Append("messageId=");
                        queryBuilder.Append(this.LastReceivedMessage.MessageId);
                    }
                    goto default;

                case RequestTypes.Send:
                    uriBuilder.Path += "send";
                    goto default;

                case RequestTypes.Reconnect:
#if !BESTHTTP_DISABLE_WEBSOCKET
                    if (transport != null && transport.Type == TransportTypes.WebSocket)
                    {
                        uriBuilder.Scheme = HTTPProtocolFactory.IsSecureProtocol(Uri) ? "wss" : "ws";
                    }
#endif

                    uriBuilder.Path += "reconnect";

                    if (this.LastReceivedMessage != null)
                    {
                        queryBuilder.Append("messageId=");
                        queryBuilder.Append(this.LastReceivedMessage.MessageId);
                    }

                    if (!string.IsNullOrEmpty(GroupsToken))
                    {
                        if (queryBuilder.Length > 0)
                        {
                            queryBuilder.Append("&");
                        }

                        queryBuilder.Append("groupsToken=");
                        queryBuilder.Append(GroupsToken);
                    }

                    goto default;

                case RequestTypes.Abort:
                    uriBuilder.Path += "abort";
                    goto default;

                case RequestTypes.Ping:
                    uriBuilder.Path += "ping";

                    queryBuilder.Append("&tid=");
                    queryBuilder.Append(this.RequestCounter++.ToString());

                    queryBuilder.Append("&_=");
                    queryBuilder.Append(Timestamp.ToString());

                    break;

                default:
                    if (queryBuilder.Length > 0)
                    {
                        queryBuilder.Append("&");
                    }

                    queryBuilder.Append("tid=");
                    queryBuilder.Append(this.RequestCounter++.ToString());

                    queryBuilder.Append("&_=");
                    queryBuilder.Append(Timestamp.ToString());

                    if (transport != null)
                    {
                        queryBuilder.Append("&transport=");
                        queryBuilder.Append(transport.Name);
                    }

                    queryBuilder.Append("&clientProtocol=");
                    queryBuilder.Append(ClientProtocols[(byte)Protocol]);

                    if (NegotiationResult != null && !string.IsNullOrEmpty(this.NegotiationResult.ConnectionToken))
                    {
                        queryBuilder.Append("&connectionToken=");
                        queryBuilder.Append(this.NegotiationResult.ConnectionToken);
                    }

                    if (this.Hubs != null && this.Hubs.Length > 0)
                    {
                        queryBuilder.Append("&connectionData=");
                        queryBuilder.Append(this.ConnectionData);
                    }

                    break;
                }

                // Query params are added to all uri
                if (this.AdditionalQueryParams != null && this.AdditionalQueryParams.Count > 0)
                {
                    queryBuilder.Append(this.QueryParams);
                }

                uriBuilder.Query = queryBuilder.ToString();

                // reset the string builder
                queryBuilder.Length = 0;

                return(uriBuilder.Uri);
            }
        }
Exemplo n.º 45
0
 /// <summary>
 /// GetLikenessValue -- Compute the normalized distance between two 64-bit hashes
 /// </summary>
 /// <param name="iNeedle"></param>
 /// <param name="iHayStack"></param>
 /// <returns></returns>
 public float GetLikenessValue(UInt64 iNeedle, UInt64 iHayStack)
 {
     return (HashSize - GetHammingDistance(iNeedle, iHayStack)) / (float)HashSize;
 }
 public IntClass(UInt64 v)
 {
     this.Value = (int)v;
 }
Exemplo n.º 47
0
        private static void VerifyUInt64ImplicitCastToBigInteger(UInt64 value)
        {
            BigInteger bigInteger = value;

            Assert.Equal(value, bigInteger);
            Assert.Equal(value.ToString(), bigInteger.ToString());
            Assert.Equal(value, (UInt64)bigInteger);

            if (value != UInt64.MaxValue)
            {
                Assert.Equal((UInt64)(value + 1), (UInt64)(bigInteger + 1));
            }

            if (value != UInt64.MinValue)
            {
                Assert.Equal((UInt64)(value - 1), (UInt64)(bigInteger - 1));
            }

            VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
        }
Exemplo n.º 48
0
 public ContentsSearcher(IEnumerable <string> directories, List <string> keywords, RegexSearch regex, UInt64 maxFileSizeInKB)
 {
     this.Directories   = directories;
     this.Keywords      = keywords;
     this.RegexSearcher = regex;
     this.MAX_FILE_SIZE = maxFileSizeInKB;
 }
 private unsafe static Boolean NumberToUInt64(ref NumberBuffer number, ref UInt64 value)
 {
     Int32 i = number.scale;
     if (i > UINT64_PRECISION || i < number.precision || number.sign)
     {
         return false;
     }
     char* p = number.digits;
     Debug.Assert(p != null, "");
     UInt64 n = 0;
     while (--i >= 0)
     {
         if (n > (0xFFFFFFFFFFFFFFFF / 10))
         {
             return false;
         }
         n *= 10;
         if (*p != '\0')
         {
             UInt64 newN = n + (UInt64)(*p++ - '0');
             // Detect an overflow here...
             if (newN < n)
             {
                 return false;
             }
             n = newN;
         }
     }
     value = n;
     return true;
 }
Exemplo n.º 50
0
 public SftpUnblockRequest(uint protocolVersion, uint requestId, byte[] handle, UInt64 offset, UInt64 length, UInt32 lockMask, Action <SftpStatusResponse> statusAction)
     : base(protocolVersion, requestId, statusAction)
 {
     this.Handle = handle;
     this.Offset = offset;
     this.Length = length;
 }
            private unsafe static Boolean HexNumberToUInt64(ref NumberBuffer number, ref UInt64 value)
            {
                Int32 i = number.scale;
                if (i > UINT64_PRECISION || i < number.precision)
                {
                    return false;
                }
                Char* p = number.digits;
                Debug.Assert(p != null, "");

                UInt64 n = 0;
                while (--i >= 0)
                {
                    if (n > (0xFFFFFFFFFFFFFFFF / 16))
                    {
                        return false;
                    }
                    n *= 16;
                    if (*p != '\0')
                    {
                        UInt64 newN = n;
                        if (*p != '\0')
                        {
                            if (*p >= '0' && *p <= '9')
                            {
                                newN += (UInt64)(*p - '0');
                            }
                            else
                            {
                                if (*p >= 'A' && *p <= 'F')
                                {
                                    newN += (UInt64)((*p - 'A') + 10);
                                }
                                else
                                {
                                    Debug.Assert(*p >= 'a' && *p <= 'f', "");
                                    newN += (UInt64)((*p - 'a') + 10);
                                }
                            }
                            p++;
                        }

                        // Detect an overflow here...
                        if (newN < n)
                        {
                            return false;
                        }
                        n = newN;
                    }
                }
                value = n;
                return true;
            }
Exemplo n.º 52
0
 public static byte[] GetBytes(UInt64 value)
 {
     return((byte[])BitConverter.GetBytes(value).Reverse().ToArray());
 }
Exemplo n.º 53
0
 public IOutputStream GetOutputStreamAt(UInt64 position)
 {
     ThrowCloningNotSuported("GetOutputStreamAt");
     return null;
 }
Exemplo n.º 54
0
 /// <summary>
 ///     Convert timestamp in milliseconds to DateTime object in UTC.
 /// </summary>
 /// <param name="valueInMs">The timestamp value in milliseconds</param>
 /// <returns>The DateTime object in UTC.</returns>
 public static DateTime ToDateTime(UInt64 valueInMs)
 {
     return(Epoch.AddMilliseconds(valueInMs));
 }
Exemplo n.º 55
0
        private static bool VerifyCtorUInt64(UInt64 value)
        {
            bool ret = true;
            BigInteger bigInteger;

            bigInteger = new BigInteger(value);

            if (!bigInteger.Equals(value))
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to UInt64 {1}", bigInteger, value);
                ret = false;
            }
            if (String.CompareOrdinal(value.ToString(), bigInteger.ToString()) != 0)
            {
                Console.WriteLine("UInt64.ToString() and BigInteger.ToString() on {0} and {1} should be equal", value, bigInteger);
                ret = false;
            }
            if (value != (UInt64)bigInteger)
            {
                Console.WriteLine("Expected BigInteger {0} to be equal to UInt64 {1}", bigInteger, value);
                ret = false;
            }

            if (value != UInt64.MaxValue)
            {
                if ((UInt64)(value + 1) != (UInt64)(bigInteger + 1))
                {
                    Console.WriteLine("Adding 1 to both {0} and {1} should remain equal", value, bigInteger);
                    ret = false;
                }
            }

            if (value != UInt64.MinValue)
            {
                if ((UInt64)(value - 1) != (UInt64)(bigInteger - 1))
                {
                    Console.WriteLine("Subtracting 1 from both {0} and {1} should remain equal", value, bigInteger);
                    ret = false;
                }
            }

            Assert.True(VerifyBigintegerUsingIdentities(bigInteger, 0 == value), " Verification Failed");
            return ret;
        }
Exemplo n.º 56
0
 public override bool NewClientSession(string strServerName, string strIP, int nPort, out UInt64 nSessionID)
 {
     nSessionID = m_nSessionIDGenerator++;
     return(true);
 }
Exemplo n.º 57
0
        private static void VerifyComparison(BigInteger x, UInt64 y, int expectedResult)
        {
            bool expectedEquals = 0 == expectedResult;
            bool expectedLessThan = expectedResult < 0;
            bool expectedGreaterThan = expectedResult > 0;

            Assert.Equal(expectedEquals, x == y);
            Assert.Equal(expectedEquals, y == x);

            Assert.Equal(!expectedEquals, x != y);
            Assert.Equal(!expectedEquals, y != x);

            Assert.Equal(expectedEquals, x.Equals(y));

            VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");

            if (expectedEquals)
            {
                Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
                Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
            }

            Assert.Equal(x.GetHashCode(), x.GetHashCode());
            Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());

            Assert.Equal(expectedLessThan, x < y);
            Assert.Equal(expectedGreaterThan, y < x);

            Assert.Equal(expectedGreaterThan, x > y);
            Assert.Equal(expectedLessThan, y > x);

            Assert.Equal(expectedLessThan || expectedEquals, x <= y);
            Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);

            Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
            Assert.Equal(expectedLessThan || expectedEquals, y >= x);
        }
Exemplo n.º 58
0
 public override void DeleteClientSession(UInt64 nSessionID)
 {
 }
 public static void Write(this BinaryWriter writer, UInt64 value, bool invertEndian = false)
 {
     if (invertEndian)
     {
         writer.WriteInvertedBytes(BitConverter.GetBytes(value));
     }
     else
     {
         writer.Write(value);
     }
 }
Exemplo n.º 60
0
        public override Int32 Create(
            String FileName,
            UInt32 CreateOptions,
            UInt32 GrantedAccess,
            UInt32 FileAttributes,
            Byte[] SecurityDescriptor,
            UInt64 AllocationSize,
            out Object FileNode0,
            out Object FileDesc,
            out FileInfo FileInfo,
            out String NormalizedName)
        {
            FileNode0      = default(Object);
            FileDesc       = default(Object);
            FileInfo       = default(FileInfo);
            NormalizedName = default(String);

            FileNode FileNode;
            FileNode ParentNode;
            Int32    Result = STATUS_SUCCESS;

            FileNode = FileNodeMap.Get(FileName);
            if (null != FileNode)
            {
                return(STATUS_OBJECT_NAME_COLLISION);
            }
            ParentNode = FileNodeMap.GetParent(FileName, ref Result);
            if (null == ParentNode)
            {
                return(Result);
            }

            if (0 != (CreateOptions & FILE_DIRECTORY_FILE))
            {
                AllocationSize = 0;
            }
            if (FileNodeMap.Count() >= MaxFileNodes)
            {
                return(STATUS_CANNOT_MAKE);
            }
            if (AllocationSize > MaxFileSize)
            {
                return(STATUS_DISK_FULL);
            }

            if ("\\" != ParentNode.FileName)
            {
                /* normalize name */
                FileName = ParentNode.FileName + "\\" + Path.GetFileName(FileName);
            }
            FileNode = new FileNode(FileName);
            FileNode.MainFileNode            = FileNodeMap.GetMain(FileName);
            FileNode.FileInfo.FileAttributes = 0 != (FileAttributes & (UInt32)System.IO.FileAttributes.Directory) ?
                                               FileAttributes : FileAttributes | (UInt32)System.IO.FileAttributes.Archive;
            FileNode.FileSecurity = SecurityDescriptor;
            if (0 != AllocationSize)
            {
                Result = SetFileSizeInternal(FileNode, AllocationSize, true);
                if (0 > Result)
                {
                    return(Result);
                }
            }
            FileNodeMap.Insert(FileNode);

            Interlocked.Increment(ref FileNode.OpenCount);
            FileNode0      = FileNode;
            FileInfo       = FileNode.GetFileInfo();
            NormalizedName = FileNode.FileName;

            return(STATUS_SUCCESS);
        }