Guest User

Untitled

a guest
Jan 15th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. use std::sync::Mutex;
  2. use std::vec::Vec;
  3.  
  4. struct Environment {
  5. data: Mutex<Vec<Block>>,
  6. }
  7.  
  8. impl Environment {
  9. pub fn new() -> Self {
  10. Self {
  11. data: Mutex::new(Vec::new())
  12. }
  13. }
  14.  
  15. pub fn push(&self, data: &Block) {
  16. self.data.lock().unwrap().push(data.clone());
  17. }
  18.  
  19. pub fn last(&self) -> Option<u32> {
  20. self.data.lock().unwrap().last().map(|block| block.height)
  21. }
  22. }
  23.  
  24. #[derive(Clone)]
  25. struct Block {
  26. height: u32,
  27. }
  28.  
  29. struct Blockchain<'env> {
  30. store: &'env Environment,
  31. }
  32.  
  33. impl<'env> Blockchain<'env> {
  34. pub fn new(store: &'env Environment) -> Self {
  35. Self {
  36. store,
  37. }
  38. }
  39.  
  40. pub fn push(&self, block: Block) {
  41. self.store.push(&block);
  42. }
  43.  
  44. pub fn height(&self) -> u32 {
  45. self.store.last().unwrap_or(0)
  46. }
  47. }
  48.  
  49. fn next_block<'env, 'bc>(blockchain: &'bc Blockchain<'env>) -> BlockBuilder<'bc, 'env> {
  50. BlockBuilder::new(blockchain)
  51. }
  52.  
  53. struct BlockBuilder<'env, 'bc> {
  54. blockchain: &'bc Blockchain<'env>,
  55. block: Block,
  56. }
  57.  
  58. impl<'env, 'bc> BlockBuilder<'env, 'bc> {
  59. pub fn new(blockchain: &'bc Blockchain<'env>) -> Self {
  60. Self {
  61. blockchain,
  62. block: Block { height: 0 },
  63. }
  64. }
  65.  
  66. pub fn with_real_height(mut self) -> Self {
  67. self.block.height = self.blockchain.height() + 1;
  68. self
  69. }
  70.  
  71. pub fn build(mut self) -> Block {
  72. self.block
  73. }
  74. }
  75.  
  76. fn main() {
  77. let env = Environment::new();
  78. let blockchain = Blockchain::new(&env);
  79.  
  80. let block2 = next_block(&blockchain)
  81. .with_real_height()
  82. .build();
  83.  
  84. blockchain.push(block2);
  85.  
  86. let block3 = crate::next_block(&blockchain)
  87. .with_real_height()
  88. .build();
  89. blockchain.push(block3);
  90.  
  91. let block4 = crate::next_block(&blockchain)
  92. .with_real_height()
  93. .build();
  94. blockchain.push(block4);
  95. }
Add Comment
Please, Sign In to add comment