copernica_links/
lib.rs

1extern crate copernica_packets;
2extern crate copernica_common;
3extern crate async_io;
4extern crate futures_lite;
5extern crate anyhow;
6extern crate reed_solomon;
7extern crate log;
8extern crate crossbeam_channel;
9mod udpipv4;
10mod mpsc_channel;
11mod mpsc_corruptor;
12pub use {
13    udpipv4::{UdpIpV4},
14    mpsc_channel::{MpscChannel},
15    mpsc_corruptor::{MpscCorruptor, Corruption},
16};
17use {
18    copernica_packets::{
19        InterLinkPacket, LinkId, LinkPacket, PublicIdentity,
20    },
21    copernica_common::{ Operations, constants::REED_SOLOMON_DE_EN_CODER_SIZE },
22    crossbeam_channel::{Receiver, Sender},
23    anyhow::{anyhow, Result},
24    reed_solomon::{Buffer, Encoder, Decoder},
25    //log::debug,
26};
27pub fn decode(msg: Vec<u8>, link_id: LinkId) -> Result<(PublicIdentity, LinkPacket)> {
28    let dec = Decoder::new(REED_SOLOMON_DE_EN_CODER_SIZE);
29    let mut buffers: Vec<Buffer> = vec![];
30    for chunk in msg.chunks(255) {
31        buffers.push(Buffer::from_slice(chunk, chunk.len()));
32    }
33    let mut reconstituted: Vec<Buffer> = vec![];
34    for buffer in buffers {
35        let buf = match dec.correct(&buffer, None) {
36            Ok(b) => b,
37            Err(e) => {
38                return Err(anyhow!("Packet corrupted beyond recovery, dropping it (error: {:?})", e));
39            },
40        };
41        reconstituted.push(buf);
42    }
43    let reconstituted: Vec<u8> = reconstituted.iter().map(|d| d.data()).collect::<Vec<_>>().concat();
44    let (public_id0, lp0) = LinkPacket::from_bytes(&reconstituted, link_id.clone())?;
45    Ok((public_id0, lp0))
46}
47pub fn encode(lp: LinkPacket, link_id: LinkId) -> Result<Vec<u8>> {
48    let mut merged = vec![];
49    let enc = Encoder::new(REED_SOLOMON_DE_EN_CODER_SIZE);
50    let lpb: Vec<u8> = lp.as_bytes(link_id.clone())?;
51    let cs = lpb.chunks(255-REED_SOLOMON_DE_EN_CODER_SIZE);
52    for c in cs {
53        let c = enc.encode(&c[..]);
54        merged.extend(&**c);
55    }
56    Ok(merged)
57}
58pub trait Link {
59    fn run(&mut self) -> Result<()>;
60    fn new(link: LinkId, ops: (String, Operations), router_in_and_out: ( Sender<InterLinkPacket> , Receiver<InterLinkPacket>)) -> Result<Self> where Self: Sized;
61}