Ejemplo n.º 1
0
        public void TestRanges()
        {
            const string test   = "SomeEnum ::= Unsigned32 (8 | 10 ..20 | 31 .. 60 )";
            Lexer        lexer  = new Lexer();
            StringReader reader = new StringReader(test);

            lexer.Parse(reader);
            string name = lexer.NextSymbol.ToString();

            lexer.NextSymbol.Expect(Symbol.Assign);
            lexer.NextSymbol.Expect(Symbol.Unsigned32);

            UnsignedType i = new UnsignedType("module", "name", lexer);

            Assert.IsTrue(i.Contains(8));
            Assert.IsTrue(i.Contains(10));
            Assert.IsTrue(i.Contains(15));
            Assert.IsTrue(i.Contains(20));
            Assert.IsTrue(i.Contains(35));
            Assert.IsFalse(i.Contains(4));
            Assert.IsFalse(i.Contains(-9));
            Assert.IsFalse(i.Contains(25));
            Assert.IsFalse(i.Contains(61));
        }
        private static IEnumerable <byte> UintToUtype(uint number, UnsignedType type)
        {
            switch (type)
            {
            case UnsignedType.Byte:
                yield return((byte)number);

                break;

            case UnsignedType.Ushort:
                foreach (var b in BitConverter.GetBytes((ushort)number))
                {
                    yield return(b);
                }
                break;

            case UnsignedType.Uint:
                foreach (var b in BitConverter.GetBytes(number))
                {
                    yield return(b);
                }
                break;
            }
        }
Ejemplo n.º 3
0
        private static SnmpScalarNode GenerateSnmpScalarNode(ObjectType ote, SnmpTreeNode parentNode, bool ignoreAccessibleFlag = false)
        {
            SnmpScalarNode result;

            ITypeAssignment mibType = ote.BaseType;
            IntegerType     it      = (mibType as IntegerType);

            if (it != null)
            {
                if (ote.ReferredType.Name == Symbol.TruthValue.ToString())
                {
                    result = new SnmpScalarNodeTruthValue(parentNode);
                }
                else if ((it.Type == IntegerType.Types.Integer) || (it.Type == IntegerType.Types.Integer32))
                {
                    result = new SnmpScalarNodeInt(parentNode);
                }
                else
                {
                    Console.WriteLine(String.Format("Unsupported IntegerType '{0}'!", it.Type));
                    return(null);
                }
                if (it.IsEnumeration)
                {
                    result.Restrictions.AddRange(CreateRestrictions(it.Enumeration));
                }
                else
                {
                    result.Restrictions.AddRange(CreateRestrictions(it.Ranges));
                }
            }
            else
            {
                UnsignedType ut = (mibType as UnsignedType);
                if (ut != null)
                {
                    if ((ut.Type == UnsignedType.Types.Unsigned32) ||
                        (ut.Type == UnsignedType.Types.Gauge32))
                    {
                        result = new SnmpScalarNodeUint(SnmpDataType.Gauge, parentNode);
                    }
                    else if (ut.Type == UnsignedType.Types.Counter32)
                    {
                        result = new SnmpScalarNodeUint(SnmpDataType.Counter, parentNode);
                    }
                    else if (ut.Type == UnsignedType.Types.TimeTicks)
                    {
                        result = new SnmpScalarNodeUint(SnmpDataType.TimeTicks, parentNode);
                    }
                    else if (ut.Type == UnsignedType.Types.Counter64)
                    {
                        result = new SnmpScalarNodeCounter64(parentNode);
                        if ((ut.Ranges != null) && (ut.Ranges.Count > 0))
                        {
                            Console.WriteLine(String.Format("Generation of ranges is not supported for Counter64 type!"));
                            return(null);
                        }
                    }
                    else
                    {
                        Console.WriteLine(String.Format("Unsupported UnsignedType '{0}'!", ut.Type));
                        return(null);
                    }
                    result.Restrictions.AddRange(CreateRestrictions(ut.Ranges));
                }
                else if (mibType is IpAddressType)
                {
                    result = new SnmpScalarNodeOctetString(SnmpDataType.IpAddress, parentNode);
                    result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size));
                }
                else if (mibType is OpaqueType)
                {
                    result = new SnmpScalarNodeOctetString(SnmpDataType.Opaque, parentNode);
                    result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size));
                }
                else if (mibType is OctetStringType)
                {
                    result = new SnmpScalarNodeOctetString(SnmpDataType.OctetString, parentNode);
                    result.Restrictions.AddRange(CreateRestrictions((mibType as OctetStringType).Size));
                }
                else if (mibType is ObjectIdentifierType)
                {
                    result = new SnmpScalarNodeObjectIdentifier(parentNode);
                }
                else if (mibType is BitsType)
                {
                    result = new SnmpScalarNodeBits(parentNode, (uint)((mibType as BitsType).Map.GetHighestValue() + 1));
                    result.Restrictions.AddRange(CreateRestrictions(mibType as BitsType));
                }
                else
                {
                    TypeAssignment ta = mibType as TypeAssignment;
                    if (ta != null)
                    {
                        Console.WriteLine(String.Format("Unsupported BaseType: Module='{0}', Name='{1}', Type='{2}'!", ta.Module.Name, ta.Name, ta.Type));
                    }
                    else
                    {
                        Console.WriteLine(String.Format("Unsupported BaseType: Module='{0}', Name='{1}'!", mibType.Module, mibType.Name));
                    }

                    return(null);
                }
            }

            result.Name = _alphaNumericRegex.Replace(ote.Name, "");
            result.Oid  = ote.Value;

            if (ote.Access == MaxAccess.readWrite)
            {
                result.AccessMode = SnmpAccessMode.ReadWrite;
            }
            else if (ote.Access == MaxAccess.readOnly)
            {
                result.AccessMode = SnmpAccessMode.ReadOnly;
            }
            else if (ote.Access == MaxAccess.readCreate)
            {
                result.AccessMode = SnmpAccessMode.ReadOnly;
            }
            else if (ignoreAccessibleFlag && (ote.Access == MaxAccess.notAccessible))
            {
                result.AccessMode = SnmpAccessMode.NotAccessible;
            }
            else
            {
                // not accessible or unsupported access type
                return(null);
            }

            return(result);
        }
        private static IEnumerable <byte> EncodeWithAutoDictionary(string SourceFilePath)
        {
            Dictionary <char, uint> chars = new Dictionary <char, uint>();

            using (StreamReader sr = new StreamReader(SourceFilePath))
            {
                HashSet <char> hs = new HashSet <char>();
                while (sr.Peek() >= 0)
                {
                    hs.Add((char)sr.Read());
                }

                uint i = 0;
                chars = hs.ToDictionary(c => c, c => i++);
            }

            long textLength = new FileInfo(SourceFilePath).Length;
            int  charsCount = chars.Count();

            char[] returnCharsArray = new char[charsCount];
            foreach (var entry in chars)
            {
                returnCharsArray[entry.Value] = entry.Key;
            }
            foreach (var b in BitConverter.GetBytes(charsCount))
            {
                yield return(b);
            }
            foreach (var c in returnCharsArray)
            {
                foreach (var b in BitConverter.GetBytes(c))
                {
                    yield return(b);
                }
            }

            UnsignedType uType = UnsignedType.Uint;

            if (charsCount + textLength < 256)
            {
                uType = UnsignedType.Byte;
            }
            else if (charsCount + textLength < 65536)
            {
                uType = UnsignedType.Ushort;
            }
            else
            {
                uType = UnsignedType.Uint;
            }
            yield return((byte)uType);

            using (StreamReader sr = new StreamReader(SourceFilePath))
            {
                Dictionary <string, uint> words = new Dictionary <string, uint>();
                uint   i = (uint)charsCount;
                string w = ((char)sr.Read()).ToString();
                while (sr.Peek() >= 0)
                {
                    char entry = (char)sr.Read();
                    if (words.ContainsKey(w + entry))
                    {
                        w = w + entry;
                    }
                    else
                    {
                        if (w.Length == 1)
                        {
                            foreach (var b in UintToUtype(chars[w.First()], uType))
                            {
                                yield return(b);
                            }
                        }
                        else
                        {
                            foreach (var b in UintToUtype(words[w], uType))
                            {
                                yield return(b);
                            }
                        }
                        words.Add(w + entry, i++);
                        w = entry.ToString();
                    }
                }
                if (w.Length == 1)
                {
                    foreach (var b in UintToUtype(chars[w.First()], uType))
                    {
                        yield return(b);
                    }
                }
                else
                {
                    foreach (var b in UintToUtype(words[w], uType))
                    {
                        yield return(b);
                    }
                }
            }
        }
        private static IEnumerable <byte> EncodeUTF8Dictionary(string SourceFilePath)
        {
            long textLength = new FileInfo(SourceFilePath).Length;
            int  charsCount = 256;

            UnsignedType uType = UnsignedType.Uint;

            if (charsCount + textLength < 256)
            {
                uType = UnsignedType.Byte;
            }
            else if (charsCount + textLength < 65536)
            {
                uType = UnsignedType.Ushort;
            }
            else
            {
                uType = UnsignedType.Uint;
            }
            yield return((byte)uType);

            using (StreamReader sr = new StreamReader(SourceFilePath))
            {
                Dictionary <string, uint> words = new Dictionary <string, uint>();
                uint   i = (uint)charsCount;
                string w = ((char)sr.Read()).ToString();
                while (sr.Peek() >= 0)
                {
                    char entry = (char)sr.Read();
                    if (words.ContainsKey(w + entry))
                    {
                        w = w + entry;
                    }
                    else
                    {
                        if (w.Length == 1)
                        {
                            foreach (var b in UintToUtype(BitConverter.ToUInt32(Encoding.UTF8.GetBytes(w)), uType))
                            {
                                yield return(b);
                            }
                        }
                        else
                        {
                            foreach (var b in UintToUtype(words[w], uType))
                            {
                                yield return(b);
                            }
                        }
                        words.Add(w + entry, i++);
                        w = entry.ToString();
                    }
                }
                if (w.Length == 1)
                {
                    foreach (var b in UintToUtype(BitConverter.ToUInt32(Encoding.UTF8.GetBytes(w)), uType))
                    {
                        yield return(b);
                    }
                }
                else
                {
                    foreach (var b in UintToUtype(words[w], uType))
                    {
                        yield return(b);
                    }
                }
            }
        }
        //Основной метод для кодирования
        internal static IEnumerable <byte> EncodeWithAutoDictionary(string SourceFilePath)
        {
            //Словарь фраз длиной в 1 символ
            Dictionary <char, uint> chars = new Dictionary <char, uint>();

            //Заполнение словаря всеми уникальными символами
            using (StreamReader sr = new StreamReader(SourceFilePath))
            {
                HashSet <char> hs = new HashSet <char>();
                while (sr.Peek() >= 0)
                {
                    hs.Add((char)sr.Read());
                }

                uint i = 0;
                chars = hs.ToDictionary(c => c, c => i++);
            }

            //Кодирование словаря
            //Перед словарём четырьми битами передаётся количество символов в нём
            //Затем код каждого символа длиной по 2 бита
            int charsCount = chars.Count();

            char[] returnCharsArray = new char[charsCount];
            foreach (var entry in chars)
            {
                returnCharsArray[entry.Value] = entry.Key;
            }
            foreach (var b in BitConverter.GetBytes(charsCount))
            {
                yield return(b);
            }
            foreach (var c in returnCharsArray)
            {
                foreach (var b in BitConverter.GetBytes(c))
                {
                    yield return(b);
                }
            }

            //Определение того, сколько байтов необходимо выделить на одну запись
            //в словаре, в зависимости от максимальной предполагаемой длины словаря
            long         textLength = new FileInfo(SourceFilePath).Length;
            UnsignedType uType      = UnsignedType.Uint;

            if (charsCount + textLength < 256)
            {
                uType = UnsignedType.Byte;
            }
            else if (charsCount + textLength < 65536)
            {
                uType = UnsignedType.Ushort;
            }
            else
            {
                uType = UnsignedType.Uint;
            }
            yield return((byte)uType);

            using (StreamReader sr = new StreamReader(SourceFilePath))
            {
                //Инициализация словаря фраз длиной от двух символов
                Dictionary <string, uint> words = new Dictionary <string, uint>();

                //Номер следующей записи в словаре
                uint i = (uint)charsCount;
                //
                string w = ((char)sr.Read()).ToString();

                //Пока не достигнут конец потока
                while (sr.BaseStream.Position != sr.BaseStream.Length)
                {
                    //Прочитать следующий символ
                    char entry = (char)sr.Read();
                    //Если фраза с новым символом содержится в словаре,
                    //перейти к следующему символу
                    if (words.ContainsKey(w + entry))
                    {
                        w = w + entry;
                    }
                    //Иначе добавить в словарь фразу с новым символом
                    //и принять за фразу новый символ, отправив фразу в поток
                    else
                    {
                        if (w.Length == 1)
                        {
                            foreach (var b in UintToUtype(chars[w.First()], uType))
                            {
                                yield return(b);
                            }
                        }
                        else
                        {
                            foreach (var b in UintToUtype(words[w], uType))
                            {
                                yield return(b);
                            }
                        }
                        words.Add(w + entry, i++);
                        w = entry.ToString();
                    }
                }
                //Кодирование последней фразы
                if (w.Length == 1)
                {
                    foreach (var b in UintToUtype(chars[w.First()], uType))
                    {
                        yield return(b);
                    }
                }
                else
                {
                    foreach (var b in UintToUtype(words[w], uType))
                    {
                        yield return(b);
                    }
                }
            }
        }