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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Utility class to communicate between components
//!
//! This class provides three structs : IP, Ports and IPSender.


extern crate capnp;
#[allow(unused_imports)]
use std::io::Read;

use result;
use result::Result;

use std::collections::HashMap;
use std::mem;

use std::sync::mpsc::{Sender, Receiver, SyncSender};
use std::sync::mpsc::sync_channel;

use scheduler::CompMsg;

/// Represent an IP
pub struct IP {
    /// The capn'p representation
    pub vec: Vec<u8>,
    /// is the action of the IP
    pub action: String,
    reader: Option<capnp::message::Reader<capnp::serialize::OwnedSegments>>,
    builder: Option<capnp::message::Builder<capnp::message::HeapAllocator>>,
}

impl IP {
    /// Return a new IP
    ///
    /// # Example
    /// ```rust,ignore
    /// let ip = IP::new();
    /// ```
    pub fn new() -> Self {
        IP { vec: vec![],
             action: String::new(),
             reader: None,
             builder: None,
        }
    }

    /// Return a capnp `Reader`
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let ip = an_initialized_ip;
    /// {
    ///     let reader: generic_text::Reader = try!(ip.get_root());
    ///     let text = try!(reader.get_text());
    /// }
    /// ```
    pub fn get_root<'a, T: capnp::traits::FromPointerReader<'a>>(&'a mut self) -> Result<T> {
        let msg = try!(capnp::serialize::read_message(&mut &self.vec[..], capnp::message::ReaderOptions::new()));
        self.reader = Some(msg);
        Ok(try!(self.reader.as_ref().unwrap().get_root()))
    }

    /// Return a capnp `Builder`
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut ip = IP::new();
    /// // Initialize the IP
    /// {
    ///     let mut builder: generic_text::Builder = ip.init_root();
    ///     builder.set_text("Hello Fractalide!");
    /// }
    /// ```
    pub fn init_root<'a, T: capnp::traits::FromPointerBuilder<'a>>(&'a mut self) -> T {
        let msg = capnp::message::Builder::new_default();
        self.builder = Some(msg);
        self.builder.as_mut().unwrap().init_root()
    }

    /// Return a capnp `Builder` from a capnp `Reader`
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut ip = an_initialized_ip;
    /// {
    ///     let mut builder = try!(init_root_from_reader::<generic_text::Builder, generic_text::Reader>());
    ///     builder.set_text("Hello Fractalide!");
    /// }
    /// ```
    pub fn init_root_from_reader<'a, T: capnp::traits::FromPointerBuilder<'a>,
                                 U: capnp::traits::FromPointerReader<'a> + capnp::traits::SetPointerBuilder<T>>
        (&'a mut self) -> Result<T> {
        let reader = try!(capnp::serialize::read_message(&mut &self.vec[..], capnp::message::ReaderOptions::new()));
        self.reader = Some(reader);
        let reader: U = try!(self.reader.as_ref().unwrap().get_root());

        let mut msg = capnp::message::Builder::new_default();
        try!(msg.set_root(reader));
        self.builder = Some(msg);
        Ok(try!(self.builder.as_mut().unwrap().get_root()))
    }

    /// Write the capnp `Builer` to the `Vec`
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let mut ip = an_initialized_ip;
    /// {
    ///     let mut builder = try!(init_root_from_reader::<generic_text::Builder, generic_text::Reader>());
    ///     builder.set_text("Hello Fractalide!");
    /// }
    /// try!(ip.before_send());
    /// ```
    pub fn before_send(&mut self) -> Result<()> {
        let mut build = mem::replace(&mut self.builder, None);
        if let Some(ref mut b) = build {
            self.vec.clear();
            try!(capnp::serialize::write_message(&mut self.vec, b))
        }
        Ok(())

    }
}

impl Clone for IP {
    fn clone(&self) -> Self {
        IP {
            vec: self.vec.clone(),
            action: self.action.clone(),
            reader: None,
            builder: None,
        }
    }
}

/// An wrapper around `SyncSender<IP>`
///
/// A specific `SyncSender` for the IP object. It also send information to the scheduler.
#[derive(Clone)]
pub struct IPSender {
    /// The SyncSender, connected to a receiver in another component
    pub sender: SyncSender<IP>,
    /// The name of the component owning the receiver
    pub dest: String,
    /// A Sender to the scheduler, to signal that the receiver must be run
    pub sched: Sender<CompMsg>,
}

impl IPSender {
    /// Send an IP to the Receiver
    pub fn send(&self, mut ip: IP) -> Result<()> {
        try!(ip.before_send());
        try!(self.sender.send(ip));
        if self.dest != "" {
            try!(self.sched.send(CompMsg::Inc(self.dest.clone())));
        }
        Ok(())
    }
}

/// Represents all the ports of a component
///
/// It provides help to send and receive IP, and to create ports.
pub struct Ports {
    /// The name of the component owning this structure
    name: String,
    /// A Sender to the scheduler owning the component
    sched: Sender<CompMsg>,
    /// All the receiver of the inputs ports
    inputs: HashMap<String, Receiver<IP>>,
    /// All the receiver of the input array ports
    inputs_array: HashMap< String, HashMap<String, Receiver<IP>>>,
    /// Place for the future IPSender in output port (to be connected)
    outputs: HashMap<String, Option<IPSender>>,
    /// Place for the future IPSender in output array port (to be connected)
    outputs_array: HashMap<String, HashMap<String, Option<IPSender>>>,
    /// The IPSender linked corresponding to the input ports
    senders: HashMap<String, IPSender>,
}

impl Ports {
    /// Create a new Ports
    ///
    /// # Example
    /// ```rust,ignore
    /// let ports = try!(Ports::new("component".to_string(),
    ///                        sched_sender,
    ///                        vec!["input".to_string()], vec![],
    ///                        vec!["output".to_string()], vec![]));
    /// let sender = try!(ports.get_sender("input"));
    /// ```
    pub fn new(name: String, sched: Sender<CompMsg>,
               n_input: Vec<String>, n_input_array: Vec<String>,
               n_output: Vec<String>, n_output_array: Vec<String>) -> Result<(Self, HashMap<String, IPSender>)> {
        let mut senders: HashMap<String, IPSender> = HashMap::new();
        let mut inputs = HashMap::new();
        for i in n_input {
            let (s, r) = sync_channel(25);
            let s = IPSender {
                sender: s,
                dest: if i != "acc" && i != "option" { name.clone() } else { "".into() },
                sched: sched.clone(),
            };
            senders.insert(i.clone(), s);
            inputs.insert(i, r);
        }
        let mut inputs_array = HashMap::new();
        for i in n_input_array { inputs_array.insert(i, HashMap::new()); }
        let mut outputs = HashMap::new();
        for i in n_output { outputs.insert(i, None); }
        let mut outputs_array = HashMap::new();
        for i in n_output_array { outputs_array.insert(i, HashMap::new()); }
        let ports = Ports {
            name: name,
            sched: sched,
            inputs: inputs,
            inputs_array: inputs_array,
            outputs: outputs,
            outputs_array: outputs_array,
            senders: senders.clone(),
        };

        Ok((ports, senders))
    }

    /// Get the sender of a input ports
    ///
    /// # Example
    /// ```rust,ignore
    /// let sender = try!(ports.get_sender("input"));
    /// let ip = IP::new();
    /// try!(sender.send(ip));
    /// ```
    pub fn get_sender(&self, port_in: &str) -> Result<IPSender> {
        self.senders.get(port_in).ok_or(result::Error::PortNotFound(self.name.clone(), port_in.into()))
            .map(|sender| {
                sender.clone()
            })
    }

    /// Get the sender of a input array ports
    ///
    /// # Example
    /// ```rust,ignore
    /// let sender = try!(ports.get_sender("inputs", "1"));
    /// let ip = IP::new();
    /// try!(sender.send(ip));
    /// ```
    pub fn get_array_sender(&self, port_name: &str, selection: &str) -> Result<IPSender> {
        self.outputs_array.get(port_name).ok_or(result::Error::PortNotFound(self.name.clone(), port_name.into()))
            .and_then(|port|{
                port.get(selection).ok_or(result::Error::SelectionNotFound(self.name.clone(), port_name.into(), selection.into()))
                    .and_then(|recv| {
                        recv.as_ref().ok_or(result::Error::ArrayOutputPortNotConnected(self.name.clone(), port_name.into(), selection.into()))
                            .and_then(|sender| {
                                Ok(sender.clone())
                            })
                    })
            })
    }

    /// Get the list of the current selections in a array input port
    ///
    /// # Example
    /// ```rust,ignore
    /// let vec = try!(ports.get_input_selections("inputs"));
    /// assert_eq!(vec.length(), 0);
    /// try!(ports.add_input_selection("inputs", "1"));
    /// try!(ports.add_input_selection("inputs", "2"));
    /// let vec = try!(ports.get_input_selections("inputs"));
    /// for i in vec {
    ///     print!("{} ", i);
    /// }
    /// // Produce `1 2`
    /// ```
    pub fn get_input_selections(&self, port_in: &'static str) -> Result<Vec<String>> {
        self.inputs_array.get(port_in).ok_or(result::Error::PortNotFound(self.name.clone(), port_in.into()))
            .map(|port| {
                port.keys().cloned().collect()
            })
    }

    /// Get the list of the current selections in a array output port
    ///
    /// # Example
    /// ```rust,ignore
    /// let vec = try!(ports.get_output_selections("outputs"));
    /// assert_eq!(vec.length(), 0);
    /// try!(ports.add_output_selection("outputs", "1"));
    /// try!(ports.add_output_selection("outputs", "2"));
    /// let vec = try!(ports.get_output_selections("outputs"));
    /// for i in vec {
    ///     print!("{} ", i);
    /// }
    /// // Produce `1 2`
    /// ```
    pub fn get_output_selections(&self, port_out: &'static str) -> Result<Vec<String>> {
        self.outputs_array.get(port_out).ok_or(result::Error::PortNotFound(self.name.clone(), port_out.into()))
            .map(|port| {
                port.keys().cloned().collect()
            })
    }

    /// Receive an IP from an input ports
    ///
    /// # Example
    /// ```rust,ignore
    /// let ip = try!(ports.recv("input"));
    /// println!("{}", ip.action);
    /// ```
    pub fn recv(&self, port_in: &str) -> Result<IP> {
        if let Some(ref mut port) = self.inputs.get(port_in) {
            // Received the IP
            let ip = try!(port.recv());
            if port_in != "acc" && port_in != "option" {
                try!(self.sched.send(CompMsg::Dec(self.name.clone())));
            }
            Ok(ip)
        } else {
            Err(result::Error::PortNotFound(self.name.clone(), port_in.into()))
        }
    }

    /// Try to receive an IP from an input ports
    ///
    /// # Example
    /// ```rust,ignore
    /// while let Ok(ip) = ports.try_recv("input") {
    ///     println!("{}", ip.action);
    /// }
    /// ```
    pub fn try_recv(&self, port_in: &str) -> Result<IP> {
        if let Some(ref mut port) = self.inputs.get(port_in) {
            let ip = try!(port.try_recv());
            if port_in != "acc" && port_in != "option" {
                try!(self.sched.send(CompMsg::Dec(self.name.clone())));
            }
            Ok(ip)
        } else {
            Err(result::Error::PortNotFound(self.name.clone(), port_in.into()))
        }
    }

    /// Receive an IP from an array input ports
    ///
    /// # Example
    /// ```rust,ignore
    /// let ip = try!(ports.recv_array("inputs", "1"));
    /// println!("{}", ip.action);
    /// ```
    pub fn recv_array(&self, port_in: &str, selection_in: &str) -> Result<IP> {
        self.inputs_array.get(port_in).ok_or(result::Error::PortNotFound(self.name.clone(), port_in.into()))
            .and_then(|port|{
                port.get(selection_in).ok_or(result::Error::SelectionNotFound(self.name.clone(), port_in.into(), selection_in.into()))
                    .and_then(|recv| {
                        let ip = try!(recv.recv());
                        if port_in != "acc" && port_in != "option" {
                            try!(self.sched.send(CompMsg::Dec(self.name.clone())));
                        }
                        Ok(ip)
                    })
            })
    }

    /// Try to receive an IP from an array input ports
    ///
    /// # Example
    /// ```rust,ignore
    /// while let Ok(ip) = ports.try_recv_array("input", "1") {
    ///     println!("{}", ip.action);
    /// }
    /// ```
    pub fn try_recv_array(&self, port_in: &str, selection_in: &str) -> Result<IP> {
        self.inputs_array.get(port_in).ok_or(result::Error::PortNotFound(self.name.clone(), port_in.into()))
            .and_then(|port|{
                port.get(selection_in).ok_or(result::Error::SelectionNotFound(self.name.clone(), port_in.into(), selection_in.into()))
                    .and_then(|recv| {
                        let ip = try!(recv.try_recv());
                        if port_in != "acc" && port_in != "option" {
                            try!(self.sched.send(CompMsg::Dec(self.name.clone())));
                        }
                        Ok(ip)
                    })
            })
    }

    /// Send an IP outside, through the output port `port_out`
    ///
    /// # Example
    /// ```rust,ignore
    ///    let ip = IP::new();
    ///    try!(ports.send("output", ip));
    /// ```
    pub fn send(&self, port_out: &str, ip: IP) -> Result<()> {
        self.outputs.get(port_out).ok_or(result::Error::PortNotFound(self.name.clone(), port_out.into()))
            .and_then(|port|{
                port.as_ref().ok_or(result::Error::OutputPortNotConnected(self.name.clone(), port_out.into()))
                    .and_then(|sender| {
                        sender.send(ip)
                    })
            })
    }

    /// Send an IP outside, through the array output port `port_out` with the selection `selection_out`
    ///
    /// # Example
    /// ```rust,ignore
    ///    let ip = IP::new();
    ///    try!(ports.send_array("output", "1", ip));
    /// ```
    pub fn send_array(&self, port_out: &str, selection_out: &str, ip: IP) -> Result<()> {
        self.outputs_array.get(port_out).ok_or(result::Error::PortNotFound(self.name.clone(), port_out.into()))
            .and_then(|port| {
                port.get(selection_out).ok_or(result::Error::SelectionNotFound(self.name.clone(), port_out.into(), selection_out.into()))
                    .and_then(|sender| {
                        sender.as_ref().ok_or(result::Error::ArrayOutputPortNotConnected(self.name.clone(), port_out.into(), selection_out.into()))
                            .and_then(|sender| {
                                sender.send(ip)
                            })
                    })
            })
    }

    /// Send an IP outside, depending of the action
    ///
    /// The component must have a simple output port and an array output port with the same name (IE: output). If the array output port had a selection corresponding to the IP action, the IP will be send on it. Otherwise, the IP is send on the simple output port.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// try!(ports.add_output_selection("output", "1"));
    /// let mut ip = IP::new();
    /// ip.action = "2".to_string();
    /// try!(send_action("output", ip)); // Send on the simple output port "output"
    /// let mut ip = IP::new();
    /// ip.action = "1".to_string();
    /// try!(send_action("output", ip)); // Send on the array output port "output", selection "1"
    /// ```
    pub fn send_action(&self, port_out: &'static str, ip: IP) -> Result<()> {
        if try!(self.get_output_selections(&port_out)).contains(&ip.action) {
            self.send_array(&port_out, &ip.action.clone(), ip)
        } else {
            self.send(&port_out, ip)
        }
    }

    /// Connect an simple output port with the IPSender
    ///
    /// ```rust,ignore
    /// try!(ports.connect("output", sender));
    /// ```
    ///
    pub fn connect(&mut self, port_out: String, sender: IPSender) -> Result<()> {
        if !self.outputs.contains_key(&port_out) {
            return Err(result::Error::PortNotFound(self.name.clone(), port_out.into()));
        }
        self.outputs.insert(port_out, Some(sender));
        Ok(())
    }

    /// Connect an array output port with the IPSender
    ///
    /// ```rust,ignore
    /// try!(ports.connect_array("output", "1", sender));
    /// ```
    ///
    pub fn connect_array(&mut self, port_out: String, selection_out: String, sender: IPSender) -> Result<()> {
        let name = self.name.clone();
        if !self.outputs_array.contains_key(&port_out) {
            return Err(result::Error::PortNotFound(name, port_out.into()));
        }
        self.outputs_array.get_mut(&port_out).ok_or(result::Error::PortNotFound(name.clone(), port_out.clone()))
            .and_then(|port| {
                if !port.contains_key(&selection_out) {
                    return Err(result::Error::SelectionNotFound(name, port_out.into(), selection_out.into()));
                }
                port.insert(selection_out, Some(sender));
                Ok(())
            })
    }

    /// Disconnect and retrieve the IPSender of an simple output port
    ///
    /// ```rust,ignore
    /// let sender = try!(ports.disconnect("output"));
    /// ```
    ///
    pub fn disconnect(&mut self, port_out: String) -> Result<Option<IPSender>> {
        if !self.outputs.contains_key(&port_out) {
            return Err(result::Error::PortNotFound(self.name.clone(), port_out.into()));
        }
        let old = self.outputs.insert(port_out, None);
        match old {
            Some(Some(ip_sender)) => {
                Ok(Some(ip_sender))
            }
            _ => { Ok(None) },
        }
    }

    /// Disconnect and retrieve the IPSender of an array output port
    ///
    /// ```rust,ignore
    /// let sender = try!(ports.disconnect_array("outputs", "1"));
    /// ```
    ///
    pub fn disconnect_array(&mut self, port_out: String, selection_out: String) -> Result<Option<IPSender>> {
        if !self.outputs_array.contains_key(&port_out) {
            return Err(result::Error::PortNotFound(self.name.clone(), port_out.into()));
        }
        let name = self.name.clone();
        self.outputs_array.get_mut(&port_out).ok_or(result::Error::PortNotFound(name.clone(), port_out.clone()))
            .and_then(|port| {
                if !port.contains_key(&selection_out) {
                    return Err(result::Error::SelectionNotFound(name, port_out, selection_out));
                }
                let old = port.insert(port_out, None);
                match old {
                    Some(Some(ip_sender)) => {
                        Ok(Some(ip_sender))
                    }
                    _ => { Ok(None) },
                }
            })
    }

    /// Change the receiver of a simple output ports
    ///
    /// usefull if you want to swap a component, but keep the existing connection
    ///
    /// ```rust,ignore
    /// ports.set_receiver("input", receiver);
    /// ```
    pub fn set_receiver(&mut self, port: String, recv: Receiver<IP>) {
        self.inputs.insert(port, recv);
    }

    /// Get the receiver of a simple output ports
    ///
    /// usefull if you want to swap a component, but keep the existing connection
    ///
    /// ```rust,ignore
    /// let receiver = try!(ports.remove_receiver("input"));
    /// ```
    pub fn remove_receiver(&mut self, port: &str) -> Result<Receiver<IP>> {
        self.inputs.remove(port).ok_or(result::Error::PortNotFound(self.name.clone(), port.into()))
            .map(|recv| { recv })
    }

    /// Get the receiver of a array output ports
    ///
    /// usefull if you want to swap a component, but keep the existing connection
    ///
    /// ```rust,ignore
    /// let receiver = try!(ports.remove_array_receiver("inputs", "1"));
    /// ```
    pub fn remove_array_receiver(&mut self, port_name: &str, selection: &str) -> Result<Receiver<IP>> {
        let name = self.name.clone();
        self.inputs_array.get_mut(port_name).ok_or(result::Error::PortNotFound(name.clone(), port_name.into()))
            .and_then(|port| {
                port.remove(selection).ok_or(result::Error::SelectionNotFound(name, port_name.into(), selection.into()))
                    .map(|recv| { recv })
            })
    }

    /// Add a selection in an input array port, and retrieve the corresponding IPSender
    ///
    /// ```rust,ignore
    /// let sender = try!(ports.add_input_selection("inputs", "1"));
    /// ```
    pub fn add_input_selection(&mut self, port_in: &str, selection_in: String) -> Result<IPSender> {
        let (s, r) = sync_channel(25);
        let s = IPSender {
            sender: s,
            dest: self.name.clone(),
            sched: self.sched.clone(),
        };
        self.inputs_array.get_mut(port_in)
            .ok_or(result::Error::PortNotFound(self.name.clone(), port_in.into()))
            .map(|port| {
                port.insert(selection_in, r);
                s
            })
    }

    /// Change the receiver of an array output ports
    ///
    /// usefull if you want to swap a component, but keep the existing connection
    ///
    /// ```rust,ignore
    /// ports.add_input_receiver("input", receiver);
    /// ```
    pub fn add_input_receiver(&mut self, port_in: &str, selection_in: String, r: Receiver<IP>) -> Result<()> {
        self.inputs_array.get_mut(port_in)
            .ok_or(result::Error::PortNotFound(self.name.clone(), port_in.into()))
            .map(|port| {
                port.insert(selection_in, r);
                ()
            })
    }

    /// Add a selection in an input array port
    ///
    /// This selection will be able to be connected to another component
    ///
    /// ```rust,ignore
    /// try!(ports.add_output_selection("inputs", "1"));
    /// ```
    pub fn add_output_selection(&mut self, port_out: &str, selection_out: String) -> Result<()> {
        self.outputs_array.get_mut(port_out)
            .ok_or(result::Error::PortNotFound(self.name.clone(), port_out.into()))
            .map(|port| {
                if !port.contains_key(&selection_out) {
                    port.insert(selection_out, None);
                }
                ()
            })
    }
}

#[allow(unused_imports)]
mod test_port {

    use super::Ports;

    use scheduler::CompMsg;

    use std::sync::mpsc::channel;
    #[test]
    fn ports() {
        assert!(1==1);
        let (s, r) = channel();


        let (mut p1, senders) = Ports::new("unique".into(), s,
                                               vec!["in".into(), "vec".into()],
                                               vec!["in_a".into()],
                                               vec!["out".into()],
                                               vec!["out_a".into()]
                                               ).expect("cannot create");
        assert!(senders.len() == 2);

        let s_in = senders.get("in").unwrap();

        p1.connect("out".into(), s_in.clone()).expect("cannot connect");

        let wrong = p1.try_recv("in");
        assert!(wrong.is_err());

        let ip = super::IP::new();

        p1.send("out", ip).expect("cannot send");

        let ok = p1.try_recv("in");
        assert!(ok.is_ok());

        let ip = super::IP::new();
        p1.send("out", ip).expect("cannot send second times");

        let nip = p1.recv("in");
        assert!(nip.is_ok());
        // test array ports

        let s_in = p1.add_input_selection("in_a", "1".into()).expect("cannot add input selection");

        p1.add_output_selection("out_a".into(), "a".into()).expect("cannot add output");
        p1.connect_array("out_a".into(), "a".into(), s_in).expect("cannot connect array");

        let ip = super::IP::new();
        p1.send_array("out_a", "a", ip).expect("cannot send array");

        let nip = p1.recv_array("in_a", "1");
        assert!(nip.is_ok());

        let i = r.recv().expect("cannot received the sched");
        assert!(
            if let CompMsg::Inc(ref name) = i { name == "unique" } else { false }
            );
        let i = r.recv().expect("cannot received the sched");
        assert!(
            if let CompMsg::Dec(ref name) = i { name == "unique" } else { false }
            );
        let i = r.recv().expect("cannot received the sched");
        assert!(
            if let CompMsg::Inc(ref name) = i { name == "unique" } else { false }
            );
        let i = r.recv().expect("cannot received the sched");
        assert!(
            if let CompMsg::Dec(ref name) = i { name == "unique" } else { false }
            );
        let i = r.recv().expect("cannot received the sched");
        assert!(
            if let CompMsg::Inc(ref name) = i { name == "unique" } else { false }
            );
        let i = r.recv().expect("cannot received the sched");
        assert!(
            if let CompMsg::Dec(ref name) = i { name == "unique" } else { false }
            );
        let i = r.try_recv();
        assert!(i.is_err());
    }
}