summaryrefslogtreecommitdiffstats
path: root/src/network/utilization.rs
blob: bb3f581cb7e47f181b1358f892a76f75fcdb32ed (plain)
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
use crate::network::{Connection, Direction, Segment};

use ::std::collections::HashMap;
use ::std::time::SystemTime;

#[derive(Clone)]
pub struct TotalBandwidth {
    pub total_bytes_downloaded: u128,
    pub total_bytes_uploaded: u128,
}

impl TotalBandwidth {
    pub fn increment_bytes_downloaded(&mut self, data_length: u128, reset_time: &SystemTime) {
        if let Ok(elapsed) = reset_time.elapsed() {
            if elapsed.as_millis() < 1000 {
                self.total_bytes_downloaded += data_length;
            }
        }
    }
    pub fn increment_bytes_uploaded(&mut self, data_length: u128, reset_time: &SystemTime) {
        if let Ok(elapsed) = reset_time.elapsed() {
            if elapsed.as_millis() < 1000 {
                self.total_bytes_uploaded += data_length;
            }
        }
    }
}

#[derive(Clone)]
pub struct Utilization {
    pub connections: HashMap<Connection, TotalBandwidth>,
    reset_time: SystemTime,
}

impl Utilization {
    pub fn new() -> Self {
        let connections = HashMap::new();
        Utilization {
            connections,
            reset_time: SystemTime::now(),
        }
    }
    pub fn clone_and_reset(&mut self) -> Self {
        let clone = self.clone();
        self.reset_time = SystemTime::now();
        self.connections.clear();
        clone
    }
    pub fn update(&mut self, seg: &Segment) {
        let total_bandwidth =
            self.connections
                .entry(seg.connection.clone())
                .or_insert(TotalBandwidth {
                    total_bytes_downloaded: 0,
                    total_bytes_uploaded: 0,
                });
        match seg.direction {
            Direction::Download => {
                total_bandwidth.increment_bytes_downloaded(seg.data_length, &self.reset_time);
            }
            Direction::Upload => {
                total_bandwidth.increment_bytes_uploaded(seg.data_length, &self.reset_time);
            }
        }
    }
}