Udger.Parser.PerlRegExpConverter.CountRange C# (CSharp) Method

CountRange() static private method

Takes endpoints of a range and returns string containing appropriate characters.
static private CountRange ( char firstCharacter, char secondCharacter, string &characters, int &result, Encoding encoding ) : bool
firstCharacter char First endpoint of a range.
secondCharacter char Second endpoint of a range.
characters string String containing all characters that are to be in the range.
result int Integer specifying an error. Value 1 means characters specified cannot /// be expressed in current encoding, value of 2 first character is greater than second.
encoding System.Text.Encoding
return bool
        internal static bool CountRange(char firstCharacter, char secondCharacter, out string characters, out int result, Encoding encoding)
        {
            // initialize out parameters
            characters = null;
            result = 0;

            char[] chars = new char[2];
            chars[0] = firstCharacter;
            chars[1] = secondCharacter;

            byte[] two_bytes = new byte[encoding.GetMaxByteCount(2)];

            // convert endpoints and test if characters are "normal" - they can be stored in one byte
            if (encoding.GetBytes(chars, 0, 2, two_bytes, 0) != 2)
            {
                result = 1;
                return false;
            }

            if (two_bytes[0] > two_bytes[1])
            {
                result = 2;
                return false;
            }

            // array for bytes that will be converted to unicode string
            byte[] bytes = new byte[two_bytes[1] - two_bytes[0] + 1];

            int i = 0;
            for (int ch = two_bytes[0]; ch <= two_bytes[1]; i++, ch++)
            {
                // casting to byte is OK, ch is always in byte range thanks to ch <= two_bytes[1] condition
                bytes[i] = (byte)ch;
            }

            characters = encoding.GetString(bytes, 0, i);
            return true;
        }