Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::sync::Mutex;
- use std::vec::Vec;
- struct Environment {
- data: Mutex<Vec<Block>>,
- }
- impl Environment {
- pub fn new() -> Self {
- Self {
- data: Mutex::new(Vec::new())
- }
- }
- pub fn push(&self, data: &Block) {
- self.data.lock().unwrap().push(data.clone());
- }
- pub fn last(&self) -> Option<u32> {
- self.data.lock().unwrap().last().map(|block| block.height)
- }
- }
- #[derive(Clone)]
- struct Block {
- height: u32,
- }
- struct Blockchain<'env> {
- store: &'env Environment,
- }
- impl<'env> Blockchain<'env> {
- pub fn new(store: &'env Environment) -> Self {
- Self {
- store,
- }
- }
- pub fn push(&self, block: Block) {
- self.store.push(&block);
- }
- pub fn height(&self) -> u32 {
- self.store.last().unwrap_or(0)
- }
- }
- fn next_block<'env, 'bc>(blockchain: &'bc Blockchain<'env>) -> BlockBuilder<'bc, 'env> {
- BlockBuilder::new(blockchain)
- }
- struct BlockBuilder<'env, 'bc> {
- blockchain: &'bc Blockchain<'env>,
- block: Block,
- }
- impl<'env, 'bc> BlockBuilder<'env, 'bc> {
- pub fn new(blockchain: &'bc Blockchain<'env>) -> Self {
- Self {
- blockchain,
- block: Block { height: 0 },
- }
- }
- pub fn with_real_height(mut self) -> Self {
- self.block.height = self.blockchain.height() + 1;
- self
- }
- pub fn build(mut self) -> Block {
- self.block
- }
- }
- fn main() {
- let env = Environment::new();
- let blockchain = Blockchain::new(&env);
- let block2 = next_block(&blockchain)
- .with_real_height()
- .build();
- blockchain.push(block2);
- let block3 = crate::next_block(&blockchain)
- .with_real_height()
- .build();
- blockchain.push(block3);
- let block4 = crate::next_block(&blockchain)
- .with_real_height()
- .build();
- blockchain.push(block4);
- }
Add Comment
Please, Sign In to add comment