Exemple #1
0
        public static int GetMaxEnumBits(long maxValue)
        {
            Contract.Requires/*<ArgumentOutOfRangeException>*/ (maxValue > 1, kGetMaxEnumBits_MaxValueOutOfRangeMessage);
            Contract.Ensures(Contract.Result <int>() > 0);

            return(Bits.IndexOfHighestBitSet((ulong)maxValue - 1) + 1);
        }
        public override IEnumerable <TCursor> ElementsByName(TName localName)
        {
            Contract.Requires(ValidateNameArg(localName));
            Contract.Ensures(Contract.Result <IEnumerable <TCursor> >() != null);

            throw new NotImplementedException();
        }
        /// <summary>Takes a (unsigned) integer and converts it into its four-cc value</summary>
        /// <param name="groupTag"></param>
        /// <param name="tag">optional result buffer</param>
        /// <param name="isBigEndian">endian order override</param>
        /// <returns>big-endian ordered four-cc if <paramref name="isBigEndian"/> is true, little-endian if false</returns>
        public static char[] FromUInt(TagWord groupTag, char[] tag = null, bool isBigEndian = true)
        {
            Contract.Requires(tag == null || tag.Length >= 4);

            Contract.Ensures(Contract.Result <char[]>() != null);
            Contract.Ensures(Contract.Result <char[]>().Length >= kExpectedTagLength);

            if (tag == null)
            {
                tag = new char[4];
            }

            if (isBigEndian)
            {
                tag[0] = (char)((groupTag & 0xFF000000) >> 24);
                tag[1] = (char)((groupTag & 0x00FF0000) >> 16);
                tag[2] = (char)((groupTag & 0x0000FF00) >> 8);
                tag[3] = (char)(groupTag & 0x000000FF);
            }
            else
            {
                tag[3] = (char)((groupTag & 0xFF000000) >> 24);
                tag[2] = (char)((groupTag & 0x00FF0000) >> 16);
                tag[1] = (char)((groupTag & 0x0000FF00) >> 8);
                tag[0] = (char)(groupTag & 0x000000FF);
            }

            return(tag);
        }
        public double[] WriteFixedArray(double[] array)
        {
            Contract.Requires(array != null);
            Contract.Ensures(Contract.Result <double[]>() != null);

            return(WriteFixedArray(array, 0, array.Length));
        }
        public static byte[] ByteStringToArray(byte[] bytes, string data, int startIndex, int count)
        {
            Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(data));
            Contract.Requires(startIndex >= 0);
            Contract.Requires(startIndex < data.Length);
            Contract.Requires(count > 0);
            Contract.Requires((startIndex + count) <= data.Length);
            Contract.Requires(
                (((data.Length - startIndex) - count) % 2) == 0,
                "Can't byte-ify a string that's not even!"
                );
            Contract.Requires <ArgumentNullException>(bytes != null);
            Contract.Requires(bytes.Length >= (count / 2));

            Contract.Ensures(Contract.Result <byte[]>() != null);

            Array.Clear(bytes, 0, bytes.Length);

            for (int x = startIndex, index = 0
                 ; x < (startIndex + count)
                 ; x += 2, index++)
            {
                bytes[index] = (byte)CharsToByte(NumeralBase.Hex, data, x);
            }

            return(bytes);
        }
Exemple #6
0
        public EndianStream StreamListElementsWithClear <T>(IList <T> values, int readCount, Func <T> initializer)
            where T : class, IO.IEndianStreamSerializable
        {
            Contract.Requires(values != null);
            Contract.Requires(initializer != null);
            Contract.Ensures(values.Count == readCount);

            bool reading = IsReading;

            if (reading)
            {
                values.Clear();
            }
            else
            {
                readCount = values.Count;
            }

            for (int x = 0; x < readCount; x++)
            {
                T v = reading
                                        ? initializer()
                                        : values[x];

                Stream(v);

                if (reading)
                {
                    values.Add(v);
                }
            }

            return(this);
        }
Exemple #7
0
        public static IEnumBitStreamer <TEnum> For <TEnum>()
            where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            Contract.Ensures(Contract.Result <IEnumBitStreamer <TEnum> >() != null);

            return(EnumBitStreamer <TEnum> .Instance);
        }
        /// <summary>Reads a tag id (eight character code)</summary>
        /// <returns>Big-endian ordered tag id</returns>
        public char[] ReadTag64()
        {
            Contract.Ensures(Contract.Result <char[]>() != null);
            Contract.Ensures(Contract.Result <char[]>().Length == 8);

            return(ReadTag64(new char[8]));
        }
        /// <summary>Reads a tag id (four character code)</summary>
        /// <returns>Big-endian ordered tag id</returns>
        public char[] ReadTag32()
        {
            Contract.Ensures(Contract.Result <char[]>() != null);
            Contract.Ensures(Contract.Result <char[]>().Length == 4);

            return(ReadTag32(new char[4]));
        }
Exemple #10
0
        /// <summary>Byte swap a given structure a number of times over a range of bytes</summary>
        /// <param name="definition">Structure definition in terms of byte swap codes</param>
        /// <param name="buffer">Buffer containing the bytes of an instance of the definition</param>
        /// <param name="startIndex">Where to start processing the definition in the buffer</param>
        /// <param name="count">Number of times to process the definition on the buffer</param>
        /// <returns>Offset in <paramref name="buffer"/> where processing ended</returns>
        public static int SwapData(IByteSwappable definition, byte[] buffer,
                                   int startIndex = 0, int count = 1)
        {
            Contract.Requires <ArgumentNullException>(definition != null);
            Contract.Requires <ArgumentNullException>(buffer != null);
            Contract.Requires <ArgumentOutOfRangeException>(startIndex >= 0);
            Contract.Requires <ArgumentOutOfRangeException>(startIndex <= buffer.Length);
            Contract.Requires <ArgumentOutOfRangeException>(count > 0);
            Contract.Requires <ArgumentOutOfRangeException>((count * definition.SizeOf) <= (buffer.Length - startIndex),
                                                            "buffer doesn't have enough data for the given byte swap parameters");
            Contract.Ensures(Contract.Result <int>() >= 0);

            if (count == 0)
            {
                return(startIndex);
            }

            var swap         = new Swapper(definition);
            int buffer_index = startIndex;

            for (int elements_remaining = count; elements_remaining > 0; elements_remaining--)
            {
                buffer_index = swap.SwapData(buffer, buffer_index);
            }

            Contract.Assert(buffer_index == (startIndex + (definition.SizeOf * count)));
            return(buffer_index);
        }
Exemple #11
0
        /// <summary>Flush the cache to <see cref="BaseStream"/> with <see cref="kWordByteCount"/> or fewer bytes bytes</summary>
        void FlushCache()
        {
                        #if !CONTRACTS_FULL_SHIM // can't do this with our shim! ValueAtReturn sets out param to default ON ENTRY
            Contract.Ensures(Contract.ValueAtReturn(out mCache) == 0);
            Contract.Ensures(Contract.ValueAtReturn(out mCacheBitIndex) == 0);
                        #endif

            if (mCacheBitIndex == 0)             // no bits to flush!
            {
                Contract.Assert(mCache == 0, "Why is there data in the cache?");
                return;
            }

            mCacheBitsStreamedCount = 0;

            int byte_count = (mCacheBitIndex - 1) >> Bits.kByteBitShift; // number of bytes to try and write
            int shift      = kWordBitCount - Bits.kByteBitCount;         // start shifting from the MSB
            while (                                                      /*!IsEndOfStream &&*/
                byte_count >= 0)
            {
                mIoBuffer[0] = (byte)(mCache >> shift);
                BaseStream.Write(mIoBuffer, 0, sizeof(byte));
                --byte_count;
                shift -= Bits.kByteBitCount;
                mCacheBitsStreamedCount += Bits.kByteBitCount;
            }

            if (byte_count != -1 && ThrowOnOverflow.CanWrite())
            {
                throw new System.IO.EndOfStreamException("Tried to write more bits than the stream has/can see");
            }

            mCache         = 0;
            mCacheBitIndex = 0;
        }
Exemple #12
0
        public string ToDisplayString()
        {
            Contract.Ensures(Contract.Result <string>() != null);

            if (IsNone)
            {
                return(TypeExtensions.kNoneDisplayString);
            }

            var sb               = new System.Text.StringBuilder(Build.ToDisplayString());
            int platform_index   = TargetPlatformIndex;
            int rsrc_model_index = ResourceModelIndex;

            if (platform_index.IsNotNone())
            {
                var platform = EngineRegistry.TargetPlatforms[platform_index];
                sb.AppendFormat(".{0}", platform);

                #region ResourceModel
                if (rsrc_model_index.IsNotNone())
                {
                    var rsrc_model = EngineRegistry.ResourceModels[rsrc_model_index];
                    sb.AppendFormat(".{0}", rsrc_model);
                }
                #endregion
            }

            return(sb.ToString());
        }
        public static string ToStringList(StringListDesc desc, IEnumerable <long> values,
                                          Predicate <IEnumerable <long> > writeTerminator = null)
        {
            Contract.Requires(!desc.RequiresTerminator || writeTerminator != null);
            Contract.Ensures(Contract.Result <string>() != null);

            var chars = new List <char>();

            bool needs_separator = false;
            int  radix           = (int)desc.Radix;

            if (values != null)
            {
                foreach (var value in values)
                {
                    if (needs_separator)
                    {
                        chars.Add(desc.Separator);
                    }
                    else
                    {
                        needs_separator = true;
                    }

                    ToStringBuilder(chars, value, radix, desc.Digits);
                }

                if (writeTerminator != null && writeTerminator(values))
                {
                    chars.Add(desc.Terminator);
                }
            }

            return(new string(chars.ToArray()));
        }
Exemple #14
0
        public static byte[] LowLevelCompress(byte[] bytes, Shell.EndianFormat byteOrder)
        {
            Contract.Requires <ArgumentNullException>(bytes != null);
            Contract.Ensures(Contract.Result <byte[]>() != null);

            byte[] result = new byte[sizeof(int)];
            // Setup the decompressed size header
            byte[] size_bytes = BitConverter.GetBytes(bytes.Length);
            if (!byteOrder.IsSameAsRuntime())
            {
                Bitwise.ByteSwap.SwapInt32(size_bytes, 0);
            }
            Array.Copy(size_bytes, result, size_bytes.Length);

            var zip = new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(
                ICSharpCode.SharpZipLib.Zip.Compression.Deflater.BEST_COMPRESSION, false);

            {
                zip.SetInput(bytes);
                zip.Finish();
                byte[] temp            = new byte[bytes.Length];
                int    compressed_size = zip.Deflate(temp);

                Contract.Assert(compressed_size <= bytes.Length);
                Array.Resize(ref result, sizeof(int) + compressed_size);
                Array.Copy(temp, 0, result, sizeof(int), compressed_size);
            }
            return(result);
        }
Exemple #15
0
        public static VectorIndexInT GetVectorIndexInT <T>()
            where T : struct
        {
            Contract.Ensures(Contract.Result <VectorIndexInT>() != null);

            TypeCode c = Type.GetTypeCode(typeof(T));

            switch (c)
            {
            case TypeCode.SByte:
            case TypeCode.Byte:
                return(VectorIndexInBytes);

            case TypeCode.Int16:
            case TypeCode.UInt16:
                return(VectorIndexInInt16);

            case TypeCode.Int32:
            case TypeCode.UInt32:
                return(VectorIndexInInt32);

            case TypeCode.Int64:
            case TypeCode.UInt64:
                return(VectorIndexInInt64);

            default: throw new ArgumentException(c.ToString(), nameof(T));
            }
        }
Exemple #16
0
        byte[] BuildAuthenticationData()
        {
            Contract.Ensures(Contract.Result <byte[]>() != null ||
                             mFooter.Authentication == BlobTransportStreamAuthentication.None);
            Contract.Assert(mFooterPosition.IsNotNone());

            System.Security.Cryptography.HashAlgorithm hash_algo = null;
            switch (mFooter.Authentication)
            {
            case BlobTransportStreamAuthentication.None: break;

            // #TODO_IMPLEMENT:
            case BlobTransportStreamAuthentication.Crc: throw new NotImplementedException();

            case BlobTransportStreamAuthentication.Hash: throw new NotImplementedException();

            case BlobTransportStreamAuthentication.Rsa: throw new NotImplementedException();
            }

            if (hash_algo != null)
            {
                return(hash_algo.ComputeHash(BaseStream, StartPosition, mFooterPosition));
            }

            return(null);
        }
        public bool[] ReadFixedArray(bool[] array)
        {
            Contract.Requires(array != null);
            Contract.Ensures(Contract.Result <bool[]>() != null);

            return(ReadFixedArray(array, 0, array.Length));
        }
Exemple #18
0
        public static BitVectorUserInterfaceData ForStrings(IEnumerable <string> bitStrings)
        {
            Contract.Ensures(Contract.Result <BitVectorUserInterfaceData>() != null);

            var info = new BitVectorUserInterfaceData();

            if (bitStrings != null)
            {
                int bit_index    = 0;
                var bit_ui_infos = new List <BitUserInterfaceData>(Bits.kInt64BitCount);
                foreach (var str in bitStrings)
                {
                    var bit_ui_info = new BitUserInterfaceData
                    {
                        DisplayName = str,
                        Visible     = true
                    };

                    if (bit_ui_info.CanNotBeRendered)
                    {
                        bit_ui_infos.Add(null);
                    }
                    else
                    {
                        bit_ui_infos.Add(bit_ui_info);
                    }

                    bit_index++;
                }

                info.SetInfoFromFactoryData(bit_ui_infos);
            }
            return(info);
        }
Exemple #19
0
        public static BitVectorUserInterfaceData ForEnum(Type enumType, int explicitNumberOfBits = TypeExtensions.kNone)
        {
            Contract.Requires <ArgumentNullException>(enumType != null);
            Contract.Requires(Reflection.Util.IsEnumType(enumType));
            Contract.Requires(explicitNumberOfBits.IsNoneOrPositive());
            Contract.Ensures(Contract.Result <BitVectorUserInterfaceData>() != null);

            var bit_field_infos = Reflection.Util.GetEnumFields(enumType);
            var bit_ui_infos    = new List <BitUserInterfaceData>(Bits.kInt64BitCount);

            bool find_highest_index = explicitNumberOfBits.IsNone();
            int  highest_index      = explicitNumberOfBits - 1;

            foreach (var bit_field_info in bit_field_infos)
            {
                int bit_index = Convert.ToInt32(bit_field_info.GetRawConstantValue(), Util.InvariantCultureInfo);
                if (bit_index < 0)
                {
                    continue;
                }

                if (find_highest_index)
                {
                    highest_index = System.Math.Max(highest_index, bit_index);

                    if (bit_field_info.Name == EnumBitEncoderBase.kEnumMaxMemberName ||
                        bit_field_info.Name == EnumBitEncoderBase.kEnumNumberOfMemberName)
                    {
                        highest_index--;
                        find_highest_index = false;
                    }
                }

                if (!find_highest_index && bit_index > highest_index)
                {
                    continue;
                }

                bit_ui_infos.EnsureCount(bit_index + 1);
                if (bit_ui_infos[bit_index] != null)
                {
                    continue;
                }

                var bit_ui_info = new BitUserInterfaceData();
                SetBitInfoFromFieldInfo(bit_ui_info, bit_field_info);

                if (bit_ui_info.CanNotBeRendered)
                {
                    continue;
                }

                bit_ui_infos[bit_index] = bit_ui_info;
            }

            var info = new BitVectorUserInterfaceData();

            info.SetInfoFromFactoryData(bit_ui_infos);
            return(info);
        }
        /// <summary>Reads a tag id (eight character code)</summary>
        /// <param name="tag">Array to populate</param>
        /// <returns>Big-endian ordered tag id</returns>
        public char[] ReadTag64(char[] tag)
        {
            Contract.Requires(tag != null);
            Contract.Requires(tag.Length >= 8);
            Contract.Ensures(Contract.Result <char[]>() != null);
            Contract.Ensures(Contract.Result <char[]>().Length >= 8);

            tag[0]     = (char)base.ReadByte();
            tag[1]     = (char)base.ReadByte();
            tag[2]     = (char)base.ReadByte();
            tag[3]     = (char)base.ReadByte();
            tag[4 + 0] = (char)base.ReadByte();
            tag[4 + 1] = (char)base.ReadByte();
            tag[4 + 2] = (char)base.ReadByte();
            tag[4 + 3] = (char)base.ReadByte();

            // Explicitly check for Little endian since this is
            // a character array and not a primitive integer
            if (ByteOrder == Shell.EndianFormat.Little)
            {
                Array.Reverse(tag, 0, 4);
                Array.Reverse(tag, 4, 4);
            }

            return(tag);
        }
Exemple #21
0
        public string GetDescription(int bitIndex)
        {
            Contract.Requires(bitIndex >= 0 && bitIndex < NumberOfBits);
            Contract.Ensures(Contract.Result <string>() != null);

            throw new NotImplementedException();
        }
Exemple #22
0
        public static int PaddingRequired(int alignmentBit, int value)
        {
            Contract.Requires <System.ArgumentOutOfRangeException>(alignmentBit <= kMaxAlignmentBit);
            Contract.Requires <System.ArgumentOutOfRangeException>(value >= 0);
            Contract.Ensures(Contract.Result <int>() >= 0);

            return((int)(Align(alignmentBit, value) - value));
        }
        public static int GetByteCount(Shell.ProcessorWordSize value)
        {
            Contract.Ensures(Contract.Result <int>() > 0);

            int mul = (int)value + 1;

            return(8 * mul);
        }
Exemple #24
0
        /// <summary>Restore the cursor to what it was before the corresponding call to a <see cref="WriteElementBegin(string, XmlElement&amp;)"/></summary>
        public void WriteElementEnd(ref TCursor oldCursor)
        {
                        #if !CONTRACTS_FULL_SHIM // can't do this with our shim! ValueAtReturn sets out param to default ON ENTRY
            Contract.Ensures(Contract.ValueAtReturn(out oldCursor) == null);
                        #endif

            RestoreCursor(ref oldCursor);
        }
        /// <summary>Returns a string representation of this object</summary>
        /// <returns>"[Engine\tBranch\tRevision]"</returns>
        public override string ToString()
        {
            Contract.Ensures(Contract.Result <string>() != null);

            // #REVIEW_BLAM: This isn't great when viewing in a debugger, as the tabs seem to be ignored (so there's no whitespace)
            return(string.Format("[{0}\t{1}\t{2}]",
                                 Engine, Branch, Revision));
        }
        public XmlDocument ToXmlDocument()
        {
            Contract.Ensures(Contract.Result <XmlDocument>() != null);

            var doc = new XmlDocument();

            return(ToXmlDocument(doc));
        }
        public static TigerHashBase CreateHaloWarsTigerHash()
        {
            Contract.Ensures(Contract.Result <TigerHashBase>() != null);

            var tiger = TigerHashBase.Create(TigerHash.kAlgorithmName);

            return(tiger);
        }
Exemple #28
0
        public static ulong GetBitmaskFlags(ulong maxValue)
        {
            Contract.Requires/*<ArgumentOutOfRangeException>*/ (maxValue > 0, kGetBitmaskFlag_MaxValueOutOfRangeMessage);
            Contract.Requires/*<ArgumentOutOfRangeException>*/ (maxValue <= kUInt64BitCount);
            Contract.Ensures(Contract.Result <ulong>() > 0);

            return(BitCountToMask64((int)--maxValue));
        }
Exemple #29
0
        public static IEnumBitStreamer <TEnum> ForWithOptions <TEnum, TOptions>()
            where TEnum : struct, IComparable, IFormattable, IConvertible
            where TOptions : EnumBitStreamerOptions, new()
        {
            Contract.Ensures(Contract.Result <IEnumBitStreamer <TEnum> >() != null);

            return(EnumBitStreamerWithOptions <TEnum, TOptions> .Instance);
        }
        public static int GetBitCount(Shell.ProcessorWordSize value)
        {
            Contract.Ensures(Contract.Result <int>() > 0);

            int shift = (int)value;

            return(8 << shift);
        }