1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use ed25519_dalek::{PublicKey, SecretKey};

use bitfield::Bitfield;
use crypto::Merkle;
use random_access_storage::RandomAccessMethods;
use std::fmt::Debug;
use storage::Storage;
use tree_index::TreeIndex;

use Feed;
use Result;

/// Construct a new `Feed` instance.
// TODO: make this an actual builder pattern.
// https://deterministic.space/elegant-apis-in-rust.html#builder-pattern
#[derive(Debug)]
pub struct FeedBuilder<T>
where
  T: RandomAccessMethods + Debug,
{
  storage: Storage<T>,
  public_key: PublicKey,
  secret_key: Option<SecretKey>,
}

impl<T> FeedBuilder<T>
where
  T: RandomAccessMethods + Debug,
{
  /// Create a new instance.
  #[inline]
  pub fn new(public_key: PublicKey, storage: Storage<T>) -> Self {
    Self {
      storage,
      public_key,
      secret_key: None,
    }
  }

  /// Set the secret key.
  pub fn secret_key(mut self, secret_key: SecretKey) -> Self {
    self.secret_key = Some(secret_key);
    self
  }

  /// Finalize the builder.
  #[inline]
  pub fn build(self) -> Result<Feed<T>> {
    Ok(Feed {
      merkle: Merkle::new(),
      byte_length: 0,
      length: 0,
      bitfield: Bitfield::default(),
      tree: TreeIndex::default(),
      public_key: self.public_key,
      secret_key: self.secret_key,
      storage: self.storage,
      peers: vec![],
    })
  }
}