bitcoin_explorer/parser/
reader.rs

1use crate::parser::errors::OpResult;
2use bitcoin::consensus::Decodable;
3use bitcoin::{Block, BlockHeader, Transaction};
4use byteorder::{LittleEndian, ReadBytesExt};
5use std::fs::File;
6use std::io::{BufReader, Cursor};
7
8///
9/// binary file read utilities.
10///
11pub trait BlockchainRead: std::io::Read {
12    #[inline]
13    fn read_varint(&mut self) -> OpResult<usize> {
14        let mut n = 0;
15        loop {
16            let ch_data = self.read_u8()?;
17            n = (n << 7) | (ch_data & 0x7F) as usize;
18            if ch_data & 0x80 > 0 {
19                n += 1;
20            } else {
21                break;
22            }
23        }
24        Ok(n)
25    }
26
27    #[inline]
28    fn read_u8(&mut self) -> OpResult<u8> {
29        let mut slice = [0u8; 1];
30        self.read_exact(&mut slice)?;
31        Ok(slice[0])
32    }
33
34    #[inline]
35    fn read_u256(&mut self) -> OpResult<[u8; 32]> {
36        let mut arr = [0u8; 32];
37        self.read_exact(&mut arr)?;
38        Ok(arr)
39    }
40
41    #[inline]
42    fn read_u32(&mut self) -> OpResult<u32> {
43        let u = ReadBytesExt::read_u32::<LittleEndian>(self)?;
44        Ok(u)
45    }
46
47    #[inline]
48    fn read_i32(&mut self) -> OpResult<i32> {
49        let u = ReadBytesExt::read_i32::<LittleEndian>(self)?;
50        Ok(u)
51    }
52
53    #[inline]
54    fn read_u8_vec(&mut self, count: u32) -> OpResult<Vec<u8>> {
55        let mut arr = vec![0u8; count as usize];
56        self.read_exact(&mut arr)?;
57        Ok(arr)
58    }
59
60    #[inline]
61    fn read_block(&mut self) -> OpResult<Block> {
62        Ok(Block::consensus_decode(self)?)
63    }
64
65    #[inline]
66    fn read_transaction(&mut self) -> OpResult<Transaction> {
67        Ok(Transaction::consensus_decode(self)?)
68    }
69
70    #[inline]
71    fn read_block_header(&mut self) -> OpResult<BlockHeader> {
72        Ok(BlockHeader::consensus_decode(self)?)
73    }
74}
75
76impl BlockchainRead for Cursor<&[u8]> {}
77impl BlockchainRead for Cursor<Vec<u8>> {}
78impl BlockchainRead for BufReader<File> {}