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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/* util.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Internal utility types for the AVRoxide concurrency implementation.

// Imports ===================================================================
use avr_oxide::util::datatypes::{VolatileBitField, BitIndex, BitFieldAccess};
use avr_oxide::concurrency::interrupt;
use avr_oxide::concurrency::scheduler;
use avr_oxide::deviceconsts::oxide;

// Declarations ==============================================================
/**
 * A thread ID.
 */
pub type ThreadId = usize;

#[repr(C)]
pub struct ThreadSet {
  threadids: VolatileBitField
}

// Code =====================================================================
const THREADSET_SIZE: usize = oxide::MAX_THREADS;

impl ThreadSet {
  pub fn new() -> Self {
    ThreadSet {
      threadids: VolatileBitField::all_clr()
    }
  }

  pub fn add_thread(&mut self, isotoken: interrupt::token::Isolated, id: ThreadId){
    self.threadids.set_isolated(isotoken, BitIndex::bit(id));
  }
  pub fn add_current_thread(&mut self, isotoken: interrupt::token::Isolated){
    self.add_thread(isotoken, scheduler::current_thread_id(isotoken));
  }
  pub fn remove_thread(&mut self, isotoken: interrupt::token::Isolated, id: ThreadId){
    self.threadids.clr_isolated(isotoken, BitIndex::bit(id));
  }
  pub fn remove_current_thread(&mut self, isotoken: interrupt::token::Isolated){
    self.remove_thread(isotoken, scheduler::current_thread_id(isotoken));
  }
  pub fn contains_thread(&self, _isotoken: interrupt::token::Isolated, id: ThreadId) -> bool {
    self.threadids.is_set(BitIndex::bit(id))
  }
  pub fn contains_current_thread(&self, isotoken: interrupt::token::Isolated) -> bool {
    self.contains_thread(isotoken, scheduler::current_thread_id(isotoken))
  }
  pub fn remove_all(&mut self) {
    self.threadids.clr_all()
  }

  /// Execute the given closure for each thread in this threadset.
  ///
  /// The closure should return a boolean indicating if it should continue
  /// iterating through the threads.
  pub fn do_each<F>(&self, isotoken: interrupt::token::Isolated, mut f: F)
  where
    F: FnMut(interrupt::token::Isolated, ThreadId) -> bool
  {
    for id in 0..THREADSET_SIZE {
      if self.contains_thread(isotoken, id) {
        let cont = (f)(isotoken, id);

        if !cont {
          break;
        }
      }
    }
  }

  /// Execute the given closure for each thread in this threadset.
  /// The thread is removed from the threadset following execution of the
  /// closure.
  ///
  /// The closure should return a boolean indicating if it should continue
  /// iterating through the threads.
  pub fn do_each_consuming<F>(&mut self, isotoken: interrupt::token::Isolated, mut f: F)
  where
    F: FnMut(interrupt::token::Isolated, ThreadId) -> bool
  {
    for id in 0..THREADSET_SIZE {
      if self.contains_thread(isotoken, id) {
        let cont = (f)(isotoken, id);

        self.remove_thread(isotoken, id);

        if !cont {
          break;
        }
      }
    }
  }
}



// Tests =====================================================================
#[cfg(test)]
mod tests {
  use std::fmt::{Debug, Formatter};
  use avr_oxide::concurrency::util::{ThreadId, ThreadSet};
  use avr_oxide::deviceconsts::oxide::MAX_THREADS;

  #[test]
  fn test_threadset() {
    let mut threadset = ThreadSet::new();

    assert!(MAX_THREADS >= 4);

    avr_oxide::concurrency::interrupt::isolated(|isotoken|{
      threadset.add_thread(isotoken, 1u8.into());
      threadset.add_thread(isotoken, 3u8.into());

      assert!(!threadset.contains_thread(isotoken,0u8.into()));
      assert!(threadset.contains_thread(isotoken, 1u8.into()));
      assert!(!threadset.contains_thread(isotoken, 2u8.into()));
      assert!(threadset.contains_thread(isotoken, 3u8.into()));
    })
  }

  #[test]
  fn test_threadset_doeach() {
    let mut threadset = ThreadSet::new();

    assert!(MAX_THREADS >= 4);

    avr_oxide::concurrency::interrupt::isolated(|isotoken|{
      threadset.add_thread(isotoken, 1u8.into());
      threadset.add_thread(isotoken, 3u8.into());

      println!("Testing threadset do_each:");
      let mut total = 0usize;
      threadset.do_each(isotoken, |isotoken,thread_id|{
        total += thread_id;

        println!("Iterating - thread id {:?}", thread_id);

        assert_ne!(thread_id, 0u8.into());
        assert_ne!(thread_id, 2u8.into());
        true
      });
      assert_eq!(total, 4);
      assert!(threadset.contains_thread(isotoken,1u8.into()));
      assert!(threadset.contains_thread(isotoken, 3u8.into()));

      // Now test the consuming version
      println!("Testing threadset do_each_consuming:");
      total = 0;
      threadset.do_each_consuming(isotoken, |isotoken,thread_id|{
        total += thread_id;

        println!("Iterating - thread id {:?}", thread_id);

        assert_ne!(thread_id, 0u8.into());
        assert_ne!(thread_id, 2u8.into());
        true
      });
      assert_eq!(total, 4);
      assert!(!threadset.contains_thread(isotoken,0u8.into()));
      assert!(!threadset.contains_thread(isotoken,1u8.into()));
      assert!(!threadset.contains_thread(isotoken,2u8.into()));
      assert!(!threadset.contains_thread(isotoken, 3u8.into()));
    })
  }
}