예제 #1
0
 public BaseChunk(int length)
 {
     Length = length;
     _data  = new byte[4 + 4 + Length + 4];
     BitOperation.Int32ToBytes(Length).CopyTo(_data, 0);
     Name.FillChunk(_data);
 }
        /// <summary>
        /// Append value to stream.
        /// </summary>
        /// <param name="value"></param>
        public void Write(UInt64 value)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException("this");
            }

            // Offset value to allow zeros
            value++;

            // Count length
            var length = BitOperation.CountUsed(value);

            // Check not too large
            if (length > (LengthBits + 2) * 8)
            {
                throw new ArgumentOutOfRangeException("Value is greater than maximum of " + (UInt64.MaxValue >> 64 - LengthBits - 1) + ". Increase length bits to support larger numbers.");
            }

            // Clip MSB, it's redundant
            length--;

            // Write length
            Output.Write((UInt64)length, LengthBits);

            // Write number
            Output.Write(value, length);
        }
예제 #3
0
        private UInt64[] DecompressMany(String value, int count)
        {
            var input  = new MemoryStream(BitOperation.ParseToBytes(value));
            var output = Codec.DecompressUnsigned(input, count);

            return(output.ToArray());
        }
예제 #4
0
 public static void Initialize(int pageSize, int threadPoolSize, int totalPoolSize)
 {
     lock (typeof(UnmanagedAllocator))
     {
         if (UnmanagedAllocator.pageSize != 0)
         {
             throw new InvalidOperationException("Already initialized.");
         }
     }
     if (pageSize <= 0 || BitOperation.SmallestPow2((uint)pageSize) != (uint)pageSize)
     {
         throw new ArgumentException("pageSize must be positive power of 2");
     }
     if (threadPoolSize <= 0 || threadPoolSize % pageSize != 0)
     {
         throw new ArgumentException("threadPoolSize must be multiple of pageSize");
     }
     if (totalPoolSize <= 0 || totalPoolSize % threadPoolSize != 0)
     {
         throw new ArgumentException("totalPoolSize must be multiple of threadPoolSize");
     }
     UnmanagedAllocator.pageSize       = pageSize;
     UnmanagedAllocator.threadPoolSize = threadPoolSize;
     UnmanagedAllocator.totalPoolSize  = totalPoolSize;
 }
예제 #5
0
        public string ToString(BitOperation parentBitOp)         //
        {
            //This bit is a constant
            if (operation == BitOperation.NONE)
            {
                return(ValToString(value));
            }

            //This bit is ONE parameter operation ex : (not A)
            if (B == null)
            {
                return(OpToString(operation) + A.ToString(operation));
            }

            //This bit is TWO parameter operation ex : (A & B)
            string operationString = A.ToString(operation) + OpToString(operation) + B.ToString(operation);

            if (operation != parentBitOp)
            {
                return("(" + operationString + ")");
            }
            else
            {
                return(operationString);
            }
        }
예제 #6
0
 public Bit(BitOperation aOperation, Bit aA, Bit aB)
 {
     operation = aOperation;
     A         = aA;
     B         = aB;
     Initialize();
 }
예제 #7
0
        public async Task <ActionResult <string> > Post(AK ak)
        {
            BigInteger a;
            uint       k;

            try
            {
                if (ak.a == null || ak.k == null)
                {
                    throw new FormatException();
                }
                a = BitOperation.BinStrToBigInteger(ak.a);
                k = Convert.ToUInt32(ak.k, 10);

                if (k > 31 || ak.a.Length > 32)
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                ModelState.AddModelError("Error", "Некорректные параметры");
                return(BadRequest(ModelState));
            }

            return(await Task.Run(() => BitOperation.BigIntegerToBinStr(BitOperation.GetBit(a, k))));
        }
예제 #8
0
        public async Task <ActionResult <string> > Post(AM am)
        {
            BigInteger a;
            uint       m;

            try
            {
                if (am.a == null || am.m == null)
                {
                    throw new FormatException();
                }

                a = BitOperation.BinStrToBigInteger(am.a);
                m = Convert.ToUInt32(am.m, 10);

                if (m > 32 || am.a.Length > 32)
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                ModelState.AddModelError("Error", "Некорректные параметры");
                return(BadRequest(ModelState));
            }

            return(await Task.Run(() => BitOperation.BigIntegerToBinStr(BitOperation.ZeroSmallBits(a, m))));
        }
예제 #9
0
        public void OperateBitGetInt()
        {
            if (!args.HasBit)
            {
                return;
            }

            Key key = new Key(args.ns, args.set, "opbkey17");

            client.Delete(null, key);

            byte[] bytes = new byte[] { 0x01, 0x42, 0x03, 0x04, 0x05 };

            client.Put(null, key, new Bin(binName, bytes));

            Record record = client.Operate(null, key,
                                           BitOperation.GetInt(binName, 8, 16, false)
                                           );

            AssertRecordFound(key, record);

            long v = (long)record.GetValue(binName);

            Assert.AreEqual(16899, v);
        }
예제 #10
0
        public async Task <ActionResult <string> > Post(AIL ail)
        {
            BigInteger a;
            uint       i, l;

            try
            {
                if (ail.a == null || ail.i == null || ail.l == null)
                {
                    throw new FormatException();
                }
                a = BitOperation.BinStrToBigInteger(ail.a);
                i = Convert.ToUInt32(ail.i, 10);
                l = Convert.ToUInt32(ail.l, 10);

                if (i > l)
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                ModelState.AddModelError("Error", "Некорректные параметры");
                return(BadRequest(ModelState));
            }

            return(await Task.Run(() => BitOperation.BigIntegerToBinStr(BitOperation.GlueBits(a, i, l))));
        }
예제 #11
0
    private SuccinctBitVector(uint[] bits, int length)
    {
        Length     = length;
        this.bits  = bits;
        count      = new byte[bits.Length];
        largeCount = new int[(bits.Length + BLOCK_PER_LARGEBLOCK - 1) >> BLOCK_PER_LARGEBLOCK_BITS];
        byte sum = 0;

        for (int i = 0; i < bits.Length - 1; i++)
        {
            var popcnt = BitOperation.PopCount(bits[i]);
            if (((i + 1) & (BLOCK_PER_LARGEBLOCK - 1)) == 0)
            {
                int ind = (i + 1) >> BLOCK_PER_LARGEBLOCK_BITS;
                largeCount[ind] = largeCount[ind - 1] + sum + popcnt;
                sum             = 0;
            }
            else
            {
                sum         += popcnt;
                count[i + 1] = sum;
            }
            count0 += BITBLOCK_LENGTH - popcnt;
            count1 += popcnt;
        }
        var lastpopcnt = BitOperation.PopCount(bits[bits.Length - 1]);

        count0 += BITBLOCK_LENGTH - lastpopcnt;
        count1 += lastpopcnt;
    }
예제 #12
0
        public void OperateBitResize()
        {
            if (!args.HasBit)
            {
                return;
            }

            Key key = new Key(args.ns, args.set, "opbkey1");

            client.Delete(null, key);

            byte[] bytes = new byte[] { 0x01, 0x42 };

            client.Put(null, key, new Bin(binName, bytes));

            Record record = client.Operate(null, key,
                                           BitOperation.Resize(BitPolicy.Default, binName, 4, BitResizeFlags.DEFAULT),
                                           Operation.Get(binName)
                                           );

            AssertRecordFound(key, record);

            IList list = record.GetList(binName);

            byte[] b = (byte[])list[1];
            //Console.WriteLine(ByteUtil.BytesToHexString(b));
            Assert.IsTrue(Util.ByteArrayEquals(new byte[] { 0x01, 0x42, 0x00, 0x00 }, b));
        }
예제 #13
0
        /// <summary>
        /// Simple example of bit functionality.
        /// </summary>
        public void RunSimpleExample(AerospikeClient client, Arguments args)
        {
            Key    key     = new Key(args.ns, args.set, "bitkey");
            string binName = args.GetBinName("bitbin");

            // Delete record if it already exists.
            client.Delete(args.writePolicy, key);

            byte[] bytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };

            client.Put(args.writePolicy, key, new Bin(binName, bytes));

            // Set last 3 bits of bitmap to true.
            Record record = client.Operate(args.writePolicy, key,
                                           BitOperation.Set(BitPolicy.Default, binName, -3, 3, new byte[] { 0xE0 }),
                                           Operation.Get(binName)
                                           );

            IList list = record.GetList(binName);

            byte[] val = (byte[])list[1];

            foreach (byte b in val)
            {
                console.Info(Convert.ToString(b));
            }
        }
        /// <summary>
        /// Append value to stream.
        /// </summary>
        /// <param name="value"></param>
        public void Write(UInt64 value)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException("this");
            }

            // Offset value to allow zeros
            value++;

            // #1 Separate X into the highest power of 2 it contains (2N) and the remaining N binary digits.
            Int32 n = 0;

            while (Math.Pow(2, n + 1) <= value)
            {
                n++;
            }
            var r = value - (UInt64)Math.Pow(2, n);

            // #2 Encode N+1 with Elias gamma coding.
            var np  = (UInt64)n + 1;
            var len = BitOperation.CountUsed(np);

            Output.Write(0, len - 1);
            Output.Write(np, len);

            // #3 Append the remaining N binary digits to this representation of N+1.
            Output.Write(r, n);
        }
        /// <summary>
        /// Calculate the length of an encoded value in bits.
        /// </summary>
        /// <param name="allowZeros">(non-standard) Support zeros by automatically offsetting all values by one.</param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Int32?CalculateBitLength(UInt64 value)
        {
            var result = 0;

            // Offset for zero
            value++;

            // #1 Separate X into the highest power of 2 it contains (2N) and the remaining N binary digits.
            Byte n = 0;

            while (Math.Pow(2, n + 1) <= value)
            {
                n++;
            }
            var r = value - (UInt64)Math.Pow(2, n);

            // #2 Encode N+1 with Elias gamma coding.
            var np  = (Byte)(n + 1);
            var len = BitOperation.CountUsed(np);

            result += len - 1;
            result += len;

            // #3 Append the remaining N binary digits to this representation of N+1.
            result += n;

            return(result);
        }
예제 #16
0
 public PhysDimension(int xAxis, int yAxis, byte unit) : base(9)
 {
     BitOperation.Int32ToBytes(xAxis).CopyTo(_data, 8);
     BitOperation.Int32ToBytes(yAxis).CopyTo(_data, 12);
     _data[16] = unit;
     GetCRC(_data.Skip(4).Take(4 + Length).ToArray()).CopyTo(_data, 8 + Length);
 }
예제 #17
0
        public void OperateBitRemove()
        {
            if (!args.HasBit)
            {
                return;
            }

            Key key = new Key(args.ns, args.set, "opbkey3");

            client.Delete(null, key);

            byte[] bytes = new byte[] { 0x01, 0x42, 0x03, 0x04, 0x05 };

            client.Put(null, key, new Bin(binName, bytes));

            Record record = client.Operate(null, key,
                                           BitOperation.Remove(BitPolicy.Default, binName, 2, 3),
                                           Operation.Get(binName)
                                           );

            AssertRecordFound(key, record);

            IList list = record.GetList(binName);

            byte[] b = (byte[])list[1];
            Assert.IsTrue(Util.ByteArrayEquals(new byte[] { 0x01, 0x42 }, b));
        }
예제 #18
0
        /// <summary>
        /// Calculate the length of an encoded value in bits.
        /// </summary>
        /// <param name="allowZeros">(non-standard) Support zeros by automatically offsetting all values by one.</param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Int32?CalculateBitLength(UInt64 value)
        {
            // Offset for zero
            value++;

            return(BitOperation.CountUsed(value) * 2 - 1);
        }
예제 #19
0
        public async Task <ActionResult <string> > Post(AIJ aij)
        {
            BigInteger a;
            uint       i, j;

            try
            {
                if (aij.a == null || aij.i == null || aij.j == null)
                {
                    throw new FormatException();
                }

                a = BitOperation.BinStrToBigInteger(aij.a);
                i = Convert.ToUInt32(aij.i, 10);
                j = Convert.ToUInt32(aij.j, 10);

                if (i > 31 || j > 31 || aij.a.Length > 32)
                {
                    throw new FormatException();
                }
            }
            catch (FormatException)
            {
                ModelState.AddModelError("Error", "Некорректные параметры");
                return(BadRequest(ModelState));
            }

            return(await Task.Run(() => BitOperation.BigIntegerToBinStr(BitOperation.SwapBit(a, i, j))));
        }
        public void Decompress_OutputPerfectSize()
        {
            var input  = new MemoryStream(BitOperation.ParseToBytes("11 000000"));
            var output = Codec.DecompressUnsigned(input, 1).ToList();

            Assert.AreEqual(1, output.Count());
            Assert.AreEqual((UInt64)0, output.First());
        }
예제 #21
0
        /// <summary>
        /// Returns the MurmurHash3_x86_32 hash.
        /// Original source/tests at <a href="https://github.com/yonik/java_util/">https://github.com/yonik/java_util/</a>.
        /// </summary>
        public static int Murmurhash3_x86_32(byte[] data, int offset, int len, int seed)
        {
            const int c1 = unchecked ((int)0xcc9e2d51);
            const int c2 = 0x1b873593;

            int h1         = seed;
            int roundedEnd = offset + (len & unchecked ((int)0xfffffffc)); // round down to 4 byte block

            for (int i = offset; i < roundedEnd; i += 4)
            {
                // little endian load order
                int k1 = (((sbyte)data[i]) & 0xff) | ((((sbyte)data[i + 1]) & 0xff) << 8) | ((((sbyte)data[i + 2]) & 0xff) << 16) | (((sbyte)data[i + 3]) << 24);
                k1 *= c1;
                k1  = BitOperation.RotateLeft(k1, 15);
                k1 *= c2;

                h1 ^= k1;
                h1  = BitOperation.RotateLeft(h1, 13);
                h1  = h1 * 5 + unchecked ((int)0xe6546b64);
            }

            // tail
            int k2 = 0;

            switch (len & 0x03)
            {
            case 3:
                k2 = (((sbyte)data[roundedEnd + 2]) & 0xff) << 16;
                // fallthrough
                goto case 2;

            case 2:
                k2 |= (((sbyte)data[roundedEnd + 1]) & 0xff) << 8;
                // fallthrough
                goto case 1;

            case 1:
                k2 |= (((sbyte)data[roundedEnd]) & 0xff);
                k2 *= c1;
                k2  = BitOperation.RotateLeft(k2, 15);
                k2 *= c2;
                h1 ^= k2;
                break;
            }

            // finalization
            h1 ^= len;

            // fmix(h1);
            h1 ^= (int)((uint)h1 >> 16);
            h1 *= unchecked ((int)0x85ebca6b);
            h1 ^= (int)((uint)h1 >> 13);
            h1 *= unchecked ((int)0xc2b2ae35);
            h1 ^= (int)((uint)h1 >> 16);

            return(h1);
        }
 public void Read_15_15_15()
 {
     using (var stream = new MemoryStream(BitOperation.ParseToBytes("10100100 00010100 10000010 10010000 00000000"))) {
         using (var reader = new EliasOmegaUnsignedReader(stream)) {
             Assert.AreEqual((ulong)15, reader.Read());
             Assert.AreEqual((ulong)15, reader.Read());
             Assert.AreEqual((ulong)15, reader.Read());
         }
     }
 }
예제 #23
0
 public void Read_13_13_13()
 {
     using (var stream = new MemoryStream(BitOperation.ParseToBytes("10000111 00001110 00011000"))) {
         using (var reader = new FibonacciUnsignedReader(stream)) {
             Assert.AreEqual((ulong)13, reader.Read());
             Assert.AreEqual((ulong)13, reader.Read());
             Assert.AreEqual((ulong)13, reader.Read());
         }
     }
 }
 public void Read_1_1_1()
 {
     using (var stream = new MemoryStream(BitOperation.ParseToBytes("10000001 10000001 10000001"))) {
         using (var reader = new VLQUnsignedReader(stream)) {
             Assert.AreEqual((ulong)1, reader.Read());
             Assert.AreEqual((ulong)1, reader.Read());
             Assert.AreEqual((ulong)1, reader.Read());
         }
     }
 }
예제 #25
0
            public unsafe UnmanagedAllocatorContext(short id)
            {
                this.id = id;
                int num = 27 - BitOperation.CountLeadingZeroes(UnmanagedAllocator.ThreadPoolSize);

                this.chunkHeader = new byte *[num];
                this.allocHandle = UnmanagedAllocator.RequestPool();
                this.currentPage = this.allocHandle;
                this.releaseHead = IntPtr.Zero;
            }
 public void Read_2_2_2()
 {
     using (var stream = new MemoryStream(BitOperation.ParseToBytes("01101101 10000000"))) {
         using (var reader = new EliasGammaUnsignedReader(stream)) {
             Assert.AreEqual((ulong)2, reader.Read());
             Assert.AreEqual((ulong)2, reader.Read());
             Assert.AreEqual((ulong)2, reader.Read());
         }
     }
 }
예제 #27
0
 public void Read_4_4_4()
 {
     using (var stream = new MemoryStream(BitOperation.ParseToBytes("00001001 00001001 00001001"))) {
         using (var reader = new ThompsonAlphaUnsignedReader(stream)) {
             Assert.AreEqual((ulong)4, reader.Read());
             Assert.AreEqual((ulong)4, reader.Read());
             Assert.AreEqual((ulong)4, reader.Read());
         }
     }
 }
예제 #28
0
            private int GetChunkIndex(int size)
            {
                int num  = BitOperation.CountLeadingZeroes(size - 1);
                int num2 = 28 - num;

                if (num2 < 0)
                {
                    num2 = 0;
                }
                return(num2);
            }
예제 #29
0
        public static string ResultDefault(this BitOperation op)
        {
            switch (op)
            {
            case BitOperation.Test:
                return("false");

            default:
                return("");
            }
        }
예제 #30
0
        public static string ResultType(this BitOperation op)
        {
            switch (op)
            {
            case BitOperation.Test:
                return("bool");

            default:
                return("void");
            }
        }
예제 #31
0
		public BitInstruction(int offset, BitOperation operation, Operand destination, Operand source)
			: base(offset, destination, source)
		{
			this.operation = operation;
		}