pub struct Parser<R: Read + Seek> { /* private fields */ }Expand description
Реализует потоковый (наподобие SAX) парсер GFF файла. Парсер реализует интерфейс
итератора по токенам. Каждый вызов метода next_token возвращает следующий токен
из потока, который сразу же может быть использован для анализа или сохранен для
дальнейшего использования.
§События разбора
Парсер представляет собой pull-down парсер, т.е. для получения данных его нужно опрашивать внешним циклом (в противоположность push-down парсеру, который испускает события при разборе очередного элемента).
Так как GFF файл может быть представлен в XML виде, и эта структура проще для представления в тексте, то ниже показан пример файла, в котором отмечены места после которых парсер генерирует токены при разборе. В виде кода Rust описанная структура данных может быть представлена таким образом:
struct Struct;
struct Item {
double: f64,
}
struct Root {
int: i32,
struc: Struct,
list: Vec<Item>,
}XML представление:
<STRUCT tag='4294967295'>[1]
<FIELD label='int'[2] type='INT'>8</FIELD>[3]
<FIELD label='struc'[4] type='STRUCT'>
<STRUCT tag='1'>[5]
</STRUCT>[6]
</FIELD>
<FIELD label='list'[7] type='LIST'>[8]
<STRUCT tag='2'>[9]
<FIELD label='double'[10] type='DOUBLE'>0.000000</FIELD>[11]
</STRUCT>[12]
</FIELD>[13]
</STRUCT>[14]Токены, получаемые последовательным вызовом next_token:
RootBegin. Прочитано описание корневой структуры – в этом состоянии уже известен тег типа структуры и количество полей в ней.Label. Прочитан индекс метки, по этому индексу может быть прочитано значение меткиValue. Прочитано примитивное значениеLabel. Прочитан индекс метки, по этому индексу может быть прочитано значение меткиStructBegin. Прочитано количество полей структуры и ее тегStructEndLabel. Прочитан индекс метки, по этому индексу может быть прочитано значение меткиListBegin. Прочитано количество элементов спискаItemBegin. Прочитано количество полей структуры, ее тег, а также предоставляется информация о порядковом индексе элементаLabel. Прочитан индекс метки, по этому индексу может быть прочитано значение меткиValue. Прочитан индекс большого значения (больше 4-х байт), по этому индексу само значение может быть прочитано отдельным вызовомItemEnd. Элемент списка прочитанListEnd. Весь список прочитанRootEnd. Файл прочитан
§Пример
В данном примере читается файл с диска, и в потоковом режиме выводится на экран, формируя что-то, напоминающее JSON.
use std::fs::File;
use serde_gff::parser::Parser;
use serde_gff::parser::Token::*;
// Читаем файл с диска и создаем парсер. При создании парсер сразу же читает небольшую
// порцию данных -- заголовок, которая нужна ему для правильного разрешения ссылок
let file = File::open("test-data/all.gff").expect("test file not exist");
let mut parser = Parser::new(file).expect("reading GFF header failed");
let mut indent = 0;
loop {
// В данном случае мы используем методы типажа Iterator для итерирования по файлу, так
// как мы полагаем, что ошибок в процессе чтения не возникнет. Если же они интересны,
// следует использовать метод `next_token`
if let Some(token) = parser.next() {
match token {
RootBegin {..} | RootEnd => {},
// Обрамляем структуры в `{ ... }`
StructBegin {..} => { indent += 1; println!("{{"); },
StructEnd => { indent -= 1; println!("{:indent$}}}", "", indent=indent*2); },
// Обрамляем списки в `[ ... ]`
ListBegin {..} => { indent += 1; println!("["); },
ListEnd => { indent -= 1; println!("{:indent$}]", "", indent=indent*2); },
// Обрамляем элементы списков в `[index]: { ... }`
ItemBegin { index, .. } => {
println!("{:indent$}[{}]: {{", "", index, indent=indent*2);
indent += 1;
},
ItemEnd => {
indent -= 1;
println!("{:indent$}}}", "", indent=indent*2);
},
Label(index) => {
// Физически значение меток хранится в другом месте файла. Так как при итерировании они
// могут быть нам неинтересны, то токен содержит только индекс используемой метки (имени
// поля). В данном же случае они нас интересуют, поэтому выполняем полное чтение
let label = parser.read_label(index).expect(&format!("can't read label {:?}", index));
print!("{:indent$}{}: ", "", label, indent=indent*2)
},
// Аналогично со значениями. Некоторые значения доступны сразу (те, чей размер не превышает
// 4 байта), другие хранятся с других частях файла и должны быть явно прочитаны.
// Также, если вас интересует только какое-то конкретное значение, может быть использован
// один из методов `read_*` парсера
Value(value) => println!("{:?}", parser.read_value(value).expect("can't read value")),
}
continue;
}
// Как только итератор возвращает None, файл закончился, либо произошла ошибка; завершаем работу
break;
}Implementations§
Source§impl<R: Read + Seek> Parser<R>
impl<R: Read + Seek> Parser<R>
Sourcepub fn new(reader: R) -> Result<Self>
pub fn new(reader: R) -> Result<Self>
Создает парсер для чтения GFF файла из указанного источника данных с использованием
кодировки UTF-8 для декодирования строк и генерацией ошибки в случае, если декодировать
набор байт, как строку в этой кодировке, не удалось.
§Параметры
reader: Источник данных для чтения файла
Sourcepub fn with_encoding(
reader: R,
encoding: EncodingRef,
trap: DecoderTrap,
) -> Result<Self>
pub fn with_encoding( reader: R, encoding: EncodingRef, trap: DecoderTrap, ) -> Result<Self>
Создает парсер для чтения GFF файла из указанного источника данных с использованием указанной кодировки для декодирования строк.
§Параметры
reader: Источник данных для чтения файлаencoding: Кодировка для декодирования символов в строкахtrap: Способ обработки символов в строках, которые не удалось декодировать с использованием выбранной кодировки
Sourcepub fn next_token(&mut self) -> Result<Token>
pub fn next_token(&mut self) -> Result<Token>
Возвращает следующий токен или ошибку, если данных не осталось или при их чтении возникли проблемы.
Sourcepub fn skip_next(&mut self, token: Token)
pub fn skip_next(&mut self, token: Token)
Быстро пропускает всю внутреннюю структуру, переводя парсер в состояние, при котором
вызов next_token вернет следующий структурный элемент после пропущенного (следующее
поле структуры или элемент списка).
§Параметры
token: Токен, полученный предшествующим вызовомnext_token
Sourcepub fn read_label(&mut self, index: LabelIndex) -> Result<Label>
pub fn read_label(&mut self, index: LabelIndex) -> Result<Label>
Читает из файла значение метки по указанному индексу. Не меняет позицию чтения в файле
Sourcepub fn read_u64(&mut self, index: U64Index) -> Result<u64>
pub fn read_u64(&mut self, index: U64Index) -> Result<u64>
Читает из файла значение поля по указанному индексу. Побочный эффект – переход по указанному адресу
Sourcepub fn read_i64(&mut self, index: I64Index) -> Result<i64>
pub fn read_i64(&mut self, index: I64Index) -> Result<i64>
Читает из файла значение поля по указанному индексу. Побочный эффект – переход по указанному адресу
Sourcepub fn read_f64(&mut self, index: F64Index) -> Result<f64>
pub fn read_f64(&mut self, index: F64Index) -> Result<f64>
Читает из файла значение поля по указанному индексу. Побочный эффект – переход по указанному адресу
Sourcepub fn read_string(&mut self, index: StringIndex) -> Result<String>
pub fn read_string(&mut self, index: StringIndex) -> Result<String>
Читает 4 байта длины и следующие за ними байты строки, интерпретирует их в соответствии с кодировкой декодера и возвращает полученную строку. Побочный эффект – переход по указанному адресу
Sourcepub fn read_resref(&mut self, index: ResRefIndex) -> Result<ResRef>
pub fn read_resref(&mut self, index: ResRefIndex) -> Result<ResRef>
Читает 1 байт длины и следующие за ними байты массива, возвращает прочитанный массив,
обернутый в ResRef. Побочный эффект – переход по указанному адресу
Sourcepub fn read_loc_string(&mut self, index: LocStringIndex) -> Result<LocString>
pub fn read_loc_string(&mut self, index: LocStringIndex) -> Result<LocString>
Читает из файла значение поля по указанному индексу. Побочный эффект – переход по указанному адресу
Sourcepub fn read_byte_buf(&mut self, index: BinaryIndex) -> Result<Vec<u8>>
pub fn read_byte_buf(&mut self, index: BinaryIndex) -> Result<Vec<u8>>
Читает 4 байта длины и следующие за ними байты массива, возвращает прочитанный массив. Побочный эффект – переход по указанному адресу
Sourcepub fn read_value(&mut self, value: SimpleValueRef) -> Result<SimpleValue>
pub fn read_value(&mut self, value: SimpleValueRef) -> Result<SimpleValue>
Если value содержит еще не прочитанные поля (т.е. содержащие индексы), читает их.
В противном случае просто преобразует тип значения в SimpleValue.
Данный метод меняет внутреннюю позицию чтения парсера, однако это не несет за собой
негативных последствий, если сразу после вызова данного метода выполнить переход к
следующему токену при итерации по токенам парсера. См. пример в описании структуры
Parser.
Trait Implementations§
Source§impl<R: Read + Seek> Iterator for Parser<R>
impl<R: Read + Seek> Iterator for Parser<R>
Source§fn next(&mut self) -> Option<Token>
fn next(&mut self) -> Option<Token>
Source§fn size_hint(&self) -> (usize, Option<usize>)
fn size_hint(&self) -> (usize, Option<usize>)
Source§fn next_chunk<const N: usize>(
&mut self,
) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where
Self: Sized,
fn next_chunk<const N: usize>(
&mut self,
) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>where
Self: Sized,
iter_next_chunk)N values. Read more1.0.0 · Source§fn count(self) -> usizewhere
Self: Sized,
fn count(self) -> usizewhere
Self: Sized,
1.0.0 · Source§fn last(self) -> Option<Self::Item>where
Self: Sized,
fn last(self) -> Option<Self::Item>where
Self: Sized,
Source§fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>
iter_advance_by)n elements. Read more1.0.0 · Source§fn nth(&mut self, n: usize) -> Option<Self::Item>
fn nth(&mut self, n: usize) -> Option<Self::Item>
nth element of the iterator. Read more1.28.0 · Source§fn step_by(self, step: usize) -> StepBy<Self>where
Self: Sized,
fn step_by(self, step: usize) -> StepBy<Self>where
Self: Sized,
1.0.0 · Source§fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>
fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>
1.0.0 · Source§fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where
Self: Sized,
U: IntoIterator,
fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>where
Self: Sized,
U: IntoIterator,
Source§fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
iter_intersperse)separator between adjacent
items of the original iterator. Read moreSource§fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
iter_intersperse)separator
between adjacent items of the original iterator. Read more1.0.0 · Source§fn map<B, F>(self, f: F) -> Map<Self, F>
fn map<B, F>(self, f: F) -> Map<Self, F>
1.0.0 · Source§fn filter<P>(self, predicate: P) -> Filter<Self, P>
fn filter<P>(self, predicate: P) -> Filter<Self, P>
1.0.0 · Source§fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
1.0.0 · Source§fn enumerate(self) -> Enumerate<Self>where
Self: Sized,
fn enumerate(self) -> Enumerate<Self>where
Self: Sized,
1.0.0 · Source§fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1.0.0 · Source§fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1.57.0 · Source§fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1.0.0 · Source§fn skip(self, n: usize) -> Skip<Self>where
Self: Sized,
fn skip(self, n: usize) -> Skip<Self>where
Self: Sized,
n elements. Read more1.0.0 · Source§fn take(self, n: usize) -> Take<Self>where
Self: Sized,
fn take(self, n: usize) -> Take<Self>where
Self: Sized,
n elements, or fewer
if the underlying iterator ends sooner. Read more1.0.0 · Source§fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
Source§fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
iter_map_windows)f for each contiguous window of size N over
self and returns an iterator over the outputs of f. Like slice::windows(),
the windows during mapping overlap as well. Read more1.0.0 · Source§fn inspect<F>(self, f: F) -> Inspect<Self, F>
fn inspect<F>(self, f: F) -> Inspect<Self, F>
1.0.0 · Source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Iterator. Read moreSource§fn collect_into<E>(self, collection: &mut E) -> &mut E
fn collect_into<E>(self, collection: &mut E) -> &mut E
iter_collect_into)1.0.0 · Source§fn partition<B, F>(self, f: F) -> (B, B)
fn partition<B, F>(self, f: F) -> (B, B)
Source§fn is_partitioned<P>(self, predicate: P) -> bool
fn is_partitioned<P>(self, predicate: P) -> bool
iter_is_partitioned)true precede all those that return false. Read more1.27.0 · Source§fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
1.27.0 · Source§fn try_for_each<F, R>(&mut self, f: F) -> R
fn try_for_each<F, R>(&mut self, f: F) -> R
1.0.0 · Source§fn fold<B, F>(self, init: B, f: F) -> B
fn fold<B, F>(self, init: B, f: F) -> B
1.51.0 · Source§fn reduce<F>(self, f: F) -> Option<Self::Item>
fn reduce<F>(self, f: F) -> Option<Self::Item>
Source§fn try_reduce<R>(
&mut self,
f: impl FnMut(Self::Item, Self::Item) -> R,
) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryType
fn try_reduce<R>( &mut self, f: impl FnMut(Self::Item, Self::Item) -> R, ) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryType
iterator_try_reduce)1.0.0 · Source§fn all<F>(&mut self, f: F) -> bool
fn all<F>(&mut self, f: F) -> bool
1.0.0 · Source§fn any<F>(&mut self, f: F) -> bool
fn any<F>(&mut self, f: F) -> bool
1.0.0 · Source§fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
1.30.0 · Source§fn find_map<B, F>(&mut self, f: F) -> Option<B>
fn find_map<B, F>(&mut self, f: F) -> Option<B>
Source§fn try_find<R>(
&mut self,
f: impl FnMut(&Self::Item) -> R,
) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryType
fn try_find<R>( &mut self, f: impl FnMut(&Self::Item) -> R, ) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryType
try_find)1.0.0 · Source§fn position<P>(&mut self, predicate: P) -> Option<usize>
fn position<P>(&mut self, predicate: P) -> Option<usize>
1.6.0 · Source§fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
1.15.0 · Source§fn max_by<F>(self, compare: F) -> Option<Self::Item>
fn max_by<F>(self, compare: F) -> Option<Self::Item>
1.6.0 · Source§fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
1.15.0 · Source§fn min_by<F>(self, compare: F) -> Option<Self::Item>
fn min_by<F>(self, compare: F) -> Option<Self::Item>
1.0.0 · Source§fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
1.36.0 · Source§fn copied<'a, T>(self) -> Copied<Self>
fn copied<'a, T>(self) -> Copied<Self>
Source§fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>where
Self: Sized,
fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>where
Self: Sized,
iter_array_chunks)N elements of the iterator at a time. Read more1.11.0 · Source§fn product<P>(self) -> P
fn product<P>(self) -> P
Source§fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
iter_order_by)Iterator with those
of another with respect to the specified comparison function. Read more1.5.0 · Source§fn partial_cmp<I>(self, other: I) -> Option<Ordering>
fn partial_cmp<I>(self, other: I) -> Option<Ordering>
PartialOrd elements of
this Iterator with those of another. The comparison works like short-circuit
evaluation, returning a result without comparing the remaining elements.
As soon as an order can be determined, the evaluation stops and a result is returned. Read moreSource§fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>where
Self: Sized,
I: IntoIterator,
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,
fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>where
Self: Sized,
I: IntoIterator,
F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,
iter_order_by)Iterator with those
of another with respect to the specified comparison function. Read moreSource§fn eq_by<I, F>(self, other: I, eq: F) -> bool
fn eq_by<I, F>(self, other: I, eq: F) -> bool
iter_order_by)1.5.0 · Source§fn lt<I>(self, other: I) -> bool
fn lt<I>(self, other: I) -> bool
Iterator are lexicographically
less than those of another. Read more1.5.0 · Source§fn le<I>(self, other: I) -> bool
fn le<I>(self, other: I) -> bool
Iterator are lexicographically
less or equal to those of another. Read more1.5.0 · Source§fn gt<I>(self, other: I) -> bool
fn gt<I>(self, other: I) -> bool
Iterator are lexicographically
greater than those of another. Read more1.5.0 · Source§fn ge<I>(self, other: I) -> bool
fn ge<I>(self, other: I) -> bool
Iterator are lexicographically
greater than or equal to those of another. Read more