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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
extern crate alloc;
use core::cmp;
use crate::heap::*;
use crate::sharedmutex::*;

#[cfg(feature="no_std_support")]
use alloc::format;
#[cfg(feature="no_std_support")]
use alloc::vec::Vec;
#[cfg(feature="no_std_support")]
use alloc::string::String;
#[cfg(feature="no_std_support")]
use alloc::borrow::ToOwned;

/// Storage for runtime byte buffer values
static mut BH:SharedMutex<Heap<DataStream>> = SharedMutex::new();

/// Storage for runtime reference count reductions
static mut BD:SharedMutex<Vec<usize>> = SharedMutex::new();

/// Implements a stream of bytes
#[derive(Debug, Default)]
pub struct DataStream {
  /// Raw data currently held in stream
  data: Vec<u8>,
  /// Length of data to be sent in this stream. Value should be zero (unset) or fixed (unchanging) value.
  len: usize,
  /// Indicates whether the current stream is open to reading
  read_open: bool,
  /// Indicates whether the current stream is open to writing
  write_open: bool,
  /// Optional MIME type of this stream
  mime_type: Option<String>,
}

impl DataStream {
  /// Create a new (empty) byte stream.
  pub fn new() -> Self {
    DataStream {
      data: Vec::new(),
      len: 0,
      read_open: true,
      write_open: true,
      mime_type: None,
    }
  }
  
   /// Create a new byte stream from a Vec<u8>.
  pub fn from_bytes(buf:Vec<u8>) -> DataStream {
    let len = buf.len();
    DataStream {
      data: buf,
      len: len,
      read_open: true,
      write_open: false,
      mime_type: None,
    }
  }
  
  /// Return a deep copy of the data stream
  pub fn deep_copy(&self) -> DataStream {
    DataStream {
      data: self.data.to_owned(),
      len: self.len,
      read_open: self.read_open,
      write_open: self.write_open,
      mime_type: self.mime_type.to_owned(),
    }
  }  
}

/// **DO NOT USE**
///
/// This function should only be used externally by DataArray and DataObject
pub fn bheap() -> &'static mut SharedMutex<Heap<DataStream>> {
  unsafe { &mut BH }
}

fn bdrop() -> &'static mut SharedMutex<Vec<usize>> {
  unsafe { &mut BD }
}

/// Represents a buffer of bytes (```Vec<u8>```)
#[derive(Debug, Default)]
pub struct DataBytes {
  /// The pointer to the array in the byte buffer heap.
  pub data_ref: usize,
}

impl Clone for DataBytes{
  /// Returns another DataBytes pointing to the same value.
  fn clone(&self) -> Self {
    let o = DataBytes{
      data_ref: self.data_ref,
    };
    let _x = &mut bheap().lock().incr(self.data_ref);
    o
  }
}

impl DataBytes {
  /// Initialize global storage of byte buffers. Call only once at startup.
  #[cfg(not(feature="mirror"))]
  pub fn init(){
    unsafe {
      BH.set(Heap::new());
      BD.set(Vec::new());
    }
  }
  #[cfg(feature="mirror")]
  pub fn init() -> ((u64, u64), (u64, u64)){
    unsafe{
      BH.init();
      BD.init();
      let q = BH.share();
      let r = BD.share();
      (q, r)
    }
  }
  
  /// Mirror global storage of arrays from another process. Call only once at startup.
  #[cfg(feature="mirror")]
  pub fn mirror(q:(u64, u64), r:(u64, u64)){
    unsafe { 
      BH = SharedMutex::mirror(q.0, q.1);
      BD = SharedMutex::mirror(r.0, r.1);
    }
  }
  
  /// Create a new (empty) byte buffer.
  pub fn new() -> DataBytes {
    let data_ref = &mut bheap().lock().push(DataStream::new());
    return DataBytes {
      data_ref: *data_ref,
    };
  }
  
  /// Create a new byte buffer from a Vec<u8>.
  pub fn from_bytes(buf:&Vec<u8>) -> DataBytes {
    let data_ref = &mut bheap().lock().push(DataStream::from_bytes(buf.to_vec()));
    return DataBytes {
      data_ref: *data_ref,
    };
  }
  
  /// Returns a copy of the underlying vec of bytes in the array
  pub fn get_data(&self) -> Vec<u8> {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.data.to_owned()
  }
  
  /// Appends the given slice to the end of the bytes in the array
  pub fn write(&self, buf:&[u8]) {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    if !vec.write_open || !vec.read_open { panic!("Attempt to write to closed data stream"); }
    vec.data.extend_from_slice(buf);
  }
  
  /// Removes and returns up to the requested number of bytes from the array
  pub fn read(&self, n:usize) -> Vec<u8> {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    if !vec.read_open { panic!("Attempt to read from closed data stream"); }
    let n = cmp::min(n, vec.data.len());
    let d = vec.data[0..n].to_vec();
    vec.data.drain(0..n);
    if !vec.write_open && vec.data.len() == 0 {
      vec.read_open = false;
    }
    d
  }
  
  /// Sets the underlying vec of bytes in the array
  pub fn set_data(&self, buf:&Vec<u8>) {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    let len = buf.len();
    vec.data.resize(len, 0); // FIXME - Is this necessary?
    vec.data.clone_from_slice(buf);
    vec.len = len;
    vec.write_open = false;
  }
  
  /// Get the number of bytes currently in the underlying byte buffer
  pub fn current_len(&self) -> usize {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.data.len()
  }
  
  /// Get the declared total number of bytes in the stream
  pub fn stream_len(&self) -> usize {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.len
  }
  
  /// Set the declared total number of bytes in the stream
  pub fn set_stream_len(&self, len: usize) {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.len = len;
  }
  
  /// Return true if the underlying data stream is open for writing
  pub fn is_write_open(&self) -> bool {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.write_open
  }
  
  /// Return true if the underlying data stream is open for reading
  pub fn is_read_open(&self) -> bool {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.read_open
  }
  
  /// Close the underlying data stream to further writing
  pub fn close_write(&self) {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.write_open = false;
  }
  
  /// Close the underlying data stream to further reading
  pub fn close_read(&self) {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.read_open = false;
  }
  
  /// Set the optional MIME type for this stream
  pub fn set_mime_type(&self, mime:Option<String>) {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.mime_type = mime;
  }
  
  /// Get the optional MIME type for this stream
  pub fn get_mime_type(&self) -> Option<String> {
    let heap = &mut bheap().lock();
    let vec = heap.get(self.data_ref);
    vec.mime_type.to_owned()
  }
  
  /// Get a reference to the byte buffer from the heap
  pub fn get(data_ref: usize) -> DataBytes {
    let o = DataBytes{
      data_ref: data_ref,
    };
    let _x = &mut bheap().lock().incr(data_ref);
    o
  }
  
  /// Increase the reference count for this DataBytes.
  pub fn incr(&self) {
    let bheap = &mut bheap().lock();
    bheap.incr(self.data_ref); 
  }

  /// Decrease the reference count for this DataBytes.
  pub fn decr(&self) {
    let bheap = &mut bheap().lock();
    bheap.decr(self.data_ref); 
  }

  /// Returns a new ```DataBytes``` that points to the same underlying byte buffer.
  #[deprecated(since="0.3.0", note="please use `clone` instead")]
  pub fn duplicate(&self) -> DataBytes {
    self.clone()
  }
  
  /// Returns a new ```DataBytes``` that points to a copy of the underlying byte buffer.
  pub fn deep_copy(&self) -> DataBytes {
    let heap = &mut bheap().lock();
    let bytes = heap.get(self.data_ref);
    let vec = bytes.deep_copy();
    let data_ref = &mut bheap().lock().push(vec);
    return DataBytes {
      data_ref: *data_ref,
    };
  }
  
  /// Returns the byte buffer as a hexidecimal String.
  pub fn to_hex_string(&self) -> String {
    let heap = &mut bheap().lock();
    let bytes = heap.get(self.data_ref);
    let strs: Vec<String> = bytes.data.iter()
                                 .map(|b| format!("{:02X}", b))
                                 .collect();
    strs.join(" ")    
  }
  
  /// Prints the byte buffers currently stored in the heap
  #[cfg(not(feature="no_std_support"))]
  pub fn print_heap() {
    println!("object {:?}", &mut bheap().lock());
  }
  
  /// Perform garbage collection. Byte buffers will not be removed from the heap until
  /// ```DataBytes::gc()``` is called.
  pub fn gc() {
    let bheap = &mut bheap().lock();
    let bdrop = &mut bdrop().lock();
    let mut i = bdrop.len();
    while i>0 {
      i = i - 1;
      let x = bdrop.remove(0);
      bheap.decr(x);
    }
  }
}

/// Adds this ```DataBytes```'s data_ref to BDROP. Reference counts are adjusted when
/// ```DataBytes::gc()``` is called.
impl Drop for DataBytes {
  fn drop(&mut self) {
    bdrop().lock().push(self.data_ref);
  }
}