Exemple #1
0
        public PxEntry UElement()
        {
            if (this.typ.Vid != PTypeEnumeration.union)
            {
                throw new Exception("Err: Element() need union");
            }
            fis.SetOffset(offset);
            int        tag = fis.br.ReadByte();
            PTypeUnion ptu = ((PTypeUnion)this.typ);

            if (tag < 0 || tag >= ptu.Variants.Length)
            {
                throw new Exception("Err: tag is out of bound");
            }
            PType tel = ptu.Variants[tag].Type;
            long  off;

            if (tel.IsAtom)
            {
                off = offset + 1;
            }
            else
            {
                off = fis.br.ReadInt64();
            }
            return(new PxEntry(tel, off, fis));
        }
        public TripleStore32(Func <Stream> stream_gen, string tmp_dir)
        {
            // Тип Object Variants
            PType tp_ov = new PTypeUnion(
                new NamedType("dummy", new PType(PTypeEnumeration.none)),
                new NamedType("iri", new PType(PTypeEnumeration.integer)),
                new NamedType("str", new PType(PTypeEnumeration.sstring)));

            tp_triple = new PTypeRecord(
                new NamedType("subj", new PType(PTypeEnumeration.integer)),
                new NamedType("pred", new PType(PTypeEnumeration.integer)),
                new NamedType("obj", tp_ov));
            table = new UniversalSequenceBase(tp_triple, stream_gen());
            var spo_comparer = Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                object[] aa = (object[])a; object[] bb = (object[])b;
                int cmp = ((int)aa[0]).CompareTo((int)bb[0]);
                return(cmp);
            }));

            keyFunc   = tri => (int)((object[])tri)[0];
            index_spo = new UniversalSequenceCompKey32(stream_gen(), keyFunc, spo_comparer, table);
            indexTest = new IndexViewImmutable(stream_gen, table,
                                               Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                object[] aa = (object[])a; object[] bb = (object[])b;
                int cmp     = ((int)aa[0]).CompareTo((int)bb[0]);
                return(cmp);
            })), tmp_dir, 20_000_000
                                               );
        }
Exemple #3
0
        private void InitTypes()
        {
            tp_entity = new PType(PTypeEnumeration.integer);
            PType tp_rliteral = new PTypeUnion(
                new NamedType("void", new PType(PTypeEnumeration.none)),
                new NamedType("integer", new PType(PTypeEnumeration.integer)),
                new NamedType("string", new PTypeRecord(
                                  new NamedType("s", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("l", new PType(PTypeEnumeration.sstring)))),
                new NamedType("date", new PType(PTypeEnumeration.longinteger)));

            tp_otriple_seq = new PTypeSequence(new PTypeRecord(
                                                   new NamedType("subject", tp_entity),
                                                   new NamedType("predicate", tp_entity),
                                                   new NamedType("object", tp_entity)));
            tp_dtriple_seq = new PTypeSequence(new PTypeRecord(
                                                   new NamedType("subject", tp_entity),
                                                   new NamedType("predicate", tp_entity),
                                                   new NamedType("data", tp_rliteral)));
            // Тип для экономного выстраивания индекса s-p для dtriples
            tp_dtriple_spf = new PTypeSequence(new PTypeRecord(
                                                   new NamedType("subject", tp_entity),
                                                   new NamedType("predicate", tp_entity),
                                                   new NamedType("offset", new PType(PTypeEnumeration.longinteger))));
        }
Exemple #4
0
        internal object ScanObject(PType typ)
        {
            switch (typ.Vid)
            {
            case PTypeEnumeration.none: return(null);

            case PTypeEnumeration.boolean: return(br.ReadByte());

            case PTypeEnumeration.integer: return(br.ReadInt32());

            case PTypeEnumeration.longinteger: return(br.ReadInt64());

            case PTypeEnumeration.real: return(br.ReadDouble());

            case PTypeEnumeration.@byte: return(br.ReadByte());

            case PTypeEnumeration.sstring:
            {
                //int len = br.ReadInt32();
                //char[] chrs = br.ReadChars(len);
                //return new string(chrs);
                return(br.ReadString());
            }

            case PTypeEnumeration.record:
            {
                PTypeRecord r_tp   = (PTypeRecord)typ;
                object[]    fields = new object[r_tp.Fields.Length];
                for (int i = 0; i < r_tp.Fields.Length; i++)
                {
                    fields[i] = ScanObject(r_tp.Fields[i].Type);
                }
                return(fields);
            }

            case PTypeEnumeration.sequence:
            {
                PTypeSequence mts  = (PTypeSequence)typ;
                PType         tel  = mts.ElementType;
                long          llen = br.ReadInt64();
                object[]      els  = new object[llen];
                for (long ii = 0; ii < llen; ii++)
                {
                    els[ii] = ScanObject(tel);
                }
                return(els);
            }

            case PTypeEnumeration.union:
            {
                PTypeUnion mtu = (PTypeUnion)typ;
                int        v   = br.ReadByte();
                PType      mt  = mtu.Variants[v].Type;
                return(new object[] { v, ScanObject(mt) });
            }

            default: throw new Exception("Err in TPath ScanObject(): type is not implemented " + typ.Vid);
            }
        }
Exemple #5
0
        public PaEntry UElementUnchecked(int tag)
        {
            PTypeUnion ptu = ((PTypeUnion)this.tp);

            if (tag < 0 || tag >= ptu.Variants.Length)
            {
                throw new Exception("Err: tag is out of bound");
            }
            PType tel = ptu.Variants[tag].Type;

            return(new PaEntry(tel, offset + 1, cell));
        }
Exemple #6
0
        private static void Test_Mag_Store()
        {
            string path = "mag_data/";

            Console.WriteLine("Start mag Store test");
            PType tp_ov = new PTypeUnion(
                new NamedType("dummy", new PType(PTypeEnumeration.none)),
                new NamedType("iri", new PType(PTypeEnumeration.integer)),
                new NamedType("str", new PType(PTypeEnumeration.sstring)));
            // Тип триплепта
            PType tp_triple = new PTypeRecord(
                //new NamedType("id", new PType(PTypeEnumeration.integer)), // Возможно, это временное решение
                new NamedType("subj", new PType(PTypeEnumeration.integer)),
                new NamedType("pred", new PType(PTypeEnumeration.integer)),
                new NamedType("obj", tp_ov));

            using (var table = File.Open(path + "triples.pac", FileMode.OpenOrCreate))
                using (var index1 = File.Open(path + "index1.pac", FileMode.OpenOrCreate))
                    using (var index2 = File.Open(path + "index2.pac", FileMode.OpenOrCreate))
                    {
                        Mag_Store store    = new Mag_Store(table, index1, index2);
                        int       nrecords = 1_000_000;
                        T.Restart();
                        // codes: 0 - <type>, 1 - <person>, 2 - <name>, 3... persons
                        var flow = Enumerable.Range(0, nrecords).SelectMany(i => new object[]
                        {
                            // субъект, предикат, объект
                            new object[] { i + 3, 0, new object[] { 1, 1 } },
                            new object[] { i + 3, 2, new object[] { 2, "Pupkin" + i } },
                        }).ToArray();
                        store.Load(flow);
                        T.Stop();
                        Console.WriteLine($"Load of {nrecords * 2} triples ok. Duration={T.ElapsedMilliseconds}");

                        var query = store.GetTriplesBySubject(nrecords * 2 / 3).ToArray();
                        //Console.WriteLine(query.Count());
                        foreach (var q in query)
                        {
                            Console.WriteLine(tp_triple.Interpret(q));
                        }

                        int    nprobes = 1000;
                        Random rnd     = new Random();
                        T.Restart();
                        for (int i = 0; i < nprobes; i++)
                        {
                            int code = rnd.Next(nrecords);
                            store.GetTriplesBySubject(code).Count();
                        }
                        T.Stop();
                        Console.WriteLine($"GetTriplesBySubject {nprobes} times. Duration={T.ElapsedMilliseconds}");
                    }
        }
Exemple #7
0
 // Техническая процедура Пропускает поле, выдает адрес, следующий за ним. Указатель никуда не установлен
 private long Skip(PType tp, long off)
 {
     if (tp.HasNoTail)
     {
         return(off + tp.HeadSize);
     }
     if (tp.Vid == PTypeEnumeration.sstring)
     {
         long offout;
         cell.ReadString(off, out offout);
         return(offout);
     }
     if (tp.Vid == PTypeEnumeration.record)
     {
         long        field_offset = off;
         PTypeRecord mtr          = (PTypeRecord)tp;
         foreach (var pa in mtr.Fields)
         {
             field_offset = Skip(pa.Type, field_offset);
         }
         return(field_offset);
     }
     if (tp.Vid == PTypeEnumeration.sequence)
     {
         PTypeSequence mts  = (PTypeSequence)tp;
         PType         tel  = mts.ElementType;
         long          llen = cell.ReadLong(off);
         if (tel.HasNoTail)
         {
             return(off + 8 + llen * tel.HeadSize);
         }
         long element_offset = off + 8;
         for (long ii = 0; ii < llen; ii++)
         {
             element_offset = Skip(tel, element_offset);
         }
         return(element_offset);
     }
     if (tp.Vid == PTypeEnumeration.union)
     {
         PTypeUnion mtu = (PTypeUnion)tp;
         int        v   = cell.ReadByte(off);
         if (v < 0 || v >= mtu.Variants.Length)
         {
             throw new Exception("Err in Skip (TPath-formula): wrong variant for union " + v);
         }
         PType mt = mtu.Variants[v].Type;
         return(Skip(mt, off + 1));
     }
     throw new Exception("Assert err: 2874");
 }
Exemple #8
0
        /// <summary>
        ///  Тип
        /// BTree<T> = empty^none,
        /// pair^{element: T, less: BTree<T>, more: BTree<T>};
        /// </summary>
        /// <param name="tpElement"></param>
        /// <returns></returns>
        private static PTypeUnion PTypeTree(PType tpElement)
        {
            var tpBtree = new PTypeUnion();

            tpBtree.Variants = new[]
            {
                new NamedType("empty", new PType(PTypeEnumeration.none)),
                new NamedType("pair", new PTypeRecord(
                                  new NamedType("element", tpElement),
                                  new NamedType("less", tpBtree),
                                  new NamedType("more", tpBtree),
                                  //1 - слева больше, -1 - справа больше.
                                  new NamedType("balance", new PType(PTypeEnumeration.integer))))
            };
            return(tpBtree);
        }
Exemple #9
0
        private void InitTypes()
        {
            PType tp_rliteral = new PTypeUnion(
                new NamedType("void", new PType(PTypeEnumeration.none)),
                new NamedType("integer", new PType(PTypeEnumeration.integer)),
                new NamedType("string", new PTypeRecord(
                                  new NamedType("s", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("l", new PType(PTypeEnumeration.sstring)))),
                new NamedType("date", new PType(PTypeEnumeration.longinteger)));

            tp_otriple_seq = new PTypeSequence(new PTypeRecord(
                                                   new NamedType("subject", new PType(PTypeEnumeration.sstring)),
                                                   new NamedType("predicate", new PType(PTypeEnumeration.sstring)),
                                                   new NamedType("object", new PType(PTypeEnumeration.sstring))));
            tp_dtriple_seq = new PTypeSequence(new PTypeRecord(
                                                   new NamedType("subject", new PType(PTypeEnumeration.sstring)),
                                                   new NamedType("predicate", new PType(PTypeEnumeration.sstring)),
                                                   new NamedType("data", tp_rliteral)));
        }
Exemple #10
0
        public PxEntry UElementUnchecked(int tag)
        {
            PTypeUnion ptu = ((PTypeUnion)this.typ);

            if (tag < 0 || tag >= ptu.Variants.Length)
            {
                throw new Exception("Err: tag is out of bound");
            }
            PType tel = ptu.Variants[tag].Type;
            long  off;

            if (tel.IsAtom)
            {
                off = offset + 1;
            }
            else
            {
                fis.SetOffset(offset + 1);
                off = fis.br.ReadInt64();
            }
            return(new PxEntry(tel, off, fis));
        }
Exemple #11
0
        public static void Test()
        {
            PType tp_point = new PTypeRecord(
                new NamedType("x", new PType(PTypeEnumeration.real)),
                new NamedType("y", new PType(PTypeEnumeration.real)));
            PType tp_figure = new PTypeUnion(
                new NamedType("nothing", new PType(PTypeEnumeration.none)),
                new NamedType("point", tp_point),
                new NamedType("polygon", new PTypeSequence(tp_point)),
                new NamedType("circle", new PTypeRecord(
                                  new NamedType("center", tp_point),
                                  new NamedType("radius", new PType(PTypeEnumeration.real)))));
            PType  tp_sequ = new PTypeSequence(tp_figure);
            object sequ    = new object[]
            {
                new object[] { 1, new object[] { 3.5, 7.8 } },
                new object[] { 2, new object[] {
                                   new object[] { 0.0, 0.0 }, new object[] { 1.0, 0.0 }, new object[] { 1.0, 1.0 }, new object[] { 0.0, 1.0 }
                               } },
                new object[] { 3, new object[] { new object[] { 5.0, 5.0 }, 4.99 } }
            };

            // Выполним текстовую сериализацию
            TextFlow.Serialize(Console.Out, sequ, tp_sequ);
            Console.WriteLine();
            // Создадим Stream, сделаем бинарную сериализацию, будем считать, что это файл
            Stream stream = new MemoryStream();

            ByteFlow.Serialize(new BinaryWriter(stream), sequ, tp_sequ);
            // Десериализуем стрим (бинарный файл)
            stream.Position = 0L;
            object sequ_1 = ByteFlow.Deserialize(new BinaryReader(stream), tp_sequ);

            // Проверим полученное значение
            Console.WriteLine(tp_sequ.Interpret(sequ_1));
        }
Exemple #12
0
        public TripleStoreInt32_(Func <Stream> stream_gen)
        {
            // Тип Object Variants
            PType tp_ov = new PTypeUnion(
                new NamedType("dummy", new PType(PTypeEnumeration.none)),
                new NamedType("iri", new PType(PTypeEnumeration.integer)),
                new NamedType("str", new PType(PTypeEnumeration.sstring)));
            PType tp_triple = new PTypeRecord(
                new NamedType("subj", new PType(PTypeEnumeration.integer)),
                new NamedType("pred", new PType(PTypeEnumeration.integer)),
                new NamedType("obj", tp_ov));

            table   = new UniversalSequenceBase(tp_triple, stream_gen());
            s_index = new IndexKey32CompImm(stream_gen, table, ob => (int)((object[])ob)[0], null);
            string             selected_chars = "!\"#$%&\'()*+,-./0123456789:;<=>?@abcdefghjklmnopqrstuwxyz{|}~абвгдежзийклмнопрстуфхцчшщъыьэюяё";
            Func <object, int> halfKeyFun     = ob =>
            {
                object[] tri  = (object[])ob;
                object[] pair = (object[])tri[2];
                int      tg   = (int)pair[0];
                if (tg == 1) // iri
                {
                    return(1 - (int)pair[1]);
                }
                else if (tg == 2) // str
                {
                    string s   = (string)pair[1];
                    int    len = s.Length;
                    var    chs = s.ToCharArray()
                                 .Concat(Enumerable.Repeat(' ', len < 4 ? 4 - len : 0))
                                 .Take(4)
                                 .Select(ch =>
                    {
                        int ind = selected_chars.IndexOf(ch);
                        if (ind == -1)
                        {
                            ind = 0;                // неизвестный символ помечается как '!'
                        }
                        return(ind);
                    }).ToArray();
                    return((chs[0] << 24) | (chs[1] << 16) | (chs[2] << 8) | chs[3]);
                }
                throw new Exception("Err: 292333");
            };

            Test_keyfun = halfKeyFun;
            Comparer <object> comp = Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                object[] aa = (object[])((object[])a)[2];
                object[] bb = (object[])((object[])b)[2];
                int a1 = (int)aa[0];
                int b1 = (int)bb[0];
                int cmp = a1.CompareTo(b1);
                if (cmp != 0)
                {
                    return(cmp);
                }
                if (a1 == 1)
                {
                    return(((int)aa[1]).CompareTo(((int)bb[1])));
                }
                return(((string)aa[1]).CompareTo(((string)bb[1])));
            }));

            o_index = new IndexKey32CompImm(stream_gen, table, halfKeyFun, comp);
        }
Exemple #13
0
        /// <summary>
        /// Добавляет в поток бинарного райтера байтовую сериализацию объектного представления значения
        /// типа tp
        /// </summary>
        /// <param name="typ"></param>
        /// <param name="bw"></param>
        /// <param name="valu"></param>
        public static void SetPO(PType typ, System.IO.BinaryWriter bw, object valu)
        {
            switch (typ.Vid)
            {
            case PTypeEnumeration.none: return;

            case PTypeEnumeration.boolean: bw.Write((bool)valu); return;

            case PTypeEnumeration.integer: bw.Write((int)valu); return;

            case PTypeEnumeration.longinteger: bw.Write((long)valu); return;

            case PTypeEnumeration.real: bw.Write((double)valu); return;

            case PTypeEnumeration.@byte: bw.Write((byte)valu); return;

            case PTypeEnumeration.fstring:
            {
                throw new Exception("Unimplemented variant fstring in PaCell.SetPObject()");
            }

            case PTypeEnumeration.sstring:
            {
                string str = (string)valu;
                //bw.Write(str.Length);
                //bw.Write(str.ToCharArray());
                bw.Write(str);
                return;
            }

            case PTypeEnumeration.record:
            {
                PTypeRecord r_tp   = (PTypeRecord)typ;
                object[]    fields = (object[])valu;
                for (int i = 0; i < r_tp.Fields.Length; i++)
                {
                    SetPO(r_tp.Fields[i].Type, bw, fields[i]);
                }
                return;
            }

            case PTypeEnumeration.sequence:
            {
                PTypeSequence mts  = (PTypeSequence)typ;
                PType         tel  = mts.ElementType;
                object[]      els  = (object[])valu;
                long          llen = els.Length;
                bw.Write(llen);
                for (long ii = 0; ii < llen; ii++)
                {
                    SetPO(tel, bw, els[ii]);
                }
                return;
            }

            case PTypeEnumeration.union:
            {
                PTypeUnion mtu  = (PTypeUnion)typ;
                object[]   pair = (object[])valu;
                int        v    = (int)pair[0];
                bw.Write((byte)v);
                PType mt = mtu.Variants[v].Type;
                SetPO(mt, bw, pair[1]); return;
            }

            default: throw new Exception("Err in TPath SetPO(): type is not implemented " + typ.Vid);
            }
        }
Exemple #14
0
        public TripleStoreInt32(Func <Stream> stream_gen)
        {
            // сначала таблица имен
            nt = new Nametable32(stream_gen);
            // Тип Object Variants
            PType tp_ov = new PTypeUnion(
                new NamedType("dummy", new PType(PTypeEnumeration.none)),
                new NamedType("iri", new PType(PTypeEnumeration.integer)),
                new NamedType("str", new PType(PTypeEnumeration.sstring)),
                new NamedType("int", new PType(PTypeEnumeration.sstring)),
                new NamedType("date", new PType(PTypeEnumeration.sstring)),
                new NamedType("langstr", new PTypeRecord(
                                  new NamedType("lang", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("str", new PType(PTypeEnumeration.sstring)))));
            PType tp_triple = new PTypeRecord(
                new NamedType("subj", new PType(PTypeEnumeration.integer)),
                new NamedType("pred", new PType(PTypeEnumeration.integer)),
                new NamedType("obj", tp_ov));

            // Главная последовательность кодированных триплетов
            table = new UniversalSequenceBase(tp_triple, stream_gen());

            // прямой ссылочный индекс
            s_index = new IndexKey32CompImmutable(stream_gen, table,
                                                  ob => Enumerable.Repeat <int>((int)((object[])ob)[0], 1), null);

            // Обратный ссылочный индекс
            i_index = new IndexKey32Imm(stream_gen, table, obj =>
            {
                object[] pair = (object[])((object[])obj)[2];
                int tg        = (int)pair[0];
                if (tg != 1)
                {
                    return(Enumerable.Empty <int>());
                }
                return(Enumerable.Repeat <int>((int)pair[1], 1));
            }, null);

            // Индекс по тексту объектов триплетов с предикатом http://fogid.net/o/name
            Comparer <object> comp = Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                return(string.Compare((string)((object[])((object[])a)[2])[1], (string)((object[])((object[])b)[2])[1]));
            }));

            int name_code = Int32.MinValue; // nt.GetSetStr("http://fogid.net/o/name"); // Такое предварительное вычисление не работает!!!

            name_index = new IndexKey32CompImmutable(stream_gen, table, obj =>
            {
                if (name_code == Int32.MinValue)
                {
                    name_code = nt.GetSetStr("http://fogid.net/o/name");
                }
                object[] tri = (object[])obj;
                //TODO: кодов имени может быть много...
                if ((int)tri[1] != name_code)
                {
                    return(Enumerable.Empty <int>());
                }
                object[] pair = (object[])tri[2];
                int tg        = (int)pair[0];
                string data   = null;
                if (tg == 2)
                {
                    data = (string)pair[1];
                }
                //else if (tg == 5) data = (string)((object[])pair[1])[1]; // пока будем работать только с простыми строками
                if (data != null)
                {
                    return(Enumerable.Repeat <int>(Hashfunctions.First4charsRu(data), 1));
                }
                return(Enumerable.Empty <int>());
            },
                                                     //new int[] { Hashfunctions.First4charsRu((string)((object[])obj)[1]) }
                                                     comp);
        }
Exemple #15
0
        static void Main1()
        {
            string root = "";

            Console.WriteLine("Start TestDataGenerators");
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            int npersons = 10;

            Phototeka.PhototekaRecordFlow rflow = new Phototeka.PhototekaRecordFlow(npersons);
            Console.WriteLine(rflow.GenerateAll().Count());
            sw.Stop();
            Console.WriteLine($"duration={sw.ElapsedMilliseconds}");

            PType tp_Arc = new PTypeUnion(
                new NamedType("field", new PTypeRecord(
                                  new NamedType("prop", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("value", new PType(PTypeEnumeration.sstring)))),
                new NamedType("text", new PTypeRecord(
                                  new NamedType("prop", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("value", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("lang", new PType(PTypeEnumeration.sstring)))),
                new NamedType("direct", new PTypeRecord(
                                  new NamedType("prop", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("resource", new PType(PTypeEnumeration.sstring))))
                );
            PType tp_Record = new PTypeRecord(
                new NamedType("about", new PType(PTypeEnumeration.sstring)),
                new NamedType("typ", new PType(PTypeEnumeration.sstring)),
                new NamedType("arcs", new PTypeSequence(tp_Arc))
                );

            // string binpath = root+"phototeka.bin";
            // sw.Restart();
            // rflow.SaveFlowToSequence(rflow.GenerateAll(), binpath);
            // sw.Stop();
            // Console.WriteLine($"duration={sw.ElapsedMilliseconds}");

            // sw.Restart();
            // UniversalSequenceBase sequ = new UniversalSequenceBase(tp_Record,
            //     File.Open(binpath, FileMode.OpenOrCreate, FileAccess.ReadWrite));
            // sequ.Scan((off, obj) => true);
            // sw.Stop();
            // Console.WriteLine($"Scanning... duration={sw.ElapsedMilliseconds}");

            //sw.Restart();
            //rflow.SaveFlowToXml(rflow.GenerateAll(), root + "phototeka.xml");
            //sw.Stop();
            //Console.WriteLine($"duration={sw.ElapsedMilliseconds}");

            string filexmlpath = root + "phototeka.fogx";

            FileStream filexml = File.Open(filexmlpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            sw.Restart();
            rflow.SaveFlowToXElement(rflow.GenerateAll(), filexml);
            sw.Stop();
            Console.WriteLine($"duration={sw.ElapsedMilliseconds}");
            filexml.Close();

            //sw.Restart();root +
            //XElement db1 = XElement.Load(filexmlpath);
            //sw.Stop();
            //Console.WriteLine($"Scanning... duration={sw.ElapsedMilliseconds}");

            string ptpath = "phototeka.fogp";

            FileStream ptextfile = File.Open(ptpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            sw.Restart();
            rflow.SaveFlowToPolarText(rflow.GenerateAll(), ptextfile);
            sw.Stop();
            Console.WriteLine($"Loading and writing... duration={sw.ElapsedMilliseconds}");
            ptextfile.Close();

            ptextfile = File.Open(ptpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            sw.Restart();
            TextReader tr    = new StreamReader(ptextfile);
            int        nrecs = TextFlow.DeserializeSequenseToFlow(tr, tp_Record).Count();

            Console.WriteLine($"{nrecs} records read");
            sw.Stop();
            Console.WriteLine($"Scanning... duration={sw.ElapsedMilliseconds}");
        }
Exemple #16
0
        static void Main(string[] args)
        {
            string path = @"..\..\..\Databases\";

            InitTypes();
            DateTime tt0 = DateTime.Now;

            // Проверка объекта
            object[] testdb = new object[] {
                new object[] { 1, new object[] { "a", "b", "c" } },
                new object[] { 1, new object[] { "a1", "b1", "c1" } },
                new object[] { 2, new object[] { "da", "db", "dc", "lang" } }
            };
            Console.WriteLine(seqtriplets.Interpret(testdb));

            // Создание ячейки плавающего формата
            string testpacfilename = path + "test.pac";

            if (System.IO.File.Exists(testpacfilename))
            {
                System.IO.File.Delete(testpacfilename);
            }
            PaCell cell = new PaCell(seqtriplets, testpacfilename, false); // false - чтобы заполнять

            // Заполнение ячейки данными из объекта
            cell.Fill(testdb);
            // Проверка того, что имеется в ячейке
            var cell_pvalue = cell.Root.GetValue();

            Console.WriteLine(cell_pvalue.Type.Interpret(cell_pvalue.Value));

            PTypeUnion tp_u = new PTypeUnion();

            tp_u.Variants = new[] {
                new NamedType("empty", new PType(PTypeEnumeration.none)),
                new NamedType("node", new PTypeRecord(
                                  new NamedType("f0", new PType(PTypeEnumeration.boolean)),
                                  new NamedType("f1", new PTypeSequence(tp_u))))
            };
            object[] vv = new object[] { 1,
                                         new object[] {
                                             true,
                                             new object[] {
                                                 new object[] { 1,
                                                                new object[] {
                                                                    false,
                                                                    new object[0]
                                                                } }
                                             }
                                         } };
            PxCell xcell = new PxCell(tp_u, path + "xcell.pxc", false);

            xcell.Fill(vv);
            PxEntry e1 = xcell.Root.UElement().Field(1);
            PxEntry e2 = e1.Element(0);
            var     v  = e2.GetValue();

            Console.WriteLine(v.Type.Interpret(v.Value));

            return;

            //cell.Clear();
            //cell.Fill(testtriplets); // проверка на то, что при неочищенной ячейке, записать в нее нельзя
            //cell.Close();
            //cell.Clear();
            //cell.Fill(testtriplets); // проверка на то, что при очищении, записать можно

            //// Проверка серийного буфера, в него загружаются данные из XML-файла, в ячейку ничего не помещается
            //// Этот тест, для начала, можно пропустить.
            //tt0 = DateTime.Now;
            //SerialBuffer buff = new SerialBuffer(new SerialFlowReceiverStub(seqtriplets));
            //TestSerialInput(buff, path);
            //Console.WriteLine("Число элементов в объекте:" + ((object[])buff.Result).LongLength);
            //Console.WriteLine("Forming buffer ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Проверка ввода из серийного скобочного потока для ячейки свободного формата
            // В данном случае, поток порождается при сканировании XML-документа
            tt0 = DateTime.Now;
            cell.Clear();
            TestSerialInput(cell, path);
            Console.WriteLine("Число элементов в объекте:" + cell.Root.Count());
            Console.WriteLine("Serial input ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
            cell.Close(); // Ячейка закрыта, теперь ее нельзя использовать

            // Проверка создания ячейки в режиме чтения
            PaCell cell2pac = new PaCell(seqtriplets, testpacfilename);
            long   cnt2     = cell2pac.Root.Count();
            var    pval2    = cell2pac.Root.Element(100000).GetValue();

            Console.WriteLine("cnt2=" + cnt2 + " Element(100000).Get()=" + pval2.Type.Interpret(pval2.Value));
            Console.WriteLine("ReadObly cell ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Создание ячейки фиксированного формата
            xcell.Clear();
            xcell = new PxCell(seqtriplets, path + "test.pxc", false);
            var pv = cell2pac.Root.Get();

            tt0 = DateTime.Now;
            xcell.Fill2(pv); // Плохой метод, заменю на хороший
            Console.WriteLine("xcell Fill ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            // Проверка наполнения
            PxEntry rxt = xcell.Root;
            var     ele = rxt.Element(400000).GetValue();

            Console.WriteLine(ele.Type.Interpret(ele.Value));
            Console.WriteLine("ok. duration=" + (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
        }
Exemple #17
0
        // Для головы место уже выделено
        internal void FillHead(object valu, PType typ, Queue <VTO> vtoList)
        {
            switch (typ.Vid)
            {
            case PTypeEnumeration.none: break;

            case PTypeEnumeration.boolean: bw.Write((bool)valu); break;

            case PTypeEnumeration.character:
            {
                char ch = (char)valu;
                var  cc = ch - '\0';
                //char.ConvertToUtf32(
                bw.Write((ushort)cc);
                break;
            }

            case PTypeEnumeration.integer: bw.Write((int)valu); break;

            case PTypeEnumeration.longinteger: bw.Write((long)valu); break;

            case PTypeEnumeration.real: bw.Write((double)valu); break;

            case PTypeEnumeration.@byte: bw.Write((byte)valu); break;

            case PTypeEnumeration.fstring:
            {
                string s    = (string)valu;
                int    size = ((PTypeFString)typ).Size;
                byte[] arr  = new byte[size];
                if (s.Length * 2 > size)
                {
                    s = s.Substring(0, size / 2);
                }
                var qu = System.Text.Encoding.Unicode.GetBytes(s, 0, s.Length, arr, 0);
                bw.Write(arr);
            }
            break;

            case PTypeEnumeration.sstring:
            {
                string s   = (string)valu;
                int    len = s.Length;
                bw.Write(len);
                long off = this.freespace;
                this.freespace += 2 * len;
                bw.Write(off);
                if (len > 0)
                {         // Если есть строка, ставим в очередь
                    vtoList.Enqueue(new VTO(valu, typ, off));
                }
            }
            break;

            case PTypeEnumeration.record:
            {
                PTypeRecord mtr = (PTypeRecord)typ;
                object[]    arr = (object[])valu;
                if (arr.Length != mtr.Fields.Length)
                {
                    throw new Exception("record has wrong number of fields");
                }
                for (int i = 0; i < arr.Length; i++)
                {
                    FillHead(arr[i], mtr.Fields[i].Type, vtoList);
                }
            }
            break;

            case PTypeEnumeration.sequence:
            {
                PTypeSequence mts = (PTypeSequence)typ;
                PType         tel = mts.ElementType;
                // Пишем голову последовательности
                long llen = ((object[])valu).Length;
                long off  = this.freespace;

                // Внешний уровень определяем по позиции указателя
                if (this.fs.Position == this.dataStart)
                {
                    this.nElements = llen;
                }

                bw.Write(llen);
                bw.Write(0L);
                bw.Write(off);
                this.freespace += tel.HeadSize * llen;
                // Если есть хвост, ставим в очередь
                if (llen > 0)
                {
                    vtoList.Enqueue(new VTO(valu, typ, off));
                }
            }
            break;

            case PTypeEnumeration.union:
            {
                object[]   arr = (object[])valu;
                int        tag = (int)arr[0];
                PTypeUnion mtu = (PTypeUnion)typ;
                PType      tel = mtu.Variants[tag].Type;
                // Пишем голову
                bw.Write((byte)(int)arr[0]);
                if (tel.IsAtom)
                {
                    if (arr[1] == null)
                    {
                        bw.Write(-1L);
                    }
                    else
                    {
                        WriteAtomAsLong(tel.Vid, arr[1]);
                    }
                }
                else
                {
                    long off = freespace;
                    freespace += tel.HeadSize;
                    bw.Write(off);
                    vtoList.Enqueue(new VTO(arr[1], tel, off)
                        {
                            makehead = true
                        });
                }
            }
            break;

            default: throw new Exception("unexpected type");
            }
        }
Exemple #18
0
        // предполагается, что pos указывает на участок памяти, достаточный для записи головы значения
        private void Fill(long pos, PType tp, object data)
        {
            if (fs.Position != pos)
            {
                fs.Position = pos;                     //fs.Seek(pos, SeekOrigin.Begin);
            }
            switch (tp.Vid)
            {
            case PTypeEnumeration.none: break;

            case PTypeEnumeration.boolean:
                bw.Write((bool)data);
                break;

            case PTypeEnumeration.character:
                char ch = (char)data;
                var  cc = ch - '\0';
                //char.ConvertToUtf32(
                bw.Write((ushort)cc);
                break;

            case PTypeEnumeration.integer:
                bw.Write((int)data);
                break;

            case PTypeEnumeration.longinteger:
                bw.Write((long)data);
                break;

            case PTypeEnumeration.real:
                bw.Write((double)data);
                break;

            case PTypeEnumeration.@byte:
                bw.Write((byte)data);
                break;

            case PTypeEnumeration.sstring:
            {
                string s = (string)data;
                bw.Write((int)s.Length);
                long pointer = Int64.MaxValue;
                if (s.Length > 0)
                {         // захватить память
                    pointer    = freespace;
                    freespace += s.Length * 2;
                }
                bw.Write(pointer);
                if (s.Length > 0)
                {
                    byte[] bytes = Encoding.Unicode.GetBytes(s);
                    if (bytes.Length != s.Length * 2)
                    {
                        throw new Exception("Assert Error in Fill");
                    }
                    if (fs.Position != pointer)
                    {
                        fs.Position = pointer;
                    }
                    bw.Write(bytes);
                }
            }
            break;

            case PTypeEnumeration.record:
            {
                PTypeRecord tr    = (PTypeRecord)tp;
                long        shift = 0L;
                for (int i = 0; i < tr.Fields.Length; i++)
                {
                    var t = tr.Fields[i].Type;
                    Fill(pos + shift, t, ((object[])data)[i]);
                    shift += t.HeadSize;         // ненужные дествия для последнего прохода цикла
                }
            }
            break;

            case PTypeEnumeration.sequence:
            {
                PTypeSequence ts        = (PTypeSequence)tp;
                PType         tpe       = ts.ElementType;
                long          nelements = ((object[])data).Length;
                bw.Write(nelements);
                long memsize = Int64.MaxValue; // это для того, чтобы всегда читать и писать
                long pointer = Int64.MaxValue; // аналогично
                if (nelements > 0)
                {                              // захватить память
                    memsize    = nelements * tpe.HeadSize;
                    pointer    = freespace;
                    freespace += memsize;
                }
                bw.Write(memsize);
                bw.Write(pointer);

                // Внешний уровень определяем по позиции указателя
                if (this.fs.Position == this.dataStart)
                {
                    this.nElements = nelements;
                }

                object[] els = (object[])data;
                // Расписываем элементы
                for (long ii = 0; ii < els.Length; ii++)
                {
                    Fill(pointer + ii * tpe.HeadSize, tpe, els[ii]);
                }
            }
            break;

            case PTypeEnumeration.union:
            {
                PTypeUnion tu    = (PTypeUnion)tp;
                object[]   upair = (object[])data;
                int        tag   = (int)upair[0];
                PType      tel   = tu.Variants[tag].Type;
                bw.Write((byte)tag);
                // либо значение, либо ссылка на новую память
                if (tel.IsAtom)
                {
                    //Fill(pos + 1, tel, upair[1]);
                    if (upair[1] == null)
                    {
                        bw.Write(-1L);
                    }
                    else
                    {                             // Это точно не правильно, надо сделать аккуратнее
                        bw.Write((long)upair[1]); // ??? Это вряд ли правильно, поскольку атомы бывают разных типов
                    }
                }
                else
                {
                    long point = freespace;
                    freespace += tel.HeadSize;
                    bw.Write(point);
                    // введем значение элемента
                    Fill(point, tel, upair[1]);
                }
            }
            break;

            default: throw new Exception("Err in Fill: unknown Vid of vtype [" + tp.Vid + "]");
            }
        }
Exemple #19
0
        public TripleStoreInt32(Func <Stream> stream_gen, string tmp_dir_path)
        {
            // сначала таблица имен
            nt = new Nametable32(stream_gen);
            // Предзагрузка должна быть обеспечена даже для пустой таблицы имен
            PreloadFognames();
            // Тип Object Variants
            PType tp_ov = new PTypeUnion(
                new NamedType("dummy", new PType(PTypeEnumeration.none)),
                new NamedType("iri", new PType(PTypeEnumeration.integer)),
                new NamedType("str", new PType(PTypeEnumeration.sstring))
                //new NamedType("int", new PType(PTypeEnumeration.sstring)),
                //new NamedType("date", new PType(PTypeEnumeration.sstring)),
                //new NamedType("langstr", new PTypeRecord(
                //    new NamedType("lang", new PType(PTypeEnumeration.sstring)),
                //    new NamedType("str", new PType(PTypeEnumeration.sstring))))
                );
            PType tp_triple = new PTypeRecord(
                new NamedType("subj", new PType(PTypeEnumeration.integer)),
                new NamedType("pred", new PType(PTypeEnumeration.integer)),
                new NamedType("obj", tp_ov));

            // Главная последовательность кодированных триплетов
            //table = new UniversalSequenceBase(tp_triple, stream_gen());
            table = new BearingDeletable(tp_triple, stream_gen);

            // прямой ссылочный индекс
            s_index = new IndexKey32Comp(stream_gen, table, ob => true,
                                         ob => (int)((object[])ob)[0], null);

            // Обратный ссылочный индекс
            inv_index = new IndexKey32Comp(stream_gen, table,
                                           ob => (int)((object[])((object[])ob)[2])[0] == 1,
                                           obj =>
            {
                object[] pair = (object[])((object[])obj)[2];
                return((int)pair[1]);
            }, null);

            // Индекс по тексту объектов триплетов с предикатом http://fogid.net/o/name
            //int p_name = Int32.MinValue;
            Comparer <object> comp = Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                return(string.Compare(
                           (string)((object[])((object[])a)[2])[1],
                           (string)((object[])((object[])b)[2])[1], StringComparison.OrdinalIgnoreCase));
            }));

            int cod_name = nt.GetSetStr("http://fogid.net/o/name");

            name_index = new IndexView(stream_gen, table, ob => (int)((object[])ob)[1] == cod_name, comp);

            comp_like = Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                int len = ((string)((object[])((object[])b)[2])[1]).Length;
                return(string.Compare(
                           (string)((object[])((object[])a)[2])[1], 0,
                           (string)((object[])((object[])b)[2])[1], 0, len, StringComparison.OrdinalIgnoreCase));
            }));

            table.Indexes = new IIndex[] { s_index, inv_index, name_index };
        }
Exemple #20
0
        public void Set(object valu)
        {
            // Возможно, стоит убрать следующую установку и внести ее в варианты, этого требующие
            fis.SetOffset(this.offset);
            switch (typ.Vid)
            {
            case PTypeEnumeration.none: break;

            case PTypeEnumeration.boolean: fis.bw.Write((bool)valu); break;

            case PTypeEnumeration.character:
            {
                char ch = (char)valu;
                var  cc = ch - '\0';
                //char.ConvertToUtf32(
                fis.bw.Write((ushort)cc);
                break;
            }

            case PTypeEnumeration.integer: fis.bw.Write((int)valu); break;

            case PTypeEnumeration.longinteger: fis.bw.Write((long)valu); break;

            case PTypeEnumeration.real: fis.bw.Write((double)valu); break;

            case PTypeEnumeration.@byte: fis.bw.Write((byte)valu); break;

            case PTypeEnumeration.fstring:
            {
                string s    = (string)valu;
                int    size = ((PTypeFString)typ).Size;
                byte[] arr  = new byte[size];
                if (s.Length * 2 > size)
                {
                    s = s.Substring(0, size / 2);
                }
                var qu = System.Text.Encoding.Unicode.GetBytes(s, 0, s.Length, arr, 0);
                fis.bw.Write(arr);
            }
            break;

            case PTypeEnumeration.sstring:
            {
                string s   = (string)valu;
                int    len = s.Length;
                fis.bw.Write(len);
                if (len > 0)
                {
                    long off = this.fis.freespace;
                    this.fis.freespace += 2 * len;
                    fis.bw.Write(off);
                    //vtoList.Enqueue(new VTO(valu, typ, off)); // Вместо "метания" записи, стоит использовать очередь или что-то подбное
                    byte[] bytes = Encoding.Unicode.GetBytes(s);
                    if (bytes.Length != s.Length * 2)
                    {
                        throw new Exception("Assert Error in Set(string)");
                    }
                    fis.SetOffset(off);
                    fis.bw.Write(bytes);
                }
            }
            break;

            case PTypeEnumeration.record:
            {
                PTypeRecord mtr = (PTypeRecord)typ;
                object[]    arr = (object[])valu;
                if (arr.Length != mtr.Fields.Length)
                {
                    throw new Exception("Err in Set(): record has wrong number of fields");
                }
                long field_offset = this.offset;
                for (int i = 0; i < arr.Length; i++)
                {
                    PxEntry entry = new PxEntry(mtr.Fields[i].Type, field_offset, this.fis);
                    //FillHead(arr[i], mtr.Fields[i].Type, vtoList);
                    entry.Set(arr[i]);
                    //if (i < arr.Length - 1) // Добавление не мешает, можно не проверять
                    field_offset += mtr.Fields[i].Type.HeadSize;
                }
            }
            break;

            case PTypeEnumeration.sequence:
            {
                PTypeSequence mts = (PTypeSequence)typ;
                PType         tel = mts.ElementType;
                // Пишем голову последовательности
                object[] arr  = (object[])valu;
                long     llen = arr.Length;

                // Внешний уровень определяем по позиции указателя
                if (this.offset == fis.dataStart)
                {
                    fis.nElements = llen;
                }

                fis.bw.Write(llen);
                // Следующие три оператора можно не делать для пустых последовательносте, но даст ли это экономию, неизвестно
                long off = fis.freespace;
                fis.bw.Write(0L);
                fis.bw.Write(off);
                // Если есть хвост, ставим в очередь
                //if (llen > 0) vtoList.Enqueue(new VTO(valu, typ, off));
                // Если есть элементы, заведем место, сформируем массив и запишем элементы
                if (llen > 0)
                {
                    int size = tel.HeadSize;
                    fis.freespace += size * llen;
                    PxEntry entry = new PxEntry(tel, off, fis);
                    for (long i = 0; i < llen; i++)
                    {
                        entry.Set(arr[i]);
                        entry.offset += size;
                    }
                }
            }
            break;

            case PTypeEnumeration.union:
            {
                object[]   arr = (object[])valu;
                int        tag = (int)arr[0];
                PTypeUnion mtu = (PTypeUnion)typ;
                PType      tel = mtu.Variants[tag].Type;
                // Пишем голову
                fis.bw.Write((byte)(int)arr[0]);
                if (tel.IsAtom)
                {
                    if (arr[1] == null)
                    {
                        fis.bw.Write(-1L);
                    }
                    else
                    {
                        fis.WriteAtomAsLong(tel.Vid, arr[1]);
                    }
                }
                else
                {
                    long off = fis.freespace;
                    fis.freespace += tel.HeadSize;
                    fis.bw.Write(off);
                    //vtoList.Enqueue(new VTO(arr[1], tel, off) { makehead = true });
                    PxEntry subelement = new PxEntry(tel, off, fis);
                    subelement.Set(arr[1]);
                }
            }
            break;

            default: throw new Exception("unexpected type");
            }
        }
Exemple #21
0
        /*
         * private void ReplaceHead(object valu)
         * {
         *  fis.SetOffset(this.offset);
         *  switch (typ.Vid)
         *  {
         *      case PTypeEnumeration.none: break;
         *      case PTypeEnumeration.boolean: fis.bw.Write((bool)valu);
         *      case PTypeEnumeration.character: fis.bw.Write((short)valu);
         *      case PTypeEnumeration.integer: fis.bw.Write((int)valu);
         *      case PTypeEnumeration.longinteger: fis.bw.Write((long)valu);
         *      case PTypeEnumeration.real: fis.bw.Write((double)valu);
         *      case PTypeEnumeration.sstring:
         *          {
         *              int len = fis.br.ReadInt32();
         *              long off = fis.br.ReadInt64();
         *              if (len > 0)
         *              {
         *                  fis.SetOffset(off);
         *                  byte[] b = fis.br.ReadBytes(len * 2);
         *                  return Encoding.Unicode.GetString(b);
         *              }
         *              else return "";
         *          }
         *      case PTypeEnumeration.record:
         *          {
         *              PTypeRecord r_tp = (PTypeRecord)typ;
         *              object[] fields = new object[r_tp.Fields.Length];
         *              long off = offse;
         *              for (int i = 0; i < r_tp.Fields.Length; i++)
         *              {
         *                  PType ftyp = r_tp.Fields[i].Type;
         *                  fields[i] = GetPObject(ftyp, off, fis);
         *                  off += ftyp.HeadSize;
         *              }
         *              return fields;
         *          }
         *      case PTypeEnumeration.sequence:
         *          {
         *              PTypeSequence mts = (PTypeSequence)typ;
         *              PType tel = mts.ElementType;
         *              long llen = fis.br.ReadInt64();
         *              fis.br.ReadInt64();
         *              long off = fis.br.ReadInt64();
         *              object[] els = new object[llen];
         *              for (long ii = 0; ii < llen; ii++)
         *              {
         *                  els[ii] = GetPObject(tel, off, fis);
         *                  off += tel.HeadSize;
         *              }
         *              return els;
         *          }
         *      case PTypeEnumeration.union:
         *          {
         *              PTypeUnion mtu = (PTypeUnion)typ;
         *              int v = fis.br.ReadByte();
         *              long off = fis.br.ReadInt64();
         *              PType mt = mtu.Variants[v].Type;
         *              if (mt.IsAtom) return new object[] { v, GetPObject(mt, offse + 1, fis) };
         *              else return new object[] { v, GetPObject(mt, off, fis) };
         *          }
         *
         *      default: throw new Exception("Err in TPath Get(): type is not implemented " + typ.Vid);
         *  }
         * }
         */
        private static object GetPObject(PType typ, long offse, PxCell fis)
        {
            fis.SetOffset(offse);
            switch (typ.Vid)
            {
            case PTypeEnumeration.none: return(null);

            case PTypeEnumeration.boolean: return(fis.br.ReadBoolean());

            case PTypeEnumeration.character: return(fis.br.ReadChar());

            case PTypeEnumeration.integer: return(fis.br.ReadInt32());

            case PTypeEnumeration.longinteger: return(fis.br.ReadInt64());

            case PTypeEnumeration.real: return(fis.br.ReadDouble());

            case PTypeEnumeration.@byte: return(fis.br.ReadByte());

            case PTypeEnumeration.sstring:
            {
                int  len = fis.br.ReadInt32();
                long off = fis.br.ReadInt64();
                if (len > 0)
                {
                    fis.SetOffset(off);
                    byte[] b = fis.br.ReadBytes(len * 2);
                    return(Encoding.Unicode.GetString(b));
                }
                else
                {
                    return("");
                }
            }

            case PTypeEnumeration.fstring:
            {
                int    size = ((PTypeFString)typ).Size;
                byte[] arr  = new byte[size];
                arr = fis.br.ReadBytes(size);
                int count = size / 2;
                while (count > 0 && arr[2 * count - 1] == 0 && arr[2 * count - 2] == 0)
                {
                    count--;
                }
                string s = System.Text.Encoding.Unicode.GetString(arr, 0, 2 * count);
                return(s);
            }

            case PTypeEnumeration.record:
            {
                PTypeRecord r_tp   = (PTypeRecord)typ;
                object[]    fields = new object[r_tp.Fields.Length];
                long        off    = offse;
                for (int i = 0; i < r_tp.Fields.Length; i++)
                {
                    PType ftyp = r_tp.Fields[i].Type;
                    fields[i] = GetPObject(ftyp, off, fis);
                    off      += ftyp.HeadSize;
                }
                return(fields);
            }

            case PTypeEnumeration.sequence:
            {
                PTypeSequence mts  = (PTypeSequence)typ;
                PType         tel  = mts.ElementType;
                long          llen = fis.br.ReadInt64();
                fis.br.ReadInt64();
                long     off = fis.br.ReadInt64();
                object[] els = new object[llen];
                for (long ii = 0; ii < llen; ii++)
                {
                    els[ii] = GetPObject(tel, off, fis);
                    off    += tel.HeadSize;
                }
                return(els);
            }

            case PTypeEnumeration.union:
            {
                PTypeUnion mtu = (PTypeUnion)typ;
                int        v   = fis.br.ReadByte();
                PType      mt  = mtu.Variants[v].Type;
                long       off = fis.br.ReadInt64();
                if (mt.IsAtom)
                {
                    return new object[] { v, off == -1L
                                                    ? null
                                                    : fis.ReadAtomFromLong(mt.Vid, offse + 1) }
                }
                ;
                else
                {
                    return(new object[] { v, GetPObject(mt, off, fis) });
                }
            }

            default: throw new Exception("Err in TPath Get(): type is not implemented " + typ.Vid);
            }
        }
Exemple #22
0
        /// <summary>
        /// Добавляет объектное значение в ячейку по месту текущей позиции файла
        /// </summary>
        /// <param name="typ"></param>
        /// <param name="value"></param>
        protected internal void Append(PType typ, object value)
        {
            switch (typ.Vid)
            {
            case PTypeEnumeration.none: break;

            case PTypeEnumeration.boolean: bw.Write((bool)value); break;

            case PTypeEnumeration.character: bw.Write((char)value); break;

            case PTypeEnumeration.integer: bw.Write((int)value); break;

            case PTypeEnumeration.longinteger: bw.Write((long)value); break;

            case PTypeEnumeration.real: bw.Write((double)value); break;

            case PTypeEnumeration.@byte: bw.Write((byte)value); break;

            case PTypeEnumeration.fstring:
            {
                string str       = (string)value;
                int    maxlength = ((PTypeFString)typ).Length;
                if (str.Length < maxlength)
                {
                    maxlength = str.Length;
                }
                int    size  = ((PTypeFString)typ).Size;
                byte[] bytes = new byte[size];
                int    nb    = Encoding.Unicode.GetBytes(str, 0, maxlength, bytes, 0);
                // Возможно, надо еще разметить остаток массива. Пока считаю, что имеется разметка нулями и этого достаточно
                fs.Write(bytes, 0, bytes.Length);
            }
            break;

            case PTypeEnumeration.sstring:
            {
                string str = (string)value;
                //bw.Write(str.Length);
                //byte[] info = new UTF8Encoding(true).GetBytes(str);
                //fs.Write(info, 0, info.Length);
                bw.Write(str);
            }
            break;

            case PTypeEnumeration.record:
            {
                PTypeRecord mtr       = (PTypeRecord)typ;
                int         ind_value = 0;
                foreach (var ft in mtr.Fields)
                {
                    PType    tel = ft.Type;
                    object[] els = (object[])value;
                    Append(tel, els[ind_value]);
                    ind_value++;
                }
            }
            break;

            case PTypeEnumeration.sequence:
            {
                PTypeSequence mts = (PTypeSequence)typ;
                PType         tel = mts.ElementType;
                object[]      els = (object[])value;
                // Внешний уровень определяем по позиции указателя
                if (this.fs.Position == this.dataStart)
                {
                    this.nElements = els.Length;
                }
                bw.Write((long)els.Length);
                foreach (var el in els)
                {
                    Append(tel, el);
                }
            }
            break;

            case PTypeEnumeration.union:
            {
                PTypeUnion tpu  = (PTypeUnion)typ;
                object[]   pair = (object[])value;
                int        tag  = (int)pair[0];
                object     val  = pair[1];
                bw.Write((byte)tag);
                Append(tpu.Variants[tag].Type, val);
            }
            break;

            default:
                throw new Exception("VStore.Append 3 exception");
            }
        }
Exemple #23
0
        /// <summary>
        /// Читает P-объект из бинарного ридера, начиная с текущего места
        /// </summary>
        /// <param name="typ"></param>
        /// <param name="br"></param>
        /// <returns></returns>
        public static object GetPO(PType typ, System.IO.BinaryReader br)
        {
            switch (typ.Vid)
            {
            case PTypeEnumeration.none: return(null);

            case PTypeEnumeration.boolean: return(br.ReadBoolean());

            case PTypeEnumeration.integer: return(br.ReadInt32());

            case PTypeEnumeration.longinteger: return(br.ReadInt64());

            case PTypeEnumeration.real: return(br.ReadDouble());

            case PTypeEnumeration.@byte: return(br.ReadByte());

            case PTypeEnumeration.fstring:
            {
                //int len = ((PTypeFString)typ).Length;
                int    size = ((PTypeFString)typ).Size;
                byte[] arr  = new byte[size];
                arr = br.ReadBytes(size);
                string s = System.Text.Encoding.Unicode.GetString(arr);
                return(s);
            }

            case PTypeEnumeration.sstring:
            {
                //int len = br.ReadInt32();
                //char[] chrs = br.ReadChars(len);
                //return new string(chrs);
                return(br.ReadString());
            }

            case PTypeEnumeration.record:
            {
                PTypeRecord r_tp   = (PTypeRecord)typ;
                object[]    fields = new object[r_tp.Fields.Length];
                for (int i = 0; i < r_tp.Fields.Length; i++)
                {
                    fields[i] = GetPO(r_tp.Fields[i].Type, br);
                }
                return(fields);
            }

            case PTypeEnumeration.sequence:
            {
                PTypeSequence mts  = (PTypeSequence)typ;
                PType         tel  = mts.ElementType;
                long          llen = br.ReadInt64();
                object[]      els  = new object[llen];
                for (long ii = 0; ii < llen; ii++)
                {
                    els[ii] = GetPO(tel, br);
                }
                return(els);
            }

            case PTypeEnumeration.union:
            {
                PTypeUnion mtu = (PTypeUnion)typ;
                int        v   = br.ReadByte();
                PType      mt  = mtu.Variants[v].Type;
                return(new object[] { v, GetPO(mt, br) });
            }

            default: throw new Exception("Err in TPath Get(): type is not implemented " + typ.Vid);
            }
        }