Skip to Content

Module parser

Библиотека парсинга форматов транзакций YPBank.

Этот крейт предоставляет структуры данных и парсеры для работы с файлами транзакций YPBank в двух форматах:

  • YPBankText — человекочитаемый текстовый формат с парами ключ-значение
  • YPBankBin — компактный бинарный формат с магическим заголовком

Быстрый старт

use parser::prelude::*; let tx = Transaction { tx_id: 1234567890123456, tx_type: TransactionType::Deposit, from_user_id: 0, to_user_id: 9876543210987654, amount: 10000, timestamp: 1633036800000, status: TransactionStatus::Success, description: "Пополнение через терминал".to_string(), }; assert_eq!(tx.tx_type, TransactionType::Deposit); assert_eq!(tx.from_user_id, 0);

Чтение транзакций (streaming)

use parser::prelude::*; use std::fs::File; let file = File::open("transactions.bin")?; let reader = TransactionReader::<_, Binary>::new(file); for result in reader { let tx = result?; println!("{:?}", tx); }

Альтернативно: прямое использование serde модуля

use parser::serde::{binary, text}; // Binary format for tx in binary::iter_reader(file) { let tx: Transaction = tx?; println!("{:?}", tx); } // Text format let tx: Transaction = text::from_str(&text_data)?;

Конверсия форматов

use parser::convert::convert; use parser::serde::{Text, Binary}; use std::fs::File; let input = File::open("input.txt")?; let output = File::create("output.bin")?; convert::<_, _, Text, Binary>(input, output)?;

Modules

Module error

Модуль ошибок парсинга транзакций.

pub mod error { /* ... */ }

Types

Enum ParseError

Главная ошибка парсинга транзакций.

Объединяет все возможные ошибки при работе с форматами YPBank: I/O ошибки, ошибки парсинга каждого формата и ошибки валидации.

pub enum ParseError { Io(std::io::Error), InvalidField { field: String, line: usize, message: String, }, MissingField(String), DuplicateField { field: String, line: usize, }, InvalidValue { field: String, expected: String, actual: String, }, InvalidMagic([u8; 4]), RecordSizeMismatch { expected: u32, actual: u32, }, InvalidEnumValue { field: String, value: u8, }, InvalidUtf8(std::string::FromUtf8Error), CsvError(String), Validation(crate::transaction::ValidationError), UnknownFormat, UnexpectedEof, }
Variants
Io

Ошибка ввода/вывода.

Fields:

IndexTypeDocumentation
0std::io::Error
InvalidField

Некорректное поле в текстовом формате.

Fields:

NameTypeDocumentation
fieldStringИмя поля.
lineusizeНомер строки (1-based).
messageStringОписание ошибки.
MissingField

Отсутствует обязательное поле.

Fields:

IndexTypeDocumentation
0String
DuplicateField

Дублирование поля в записи.

Fields:

NameTypeDocumentation
fieldStringИмя дублирующегося поля.
lineusizeНомер строки (1-based).
InvalidValue

Некорректное значение поля.

Fields:

NameTypeDocumentation
fieldStringИмя поля.
expectedStringОжидаемый тип/формат.
actualStringФактическое значение.
InvalidMagic

Некорректные magic bytes в бинарном формате.

Fields:

IndexTypeDocumentation
0[u8; 4]
RecordSizeMismatch

Несоответствие размера записи в заголовке и фактического.

Fields:

NameTypeDocumentation
expectedu32Размер из заголовка.
actualu32Фактический размер.
InvalidEnumValue

Некорректное значение для enum-поля (TX_TYPE или STATUS).

Fields:

NameTypeDocumentation
fieldStringИмя поля.
valueu8Некорректное числовое значение.
InvalidUtf8

Некорректная UTF-8 строка в описании.

Fields:

IndexTypeDocumentation
0std::string::FromUtf8Error
CsvError

Ошибка парсинга или записи CSV.

Fields:

IndexTypeDocumentation
0String
Validation

Ошибка бизнес-валидации транзакции.

Fields:

IndexTypeDocumentation
0crate::transaction::ValidationError
UnknownFormat

Неизвестный формат файла.

UnexpectedEof

Неожиданный конец файла.

Implementations
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
  • Display

    • fn fmt(self: &Self, __formatter: &mut ::core::fmt::Formatter<''_>) -> ::core::fmt::Result { /* ... */ }
  • Error

    • fn source(self: &Self) -> ::core::option::Option<&dyn ::thiserror::__private17::Error + ''static> { /* ... */ }
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }

      Returns the argument unchanged.

    • fn from(source: std::io::Error) -> Self { /* ... */ }
    • fn from(source: std::string::FromUtf8Error) -> Self { /* ... */ }
    • fn from(source: ValidationError) -> Self { /* ... */ }
    • fn from(err: crate::serde::Error) -> Self { /* ... */ }
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      Calls U::from(self).
  • RefUnwindSafe

  • Send

  • Sync

  • ToString

    • fn to_string(self: &Self) -> String { /* ... */ }
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
  • Unpin

  • UnwindSafe

Type Alias ParseResult

Удобный alias для Result с ParseError.

pub type ParseResult<T> = Result<T, ParseError>;

Module reader

Потоковый reader для транзакций.

Предоставляет [TransactionReader] — итератор, который читает транзакции из любого источника, реализующего [Read].

pub mod reader { /* ... */ }

Types

Struct TransactionReader

Потоковый reader для транзакций.

Реализует [Iterator] для чтения транзакций из потока. Использует [BufReader] для буферизации, что необходимо для корректной работы текстового формата.

Type Parameters

  • R: источник данных (реализует [Read])
  • F: формат (реализует [SerdeFormat])

Пример

use parser::reader::TransactionReader; use parser::serde::Binary; use std::fs::File; let file = File::open("transactions.bin")?; let reader = TransactionReader::<_, Binary>::new(file); for result in reader { let tx = result?; println!("{:?}", tx); }
pub struct TransactionReader<R, F> { // Some fields omitted }
Fields
NameTypeDocumentation
private fieldsSome fields have been omitted
Implementations
Methods
  • pub fn new(reader: R) -> Self { /* ... */ }

    Создаёт новый reader.

  • pub fn records_read(self: &Self) -> usize { /* ... */ }

    Возвращает количество успешно прочитанных записей.

  • pub fn get_ref(self: &Self) -> &R { /* ... */ }

    Получает ссылку на внутренний reader.

  • pub fn into_inner(self: Self) -> R { /* ... */ }

    Извлекает внутренний reader.

Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      Calls U::from(self).
  • IntoIterator

    • fn into_iter(self: Self) -> I { /* ... */ }
  • Iterator

    • fn next(self: &mut Self) -> Option<<Self as >::Item> { /* ... */ }
  • RefUnwindSafe

  • Send

  • Sync

  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
  • Unpin

  • UnwindSafe

Module serde

Serde-based serialization for transaction formats.

This module provides custom Serde Serializer and Deserializer implementations for the YPBN binary and text formats, offering a unified streaming API.

Streaming API

All formats support streaming read/write via:

  • read_one() — read a single transaction
  • write_one() — write a single transaction
  • iter_reader() — iterate over transactions

Example

use parser::serde::{binary, text}; use parser::Transaction; // Binary format let bytes = binary::to_bytes(&tx)?; let decoded: Transaction = binary::from_bytes(&bytes)?; // Text format (streaming) for tx in text::iter_reader(file) { let tx = tx?; println!("{:?}", tx); }
pub mod serde { /* ... */ }

Modules

Module binary

Serde-based YPBN binary format serialization.

This module provides Serde Serializer and Deserializer implementations for the YPBank binary format with magic bytes YPBN and big-endian encoding.

Format

[MAGIC: 4 bytes] [SIZE: 4 bytes BE] [BODY: variable] "YPBN" (u32) TX_ID(8) + TX_TYPE(1) + ...

Streaming Example

use parser::serde::binary; use std::fs::File; let file = File::open("transactions.bin")?; for tx in binary::iter_reader(file) { let tx = tx?; println!("{:?}", tx); }
pub mod binary { /* ... */ }

Types

Struct RecoverableIterator

Iterator that recovers from errors by seeking to next MAGIC sequence.

This iterator tracks statistics about successful and skipped records, accessible via records_read() and skipped_count().

pub struct RecoverableIterator<R, T> { // Some fields omitted }
Fields
NameTypeDocumentation
private fieldsSome fields have been omitted
Implementations
Methods
  • pub fn records_read(self: &Self) -> usize { /* ... */ }

    Returns the number of successfully deserialized records.

  • pub fn skipped_count(self: &Self) -> usize { /* ... */ }

    Returns the number of skipped (corrupt) records.

  • pub fn bytes_read(self: &Self) -> u64 { /* ... */ }

    Returns the total bytes read from the stream.

Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      Calls U::from(self).
  • IntoIterator

    • fn into_iter(self: Self) -> I { /* ... */ }
  • Iterator

    • fn next(self: &mut Self) -> Option<<Self as >::Item> { /* ... */ }
  • RefUnwindSafe

  • Send

  • Sync

  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
  • Unpin

  • UnwindSafe

Functions

Function read_one

Reads a single transaction from a reader (streaming).

Returns Ok(Some(tx)) if a transaction was read, Ok(None) at EOF, or Err on parse error.

Example

use parser::serde::binary; use std::fs::File; let mut file = File::open("transactions.bin")?; while let Some(tx) = binary::read_one(&mut file)? { println!("{:?}", tx); }
pub fn read_one<R: Read, T: for<''de> Deserialize<''de>>(reader: &mut R) -> super::Result<Option<T>> { /* ... */ }

Function write_one

Writes a single transaction to a writer (streaming).

Each call writes one complete record with magic bytes and size header.

Example

use parser::serde::binary; use std::fs::File; let mut file = File::create("output.bin")?; binary::write_one(&mut file, &tx)?;
pub fn write_one<W: Write, T: Serialize>(writer: &mut W, value: &T) -> super::Result<()> { /* ... */ }

Function iter_reader

Creates an iterator over transactions in a reader.

Example

use parser::serde::binary; use std::fs::File; let file = File::open("transactions.bin")?; for result in binary::iter_reader::<_, Transaction>(file) { let tx = result?; println!("{:?}", tx); }
pub fn iter_reader<R: Read, T: for<''de> Deserialize<''de>>(reader: R) -> impl Iterator<Item = super::Result<T>> { /* ... */ }

Function iter_reader_with_recovery

Creates a recoverable iterator over transactions in a reader.

Unlike [iter_reader], this iterator attempts to recover from errors by scanning for the next MAGIC sequence “YPBN” and continuing.

Example

use parser::serde::binary; use std::fs::File; let file = File::open("possibly_corrupt.bin")?; let reader = binary::iter_reader_with_recovery::<_, Transaction>(file); for result in reader { match result { Ok(tx) => println!("Read: {:?}", tx), Err(e) => println!("Skipped corrupt record: {}", e), } } println!("Successfully read: {}, skipped: {}", reader.records_read(), reader.skipped_count());
pub fn iter_reader_with_recovery<R: Read, T: for<''de> Deserialize<''de>>(reader: R) -> RecoverableIterator<R, T> { /* ... */ }

Function to_bytes

Serializes a value to YPBN binary bytes.

Example

let bytes = binary::to_bytes(&transaction)?;
pub fn to_bytes<T: Serialize>(value: &T) -> super::Result<Vec<u8>> { /* ... */ }

Function to_writer

⚠️ Deprecated since 0.2.0: use write_one instead

Serializes a value to a writer in YPBN format.

For optimal performance with seekable writers, consider using to_bytes and writing the result. This function buffers one record.

pub fn to_writer<W: Write, T: Serialize>(writer: &mut W, value: &T) -> super::Result<()> { /* ... */ }

Function from_bytes

Deserializes a value from YPBN binary bytes.

Example

let tx: Transaction = binary::from_bytes(&bytes)?;
pub fn from_bytes<''de, T: Deserialize<''de>>(bytes: &''de [u8]) -> super::Result<T> { /* ... */ }

Function from_reader

⚠️ Deprecated since 0.2.0: use read_one for streaming, or iter_reader for iteration

Deserializes a value from a reader in YPBN format (streaming).

Reads one record. For multiple records, use iter_reader or read_one.

pub fn from_reader<R: Read, T: for<''de> Deserialize<''de>>(reader: &mut R) -> super::Result<Option<T>> { /* ... */ }

Constants and Statics

Constant MAGIC

Magic bytes for YPBN format.

pub const MAGIC: &[u8; 4] = b"YPBN";

Re-exports

Re-export BinaryDeserializer

pub use de::BinaryDeserializer;

Re-export StreamingBinaryDeserializer

pub use de::StreamingBinaryDeserializer;

Re-export BinarySerializer

pub use ser::BinarySerializer;

Module csv

CSV format serialization for YPBank transactions.

This module provides streaming read/write operations for transactions in standard CSV format with a header row.

Format

TX_ID,TX_TYPE,FROM_USER_ID,TO_USER_ID,AMOUNT,TIMESTAMP,STATUS,DESCRIPTION 1234567890,DEPOSIT,0,9876543210,50000,1700000000000,SUCCESS,"Test deposit"

Streaming Example

use parser::serde::csv; use std::fs::File; let file = File::open("transactions.csv")?; for tx in csv::iter_reader(file) { let tx = tx?; println!("{:?}", tx); }
pub mod csv { /* ... */ }

Functions

Function read_one

Reads a single transaction from a CSV reader (streaming).

Important: This function expects the header to be already skipped. Use [iter_reader] for automatic header handling, or manually skip the first line before calling this function.

Returns Ok(Some(tx)) if a transaction was read, Ok(None) at EOF.

Example

use parser::serde::csv; use std::io::BufReader; use std::fs::File; let mut reader = BufReader::new(File::open("transactions.csv")?); // Skip header manually let mut header = String::new(); reader.read_line(&mut header)?; while let Some(tx) = csv::read_one(&mut reader)? { println!("{:?}", tx); }
pub fn read_one<R: BufRead>(reader: &mut R) -> super::Result<Option<crate::transaction::Transaction>> { /* ... */ }

Function skip_header

Skips the CSV header line when reading.

Should be called once before reading the first transaction. Returns Ok(()) even if the file is empty.

Example

use parser::serde::csv; use std::io::BufReader; use std::fs::File; let mut reader = BufReader::new(File::open("transactions.csv")?); csv::skip_header(&mut reader)?; while let Some(tx) = csv::read_one(&mut reader)? { println!("{:?}", tx); }
pub fn skip_header<R: BufRead>(reader: &mut R) -> super::Result<()> { /* ... */ }

Function write_header

Writes the CSV header line.

Should be called once before writing any transactions.

Example

use parser::serde::csv; use std::fs::File; let mut file = File::create("output.csv")?; csv::write_header(&mut file)?; csv::write_one(&mut file, &tx)?;
pub fn write_header<W: Write>(writer: &mut W) -> super::Result<()> { /* ... */ }

Function write_one

Writes a single transaction as a CSV row (streaming).

Example

use parser::serde::csv; use std::fs::File; let mut file = File::create("output.csv")?; csv::write_header(&mut file)?; csv::write_one(&mut file, &tx)?;
pub fn write_one<W: Write>(writer: &mut W, tx: &crate::transaction::Transaction) -> super::Result<()> { /* ... */ }

Function iter_reader

Creates an iterator over transactions in a CSV file.

Automatically skips the header row on the first read.

Example

use parser::serde::csv; use std::fs::File; let file = File::open("transactions.csv")?; for result in csv::iter_reader(file) { let tx = result?; println!("{:?}", tx); }
pub fn iter_reader<R: Read>(reader: R) -> impl Iterator<Item = super::Result<crate::transaction::Transaction>> { /* ... */ }

Function iter_buf_reader

Creates an iterator from a BufRead source (avoids double buffering).

pub fn iter_buf_reader<R: BufRead>(reader: R) -> impl Iterator<Item = super::Result<crate::transaction::Transaction>> { /* ... */ }

Function to_string

Serializes a transaction to a CSV row string (without header).

Example

let row = csv::to_string(&transaction)?;
pub fn to_string<T: Serialize>(value: &T) -> super::Result<String> { /* ... */ }

Function from_str

Deserializes a transaction from a CSV row string (without header).

Example

let row = "1234567890,DEPOSIT,0,9876543210,50000,1700000000000,SUCCESS,\"Test\""; let tx: Transaction = csv::from_str(row)?;
pub fn from_str<T: for<''de> Deserialize<''de>>(s: &str) -> super::Result<T> { /* ... */ }

Constants and Statics

Constant HEADER

CSV header line with all field names.

pub const HEADER: &str = "TX_ID,TX_TYPE,FROM_USER_ID,TO_USER_ID,AMOUNT,TIMESTAMP,STATUS,DESCRIPTION";

Module text

Serde-based text format serialization.

This module provides Serde Serializer and Deserializer implementations for the YPBank text format with KEY: VALUE pairs.

Format

TX_ID: 1234567890 TX_TYPE: DEPOSIT FROM_USER_ID: 0 TO_USER_ID: 9876543210 AMOUNT: 50000 TIMESTAMP: 1700000000000 STATUS: SUCCESS DESCRIPTION: "Test deposit"

Records are separated by empty lines.

Streaming Example

use parser::serde::text; use std::fs::File; let file = File::open("transactions.txt")?; for tx in text::iter_reader(file) { let tx = tx?; println!("{:?}", tx); }
pub mod text { /* ... */ }

Functions

Function read_one

Reads a single transaction from a reader (streaming).

Returns Ok(Some(tx)) if a transaction was read, Ok(None) at EOF. Records are separated by empty lines.

Example

use parser::serde::text; use std::fs::File; use std::io::BufReader; let file = BufReader::new(File::open("transactions.txt")?); while let Some(tx) = text::read_one(&mut reader)? { println!("{:?}", tx); }
pub fn read_one<R: BufRead, T: for<''de> Deserialize<''de>>(reader: &mut R) -> super::Result<Option<T>> { /* ... */ }

Function read_one_from

Reads a single transaction from any Read source.

Wraps the reader in BufReader for buffered line reading.

pub fn read_one_from<R: Read, T: for<''de> Deserialize<''de>>(reader: R) -> super::Result<Option<T>> { /* ... */ }

Function write_one

Writes a single transaction to a writer (streaming).

Appends an empty line after the record to separate from the next one.

Example

use parser::serde::text; use std::fs::File; let mut file = File::create("output.txt")?; text::write_one(&mut file, &tx)?;
pub fn write_one<W: Write, T: Serialize>(writer: &mut W, value: &T) -> super::Result<()> { /* ... */ }

Function iter_reader

Creates an iterator over transactions in a reader.

Example

use parser::serde::text; use std::fs::File; let file = File::open("transactions.txt")?; for result in text::iter_reader::<_, Transaction>(file) { let tx = result?; println!("{:?}", tx); }
pub fn iter_reader<R: Read, T: for<''de> Deserialize<''de>>(reader: R) -> impl Iterator<Item = super::Result<T>> { /* ... */ }

Function iter_buf_reader

Creates an iterator from a BufRead source (avoids double buffering).

pub fn iter_buf_reader<R: BufRead, T: for<''de> Deserialize<''de>>(reader: R) -> impl Iterator<Item = super::Result<T>> { /* ... */ }

Function to_string

Serializes a value to text format string.

Example

let text = text::to_string(&transaction)?;
pub fn to_string<T: Serialize>(value: &T) -> super::Result<String> { /* ... */ }

Function to_writer

⚠️ Deprecated since 0.2.0: use write_one instead

Serializes a value to a writer in text format.

pub fn to_writer<W: Write, T: Serialize>(writer: &mut W, value: &T) -> super::Result<()> { /* ... */ }

Function from_str

Deserializes a value from text format string.

Example

let tx: Transaction = text::from_str(&text)?;
pub fn from_str<''de, T: Deserialize<''de>>(s: &''de str) -> super::Result<T> { /* ... */ }

Function from_reader

⚠️ Deprecated since 0.2.0: use read_one for streaming, or iter_reader for iteration

Deserializes a value from a reader in text format (streaming).

Reads one record. For multiple records, use iter_reader or read_one.

pub fn from_reader<R: Read, T: for<''de> Deserialize<''de>>(reader: R) -> super::Result<Option<T>> { /* ... */ }

Re-exports

Re-export StreamingTextDeserializer

pub use de::StreamingTextDeserializer;

Re-export TextDeserializer

pub use de::TextDeserializer;

Re-export TextSerializer

pub use ser::TextSerializer;

Types

Struct Binary

Marker type for Binary format.

pub struct Binary;
Implementations
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
  • Clone

    • fn clone(self: &Self) -> Binary { /* ... */ }
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
  • Default

    • fn default() -> Binary { /* ... */ }
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      Calls U::from(self).
  • RefUnwindSafe

  • Send

  • SerdeFormat

    • fn read_one<R: BufRead>(reader: &mut R) -> Result<Option<Transaction>> { /* ... */ }
    • fn write_one<W: Write>(writer: &mut W, tx: &Transaction) -> Result<()> { /* ... */ }
  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
  • Unpin

  • UnwindSafe

Struct Text

Marker type for Text format.

pub struct Text;
Implementations
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
  • Clone

    • fn clone(self: &Self) -> Text { /* ... */ }
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
  • Default

    • fn default() -> Text { /* ... */ }
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      Calls U::from(self).
  • RefUnwindSafe

  • Send

  • SerdeFormat

    • fn read_one<R: BufRead>(reader: &mut R) -> Result<Option<Transaction>> { /* ... */ }
    • fn write_one<W: Write>(writer: &mut W, tx: &Transaction) -> Result<()> { /* ... */ }
  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
  • Unpin

  • UnwindSafe

Struct Csv

Marker type for CSV format.

pub struct Csv;
Implementations
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
  • Clone

    • fn clone(self: &Self) -> Csv { /* ... */ }
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
  • Default

    • fn default() -> Csv { /* ... */ }
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      Calls U::from(self).
  • RefUnwindSafe

  • Send

  • SerdeFormat

    • fn read_one<R: BufRead>(reader: &mut R) -> Result<Option<Transaction>> { /* ... */ }
    • fn write_one<W: Write>(writer: &mut W, tx: &Transaction) -> Result<()> { /* ... */ }
    • fn write_header<W: Write>(writer: &mut W) -> Result<()> { /* ... */ }
    • fn skip_header<R: BufRead>(reader: &mut R) -> Result<()> { /* ... */ }
  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
  • Unpin

  • UnwindSafe

Enum Format

Format enum for runtime format selection.

Use this when the format is determined at runtime (e.g., from file extension).

pub enum Format { Binary, Text, Csv, }
Variants
Binary

Binary YPBN format.

Text

Text KEY: VALUE format.

Csv

CSV format with header row.

Implementations
Methods
  • pub fn from_extension(ext: &str) -> Option<Self> { /* ... */ }

    Determines format from file extension.

  • pub fn detect<R: Read>(reader: &mut R) -> Result<Self> { /* ... */ }

    Detects format from file content (magic bytes).

Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
  • Clone

    • fn clone(self: &Self) -> Format { /* ... */ }
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
  • Eq

  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      Returns the argument unchanged.
  • Hash

    • fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ }
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      Calls U::from(self).
  • PartialEq

    • fn eq(self: &Self, other: &Format) -> bool { /* ... */ }
  • RefUnwindSafe

  • Send

  • StructuralPartialEq

  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
  • Unpin

  • UnwindSafe

Traits

Trait SerdeFormat

Trait for streaming serialization/deserialization of transactions.

Implemented by marker types (Binary, Text, Csv) to provide format-specific streaming operations.

Note: read_one takes BufRead to support text format’s line-by-line reading. For binary format, BufRead is a superset of Read, so it works seamlessly.

pub trait SerdeFormat { /* Associated items */ }

This trait is not object-safe and cannot be used in dynamic trait objects.

Required Items
Required Methods
  • read_one: Reads a single transaction from a buffered reader.
  • write_one: Writes a single transaction to a writer.
Provided Methods
  • fn write_header<W: Write>(_writer: &mut W) -> Result<()> { /* ... */ }

    Writes a header if the format requires one.

  • fn skip_header<R: BufRead>(_reader: &mut R) -> Result<()> { /* ... */ }

    Skips the header when reading, if the format has one.

Implementations

This trait is implemented for the following types:

  • Binary
  • Text
  • Csv

Re-exports

Re-export Error

pub use error::Error;

Re-export Result

pub use error::Result;

Module transaction

Модель данных транзакций для форматов YPBank.

Этот модуль определяет основную структуру [Transaction] и связанные типы, общие для всех форматов YPBank (Text, Binary, CSV).

pub mod transaction { /* ... */ }

Re-exports

Re-export Transaction

pub use types::Transaction;

Re-export TransactionStatus

pub use types::TransactionStatus;

Re-export TransactionType

pub use types::TransactionType;

Re-export ValidationError

pub use validation::ValidationError;

Module writer

Потоковый writer для транзакций.

Предоставляет [TransactionWriter] для записи транзакций в любой тип, реализующий [Write].

pub mod writer { /* ... */ }

Types

Struct TransactionWriter

Потоковый writer для транзакций.

Использует буферизацию для эффективного I/O.

Type Parameters

  • W: целевой поток (реализует [Write])
  • F: формат (реализует [SerdeFormat])

Пример

use parser::writer::TransactionWriter; use parser::serde::Text; use std::fs::File; let file = File::create("output.txt")?; let mut writer = TransactionWriter::<_, Text>::new(file); writer.write_header()?; writer.write(&tx1)?; writer.write(&tx2)?; writer.flush()?;
pub struct TransactionWriter<W: Write, F: SerdeFormat> { // Some fields omitted }
Fields
NameTypeDocumentation
private fieldsSome fields have been omitted
Implementations
Methods
  • pub fn new(writer: W) -> Self { /* ... */ }

    Создаёт новый writer.

  • pub fn with_capacity(capacity: usize, writer: W) -> Self { /* ... */ }

    Создаёт writer с указанным размером буфера.

  • pub fn write_header(self: &mut Self) -> Result<()> { /* ... */ }

    Записывает заголовок формата (если он есть).

  • pub fn write(self: &mut Self, tx: &Transaction) -> Result<()> { /* ... */ }

    Записывает одну транзакцию.

  • pub fn write_all(self: &mut Self, txs: &[Transaction]) -> Result<()> { /* ... */ }

    Записывает несколько транзакций.

  • pub fn flush(self: &mut Self) -> Result<()> { /* ... */ }

    Принудительно сбрасывает буфер.

  • pub fn records_written(self: &Self) -> usize { /* ... */ }

    Возвращает количество записанных транзакций.

  • pub fn get_ref(self: &Self) -> &W { /* ... */ }

    Получает ссылку на внутренний writer.

  • pub fn into_inner(self: Self) -> std::result::Result<W, std::io::IntoInnerError<BufWriter<W>>> { /* ... */ }

    Извлекает внутренний writer (с предварительным flush).

Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      Calls U::from(self).
  • RefUnwindSafe

  • Send

  • Sync

  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
  • Unpin

  • UnwindSafe

Module prelude

Prelude для удобного импорта часто используемых типов.

use parser::prelude::*;
pub mod prelude { /* ... */ }

Re-exports

Re-export TransactionReader

pub use crate::reader::TransactionReader;

Re-export Binary

pub use crate::serde::Binary;

Re-export Csv

pub use crate::serde::Csv;

Re-export Format

pub use crate::serde::Format;

Re-export Result

pub use crate::serde::Result as SerdeResult;

Re-export SerdeFormat

pub use crate::serde::SerdeFormat;

Re-export Text

pub use crate::serde::Text;

Re-export binary

pub use crate::serde::binary;

Re-export csv

pub use crate::serde::csv;

Re-export text

pub use crate::serde::text;

Re-export Transaction

pub use crate::transaction::Transaction;

Re-export TransactionStatus

pub use crate::transaction::TransactionStatus;

Re-export TransactionType

pub use crate::transaction::TransactionType;

Re-export ValidationError

pub use crate::transaction::ValidationError;

Re-export TransactionWriter

pub use crate::writer::TransactionWriter;