コード例 #1
0
        public StreamTypeNamer(string prefix)
        {
            Precondition.For(prefix, nameof(prefix)).NotNullOrWhiteSpace();

            this.prefix = prefix;
        }
コード例 #2
0
ファイル: ComponentManager.cs プロジェクト: sontx/config4net
 public T CreateComponentFromComponentType <T>(Type componentType) where T : IComponent
 {
     Precondition.ArgumentNotNull(componentType, nameof(componentType));
     Precondition.ArgumentCompatibleType(componentType, typeof(IComponent), nameof(componentType));
     return((T)ComponentFactoryWrapper.From(_registeredComponentFactories[componentType]).Create());
 }
コード例 #3
0
        public ThreadedWork(Action finishedWorkCallback)
        {
            Precondition.IsNotNull(finishedWorkCallback);

            this.FinishedWorkCallback = finishedWorkCallback;
        }
コード例 #4
0
        /// <summary>
        /// 确认按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sureButton_Click(object sender, EventArgs e)
        {
            string error = null;

            if (!this.checkDatas(ref error))
            {
                MessageBox.Show(error, "错误", MessageBoxButtons.OK);
                return;
            }

            if (this.editPrecondition != null)//编辑
            {
                Precondition tmpP = new Precondition();
                tmpP.name = this.editPrecondition.name;
                tmpP.type = this.editPrecondition.type;

                this.editPrecondition.name       = this.nameTextBox.Text.Trim(new char[] { '\n', ' ' });
                this.editPrecondition.type       = this.typeTextBox.Text.Trim(new char[] { '\n', ' ' });
                this.editPrecondition.childCount = (int)this.numericUpDown1.Value;
                this.editPrecondition.isBase     = this.isBasePCheckBox.Checked;

                if (this.editPrecondition.childCount > 0 && !this.isBasePCheckBox.Checked)
                {
                    this.editPrecondition.child = new List <Precondition>();
                    if (this.editPrecondition.childCount >= 1)
                    {
                        Precondition child1 = this.childDatas[this.child1CheckedListBox.SelectedIndex];
                        this.editPrecondition.child.Add(child1);
                    }

                    if (this.editPrecondition.childCount >= 2)
                    {
                        Precondition child2 = this.childDatas[this.child2CheckedListBox.SelectedIndex];
                        this.editPrecondition.child.Add(child2);
                    }
                }

                List <Precondition> parms = new List <Precondition>();
                parms.Add(tmpP);
                parms.Add(this.editPrecondition);
                NotificationCenter.DefaultCenter().postNotification("PreconditionUpdate", parms);
            }
            else
            {
                Precondition newP = new Precondition();
                newP.name       = this.nameTextBox.Text.Trim(new char[] { '\n', ' ' });
                newP.type       = this.typeTextBox.Text.Trim(new char[] { '\n', ' ' });
                newP.childCount = (int)this.numericUpDown1.Value;
                newP.isBase     = this.isBasePCheckBox.Checked;
                if (newP.childCount > 0 && !this.isBasePCheckBox.Checked)
                {
                    newP.child = new List <Precondition>();
                    if (newP.childCount >= 1)
                    {
                        Precondition child1 = this.childDatas[this.child1CheckedListBox.SelectedIndex];
                        newP.child.Add(child1);
                    }

                    if (newP.childCount >= 2)
                    {
                        Precondition child2 = this.childDatas[this.child2CheckedListBox.SelectedIndex];
                        newP.child.Add(child2);
                    }
                }

                this.childPreconditions.Add(newP);
            }

            if (this.m_delegate != null)
            {
                this.m_delegate.RefreshPrecondition();
            }

            this.Close();
        }
コード例 #5
0
ファイル: Mutator.cs プロジェクト: riverar/devtools
 /// <summary>
 /// Visits the specified precondition.
 /// </summary>
 /// <param name="precondition">The precondition.</param>
 public virtual IPrecondition Visit(Precondition precondition)
 {
     precondition.Condition = this.Visit(precondition.Condition);
       if (precondition.Description != null)
     precondition.Description = this.Visit(precondition.Description);
       if (precondition.ExceptionToThrow != null)
     precondition.ExceptionToThrow = this.Visit(precondition.ExceptionToThrow);
       return precondition;
 }
コード例 #6
0
 private void CheckRange(int length)
 {
     Precondition.InRange(Position + length, 0, Buffer.Length,
                          $"Not enough space in packet: {ToString()}\n");
 }
コード例 #7
0
        public static bool TryFormat(this Guid value, Span <byte> buffer, out int bytesWritten, TextFormat format = default(TextFormat), EncodingData encoding = default(EncodingData))
        {
            if (format.IsDefault)
            {
                format.Symbol = 'G';
            }
            Precondition.Require(format.Symbol == 'G' || format.Symbol == 'D' || format.Symbol == 'N' || format.Symbol == 'B' || format.Symbol == 'P');
            bool dash = true;
            char tail = '\0';

            bytesWritten = 0;

            switch (format.Symbol)
            {
            case 'D':
            case 'G':
                break;

            case 'N':
                dash = false;
                break;

            case 'B':
                if (!TryWriteChar('{', buffer, ref bytesWritten, encoding))
                {
                    return(false);
                }
                tail = '}';
                break;

            case 'P':
                if (!TryWriteChar('(', buffer, ref bytesWritten, encoding))
                {
                    return(false);
                }
                tail = ')';
                break;

            default:
                Precondition.Require(false);     // how did we get here?
                break;
            }


            var byteFormat = new TextFormat('x', 2);

            unsafe
            {
                byte *bytes = (byte *)&value;

                if (!TryWriteByte(bytes[3], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[2], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[1], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[0], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }

                if (dash)
                {
                    if (!TryWriteChar('-', buffer, ref bytesWritten, encoding))
                    {
                        return(false);
                    }
                }

                if (!TryWriteByte(bytes[5], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[4], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }

                if (dash)
                {
                    if (!TryWriteChar('-', buffer, ref bytesWritten, encoding))
                    {
                        return(false);
                    }
                }

                if (!TryWriteByte(bytes[7], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[6], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }

                if (dash)
                {
                    if (!TryWriteChar('-', buffer, ref bytesWritten, encoding))
                    {
                        return(false);
                    }
                }

                if (!TryWriteByte(bytes[8], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[9], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }

                if (dash)
                {
                    if (!TryWriteChar('-', buffer, ref bytesWritten, encoding))
                    {
                        return(false);
                    }
                }

                if (!TryWriteByte(bytes[10], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[11], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[12], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[13], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[14], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[15], buffer, ref bytesWritten, byteFormat, encoding))
                {
                    return(false);
                }
            }

            if (tail != '\0')
            {
                if (!TryWriteChar(tail, buffer, ref bytesWritten, encoding))
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #8
0
ファイル: Copier.cs プロジェクト: riverar/devtools
 /// <summary>
 /// Visits the specified precondition.
 /// </summary>
 /// <param name="precondition">The precondition.</param>
 protected virtual IPrecondition DeepCopy(Precondition precondition)
 {
     precondition.Condition = this.Substitute(precondition.Condition);
       if (precondition.Description != null)
     precondition.Description = this.Substitute(precondition.Description);
       if (precondition.ExceptionToThrow != null)
     precondition.ExceptionToThrow = this.Substitute(precondition.ExceptionToThrow);
       return precondition;
 }
コード例 #9
0
 public static string Password(this HtmlControlHelper helper,
                               string name, object value, IDictionary <string, object> attributes)
 {
     Precondition.Defined(name, () => Error.ArgumentNull("name"));
     return(InputBuilder(helper, "password", name, value, attributes));
 }
コード例 #10
0
        private static string SelectBuilder(HtmlControlHelper helper,
                                            string name, MultiSelectList dataSource, bool isMultiple,
                                            IDictionary <string, object> attributes)
        {
            Precondition.Defined(name, () => Error.ArgumentNull("name"));

            if (attributes == null)
            {
                attributes = new ValueDictionary();
            }

            if (isMultiple)
            {
                attributes["multiple"] = "multiple";
            }
            else
            {
                attributes.Remove("multiple");
            }

            HtmlElementBuilder outer = new HtmlElementBuilder("select");

            outer.Attributes.Merge(attributes, true);
            outer.Attributes.Merge("name", name, true);

            if (dataSource != null)
            {
                StringBuilder builder = new StringBuilder();

                IEnumerable <ListItem> listItems = dataSource.GetListItems();
                string[] selectedValues          = null;

                if (helper.DataSource.Keys.Any(k => k.Equals(name, StringComparison.OrdinalIgnoreCase)))
                {
                    selectedValues = helper.DataSource.GetValue <string>(name, String.Empty)
                                     .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }

                builder.AppendLine();

                foreach (ListItem item in listItems)
                {
                    if (selectedValues != null)
                    {
                        item.Selected = selectedValues.Any(s =>
                                                           String.Equals(item.Value, s, StringComparison.OrdinalIgnoreCase));
                    }

                    HtmlElementBuilder inner = new HtmlElementBuilder("option");
                    inner.InnerText = item.Text;

                    if (item.Value != null)
                    {
                        inner.Attributes.Merge("value", item.Value, true);
                    }

                    if (item.Selected)
                    {
                        inner.Attributes.Merge("selected", "selected");
                    }

                    builder.AppendLine(inner.ToString());
                }
                outer.InnerHtml = builder.ToString();
            }
            return(outer.ToString());
        }
コード例 #11
0
ファイル: PreconditionNot.cs プロジェクト: moto2002/unityLab
 public PreconditionNot(Precondition precondition)
 {
     this.precondition = precondition;
 }
コード例 #12
0
 internal void AddPrecondition(Precondition precondition)
 {
     if (this.Preconditions == null) {
     this.Preconditions = new List<Precondition>();
     this.HasContract = true;
       }
       this.Preconditions.Add(precondition);
 }
コード例 #13
0
ファイル: Mutator.cs プロジェクト: riverar/devtools
 /// <summary>
 /// Rewrites the children of the given pre condition.
 /// </summary>
 public virtual void RewriteChildren(Precondition precondition)
 {
     this.RewriteChildren((ContractElement)precondition);
       if (precondition.ExceptionToThrow != null)
     precondition.ExceptionToThrow = this.Rewrite(precondition.ExceptionToThrow);
 }
コード例 #14
0
        private static bool TryFormatHexadecimalInvariantCultureUtf8(ulong value, Span <byte> buffer, out int bytesWritten, StandardFormat format)
        {
            Precondition.Require(format.Symbol == 'X' || format.Symbol == 'x');

            byte firstDigitOffset   = (byte)'0';
            byte firstHexCharOffset = format.Symbol == 'X' ? (byte)'A' : (byte)'a';

            firstHexCharOffset -= 10;

            // Count amount of hex digits
            var   hexDigitsCount = 1;
            ulong valueToCount   = value;

            if (valueToCount > 0xFFFFFFFF)
            {
                hexDigitsCount += 8;
                valueToCount  >>= 0x20;
            }
            if (valueToCount > 0xFFFF)
            {
                hexDigitsCount += 4;
                valueToCount  >>= 0x10;
            }
            if (valueToCount > 0xFF)
            {
                hexDigitsCount += 2;
                valueToCount  >>= 0x8;
            }
            if (valueToCount > 0xF)
            {
                hexDigitsCount++;
            }

            var bytesCount = hexDigitsCount;

            // Count leading zeros
            var leadingZerosCount = format.HasPrecision ? format.Precision - hexDigitsCount : 0;

            bytesCount += leadingZerosCount > 0 ? leadingZerosCount : 0;

            if (bytesCount > buffer.Length)
            {
                bytesWritten = 0;
                return(false);
            }

            var index = bytesCount;

            while (hexDigitsCount-- > 0)
            {
                byte digit = (byte)(value & 0xF);
                value         >>= 0x4;
                digit          += digit < 10 ? firstDigitOffset : firstHexCharOffset;
                buffer[--index] = digit;
            }

            // Write leading zeros if any
            while (leadingZerosCount-- > 0)
            {
                buffer[--index] = firstDigitOffset;
            }

            bytesWritten = bytesCount;
            return(true);
        }
コード例 #15
0
 private static HtmlElementRule Validate(HtmlElementRule rule)
 {
     Precondition.Require(rule, () => Error.ArgumentNull("rule"));
     return(rule);
 }
コード例 #16
0
 void IHttpHandler.ProcessRequest(HttpContext context)
 {
     Precondition.Require(context, () => Error.ArgumentNull("context"));
     ProcessRequest(new HttpContextWrapper(context));
 }
コード例 #17
0
 public RequireUsersAttribute(params string[] users)
 {
     Precondition.Require(users, () => Error.ArgumentNull("users"));
     _users = users;
 }
コード例 #18
0
ファイル: Contracts.cs プロジェクト: riverar/devtools
 /// <summary>
 /// A copy constructor that allocates an instance that is the same as the given template, except for its containing block.
 /// </summary>
 /// <param name="containingBlock">The containing block of the copied precondition. This should be different from the containing block of the template precondition.</param>
 /// <param name="template">The statement to copy.</param>
 private Precondition(BlockStatement containingBlock, Precondition template)
     : base(containingBlock, template)
 {
     if (template.ExceptionToThrow != null)
     this.exceptionToThrow = template.ExceptionToThrow.MakeCopyFor(containingBlock);
 }
コード例 #19
0
 public MvcHandler(RequestContext context)
 {
     Precondition.Require(context, () => Error.ArgumentNull("context"));
     _context = context;
 }
コード例 #20
0
 private static IDbDataProvider CreateProvider(IDbDataProviderFactory factory)
 {
     Precondition.Require(factory, () => Error.ArgumentNull("factory"));
     return(factory.CreateProvider());
 }
コード例 #21
0
 //-------------------------------------------------------------
 public bool Evaluate(/*in*/ BTWorkingData wData)
 {
     return((Precondition == null || Precondition.IsTrue(wData)) && OnEvaluate(wData));
 }
コード例 #22
0
 private static IValueSet EnsureValues(IValueSet values)
 {
     Precondition.Require(values, () => Error.ArgumentNull("values"));
     return(values);
 }
コード例 #23
0
ファイル: MvcForm.cs プロジェクト: ProstoA/Radischevo.Wahha
 public MvcForm(HttpResponseBase response)
 {
     Precondition.Require(response, () => Error.ArgumentNull("response"));
     _response = response;
 }
コード例 #24
0
 /// <summary>
 /// Adds a top-level rule for the attribute. In most cases, the rule is ignored.
 /// </summary>
 /// <param name="rule">A new sub-rule to add.</param>
 protected virtual HtmlAttributeRule AddAttributeRule(HtmlAttributeRule rule)
 {
     Precondition.Require(rule, () => Error.ArgumentNull("rule"));
     return(Document.AddAttributeRule(rule));
 }
コード例 #25
0
        public static bool TryFormat(this Guid value, Span <byte> buffer, Format.Parsed format, FormattingData formattingData, out int bytesWritten)
        {
            Precondition.Require(format.Symbol == Format.Symbol.G || format.Symbol == Format.Symbol.D || format.Symbol == Format.Symbol.N || format.Symbol == Format.Symbol.B || format.Symbol == Format.Symbol.P);
            bool dash = true;
            char tail = '\0';

            bytesWritten = 0;

            switch (format.Symbol)
            {
            case Format.Symbol.D:
            case Format.Symbol.G:
                break;

            case Format.Symbol.N:
                dash = false;
                break;

            case Format.Symbol.B:
                if (!TryWriteChar('{', buffer, formattingData, ref bytesWritten))
                {
                    return(false);
                }
                tail = '}';
                break;

            case Format.Symbol.P:
                if (!TryWriteChar('(', buffer, formattingData, ref bytesWritten))
                {
                    return(false);
                }
                tail = ')';
                break;

            default:
                Precondition.Require(false);     // how did we get here?
                break;
            }

            var bytes = value.ToByteArray(); // TODO: it would be nice to eliminate this allocation

            var byteFormat = new Format.Parsed()
            {
                Precision = 2, Symbol = Format.Symbol.XLowercase
            };

            if (!TryWriteByte(bytes[3], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[2], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[1], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[0], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }

            if (dash)
            {
                if (!TryWriteChar('-', buffer, formattingData, ref bytesWritten))
                {
                    return(false);
                }
            }

            if (!TryWriteByte(bytes[5], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[4], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }

            if (dash)
            {
                if (!TryWriteChar('-', buffer, formattingData, ref bytesWritten))
                {
                    return(false);
                }
            }

            if (!TryWriteByte(bytes[7], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[6], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }

            if (dash)
            {
                if (!TryWriteChar('-', buffer, formattingData, ref bytesWritten))
                {
                    return(false);
                }
            }

            if (!TryWriteByte(bytes[8], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[9], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }

            if (dash)
            {
                if (!TryWriteChar('-', buffer, formattingData, ref bytesWritten))
                {
                    return(false);
                }
            }

            if (!TryWriteByte(bytes[10], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[11], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[12], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[13], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[14], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }
            if (!TryWriteByte(bytes[15], buffer, byteFormat, formattingData, ref bytesWritten))
            {
                return(false);
            }

            if (tail != '\0')
            {
                if (!TryWriteChar(tail, buffer, formattingData, ref bytesWritten))
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #26
0
 public TemplateHelper(HtmlHelper helper)
 {
     Precondition.Require(helper, () => Error.ArgumentNull("helper"));
     _helper = helper;
 }
コード例 #27
0
 protected virtual ValidationRule <T> GetSut <T>(T value, string name)
 {
     return(Precondition.For(value, name));
 }
コード例 #28
0
 public void Add(string name, IValueProviderFactory factory)
 {
     Precondition.Require(factory, () => Error.ArgumentNull("factory"));
     _collection[name] = factory;
 }
コード例 #29
0
 protected override ValidationRule <bool> GetSut()
 {
     return(Precondition.For(ExpectedValue, "BB"));
 }
コード例 #30
0
 public static bool TryFormat(this float value, Span <byte> buffer, Format.Parsed format, FormattingData formattingData, out int bytesWritten)
 {
     Precondition.Require(format.Symbol == Format.Symbol.G);
     return(FloatFormatter.TryFormatNumber(value, true, buffer, format, formattingData, out bytesWritten));
 }
コード例 #31
0
        /// <summary>
        /// Parses an unsigned 64-bit integer from a location within a UTF-8 byte array buffer.
        /// </summary>
        /// <param name="utf8Text">The UTF-8 buffer, passed as a byte array.</param>
        /// <param name="index">The index location of the value to be parsed within the buffer.</param>
        /// <param name="value">The parsed value.</param>
        /// <param name="bytesConsumed">The length (in bytes) of the unparsed value within the UTF-8 buffer.</param>
        /// <returns>True if parsing is successful; false otherwise.</returns>
        public static bool TryParse(byte[] utf8Text, int index, out sbyte value, out int bytesConsumed)
        {
            Precondition.Require(utf8Text.Length > 0);

            value         = 0;
            bytesConsumed = 0;
            bool negative = false;
            bool signed   = false;

            if (utf8Text[index] == '-')
            {
                negative = true;
                signed   = true;
                index++;
                bytesConsumed++;
            }
            else if (utf8Text[index] == '+')
            {
                signed = true;
                index++;
                bytesConsumed++;
            }

            for (int byteIndex = index; byteIndex < utf8Text.Length; byteIndex++) // loop through the byte array
            {
                byte nextByte = utf8Text[byteIndex];
                if (nextByte < '0' || nextByte > '9') // if the next character is not a digit
                {
                    if (bytesConsumed == 1 && signed) // if the first character happened to be a '-' or a '+', we reset the byte counter so logic proceeds as normal.
                    {
                        bytesConsumed = 0;
                    }
                    if (bytesConsumed == 0)   // check to see if we've processed any digits at all
                    {
                        value = default(int); // if we haven't, set value to 0 and return false
                        return(false);
                    }
                    else
                    {
                        if (negative) // We check if the value is negative at the very end to save on comp time
                        {
                            value = (sbyte)-value;
                        }
                        return(true); // otherwise return true
                    }
                }
                sbyte candidate = (sbyte)(value * 10); // left shift the value
                candidate += (sbyte)(nextByte - '0');  // parse the current digit to a sbyte and add it to the temporary value
                if (candidate >= value)                // if it was a digit 0-9, this should be true
                {
                    value = candidate;
                }
                else // for signed types this will occur at the min values as overflow occurs during addition, so we handle that
                {
                    if (candidate == sbyte.MinValue)
                    {
                        bytesConsumed++;
                        value = candidate;
                        return(true);
                    }
                    if (negative) // We check if the value is negative at the very end to save on comp time
                    {
                        value = (sbyte)-value;
                    }
                    return(true);
                }
                bytesConsumed++; // increment the number of bytes consumed, then loop
            }

            if (negative) // We check if the value is negative at the very end to save on comp time
            {
                value = (sbyte)-value;
            }
            return(true);
        }
コード例 #32
0
        // TODO: this whole routine is too slow. It does div and mod twice, which are both costly (especially that some JITs cannot optimize it).
        // It does it twice to avoid reversing the formatted buffer, which can be tricky given it should handle arbitrary cultures.
        // One optimization I thought we could do is to do div/mod once and store digits in a temp buffer (but that would allocate). Modification to the idea would be to store the digits in a local struct
        // Another idea possibly worth tying would be to special case cultures that have constant digit size, and go back to the format + reverse buffer approach.
        private static bool TryFormatDecimal(ulong value, Span <byte> buffer, out int bytesWritten, StandardFormat format, SymbolTable symbolTable)
        {
            char symbol = char.ToUpperInvariant(format.Symbol);

            Precondition.Require(symbol == 'D' || format.Symbol == 'G' || format.Symbol == 'N');

            // Reverse value on decimal basis, count digits and trailing zeros before the decimal separator
            ulong reversedValueExceptFirst = 0;
            var   digitsCount        = 1;
            var   trailingZerosCount = 0;

            // We reverse the digits in numeric form because reversing encoded digits is hard and/or costly.
            // If value contains 20 digits, its reversed value will not fit into ulong size.
            // So reverse it till last digit (reversedValueExceptFirst will have all the digits except the first one).
            while (value >= 10)
            {
                var digit = value % 10UL;
                value = value / 10UL;

                if (reversedValueExceptFirst == 0 && digit == 0)
                {
                    trailingZerosCount++;
                }
                else
                {
                    reversedValueExceptFirst = reversedValueExceptFirst * 10UL + digit;
                    digitsCount++;
                }
            }

            bytesWritten = 0;
            int digitBytes;

            // If format is D and precision is greater than digitsCount + trailingZerosCount, append leading zeros
            if (symbol == 'D' && format.HasPrecision)
            {
                var leadingZerosCount = format.Precision - digitsCount - trailingZerosCount;
                while (leadingZerosCount-- > 0)
                {
                    if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                }
            }

            // Append first digit
            if (!symbolTable.TryEncode((SymbolTable.Symbol)value, buffer.Slice(bytesWritten), out digitBytes))
            {
                bytesWritten = 0;
                return(false);
            }
            bytesWritten += digitBytes;
            digitsCount--;

            if (symbol == 'N')
            {
                const int GroupSize = 3;

                // Count amount of digits before first group separator. It will be reset to groupSize every time digitsLeftInGroup == zero
                var digitsLeftInGroup = (digitsCount + trailingZerosCount) % GroupSize;
                if (digitsLeftInGroup == 0)
                {
                    if (digitsCount + trailingZerosCount > 0)
                    {
                        // There is a new group immediately after the first digit
                        if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes))
                        {
                            bytesWritten = 0;
                            return(false);
                        }
                        bytesWritten += digitBytes;
                    }
                    digitsLeftInGroup = GroupSize;
                }

                // Append digits
                while (reversedValueExceptFirst > 0)
                {
                    if (digitsLeftInGroup == 0)
                    {
                        if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes))
                        {
                            bytesWritten = 0;
                            return(false);
                        }
                        bytesWritten     += digitBytes;
                        digitsLeftInGroup = GroupSize;
                    }

                    var nextDigit = reversedValueExceptFirst % 10UL;
                    reversedValueExceptFirst = reversedValueExceptFirst / 10UL;

                    if (!symbolTable.TryEncode((SymbolTable.Symbol)nextDigit, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                    digitsLeftInGroup--;
                }

                // Append trailing zeros if any
                while (trailingZerosCount-- > 0)
                {
                    if (digitsLeftInGroup == 0)
                    {
                        if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes))
                        {
                            bytesWritten = 0;
                            return(false);
                        }
                        bytesWritten     += digitBytes;
                        digitsLeftInGroup = GroupSize;
                    }

                    if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                    digitsLeftInGroup--;
                }
            }
            else
            {
                while (reversedValueExceptFirst > 0)
                {
                    var bufferSlice = buffer.Slice(bytesWritten);
                    var nextDigit   = reversedValueExceptFirst % 10UL;
                    reversedValueExceptFirst = reversedValueExceptFirst / 10UL;
                    if (!symbolTable.TryEncode((SymbolTable.Symbol)nextDigit, bufferSlice, out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                }

                // Append trailing zeros if any
                while (trailingZerosCount-- > 0)
                {
                    if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                }
            }

            // If format is N and precision is not defined or is greater than zero, append trailing zeros after decimal point
            if (symbol == 'N')
            {
                int trailingZerosAfterDecimalCount = format.HasPrecision ? format.Precision : 2;

                if (trailingZerosAfterDecimalCount > 0)
                {
                    if (!symbolTable.TryEncode(SymbolTable.Symbol.DecimalSeparator, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;

                    while (trailingZerosAfterDecimalCount-- > 0)
                    {
                        if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes))
                        {
                            bytesWritten = 0;
                            return(false);
                        }
                        bytesWritten += digitBytes;
                    }
                }
            }

            return(true);
        }
コード例 #33
0
 protected bool IsPreconditionMet()
 {
     return(Precondition == null || Precondition.IsTrue());
 }
コード例 #34
0
ファイル: Copier.cs プロジェクト: riverar/devtools
 /// <summary>
 /// Get the mutable copy of a precondition.
 /// </summary>
 /// <param name="precondition"></param>
 /// <returns></returns>
 public virtual Precondition GetMutableCopy(IPrecondition precondition)
 {
     object cachedValue;
       if (this.cache.TryGetValue(precondition, out cachedValue))
     return (Precondition)cachedValue;
       var result = new Precondition(precondition);
       // Probably not necessary, no two postconditions are shared.
       this.cache.Add(precondition, result);
       this.cache.Add(result, result);
       return result;
 }
コード例 #35
0
 public bool TryWriteDigit(ulong digit, Span <byte> buffer, out int bytesWritten)
 {
     Precondition.Require(digit < 10);
     return(TryWriteDigitOrSymbol(digit, buffer, out bytesWritten));
 }
コード例 #36
0
 public HttpContentTypeAttribute(string contentType)
 {
     Precondition.Defined(contentType, () => Error.ArgumentNull("contentType"));
     _contentType = contentType;
 }
コード例 #37
0
 public SingleMappedAssociationLoader(DbCommandDescriptor command)
 {
     Precondition.Require(command, () => Error.ArgumentNull("command"));
     _command = command;
 }
コード例 #38
0
ファイル: PreconditionOr.cs プロジェクト: moto2002/unityLab
 public PreconditionOr(Precondition precondition0, Precondition precondition1)
 {
     this.precondition0 = precondition0;
     this.precondition1 = precondition1;
 }
コード例 #39
0
ファイル: Mutator.cs プロジェクト: riverar/devtools
 /// <summary>
 /// Visits the specified precondition.
 /// </summary>
 /// <param name="precondition">The precondition.</param>
 public virtual IPrecondition Visit(IPrecondition precondition)
 {
     Precondition mutablePrecondition = precondition as Precondition;
       if (!this.copyOnlyIfNotAlreadyMutable || mutablePrecondition == null)
     mutablePrecondition = new Precondition(precondition);
       return this.Visit(mutablePrecondition);
 }