summaryrefslogtreecommitdiffstats
path: root/src/net/data_repr.rs
blob: 708241ddeb4c85155ff25113391419a8379c98d0 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// -*- coding: utf-8 -*-
//
// Copyright 2021 Michael Buesch <m@bues.ch>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

use anyhow as ah;
use std::convert::TryInto;
use std::cmp::min;

pub trait ToNet32 {
    /// Convert to network byte order.
    fn to_net(&self) -> [u8; 4];
}

pub trait ToNetStr {
    /// Convert to network byte format.
    fn to_net(&self, bytes: &mut [u8], truncate: bool) -> ah::Result<usize>;
}

pub trait FromNet32 {
    /// Convert from network byte order.
    fn from_net(data: &[u8]) -> ah::Result<u32>;
}

pub trait FromNetStr {
    /// Convert from network byte format.
    fn from_net(bytes: &[u8], len: usize, lossy: bool) -> ah::Result<String>;
}

impl ToNet32 for u32 {
    fn to_net(&self) -> [u8; 4] {
        self.to_be_bytes()
    }
}

impl FromNet32 for u32 {
    fn from_net(data: &[u8]) -> ah::Result<u32> {
        if data.len() >= 4 {
            Ok(u32::from_be_bytes(data[0..4].try_into()?))
        } else {
            return Err(ah::format_err!("from_net u32: Not enough data."))
        }
    }
}

impl ToNetStr for str {
    fn to_net(&self, bytes: &mut [u8], truncate: bool) -> ah::Result<usize> {
        let mut len = self.as_bytes().len();
        if len > bytes.len() {
            if !truncate {
                return Err(ah::format_err!("to_net str: String is too long."));
            }
            len = bytes.len()
        }
        bytes[0..len].copy_from_slice(&self.as_bytes());
        Ok(len)
    }
}

impl FromNetStr for String {
    fn from_net(bytes: &[u8], len: usize, lossy: bool) -> ah::Result<String> {
        let len = min(len, bytes.len());
        if lossy {
            Ok(String::from_utf8_lossy(&bytes[0..len]).to_string())
        } else {
            Ok(String::from_utf8(bytes[0..len].to_vec())?)
        }
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface