sdlan-rs/src/utils/helper.rs

86 lines
2.1 KiB
Rust

use super::SDLanError;
use dashmap::DashMap;
use std::net::{IpAddr, SocketAddr};
use std::path::Path;
use std::sync::Arc;
pub struct MyDashMap<T>(DashMap<String, Arc<T>>);
impl<T> MyDashMap<T> {
pub fn new() -> Self {
MyDashMap(DashMap::new())
}
pub fn get(&self, key: &str) -> Option<Arc<T>> {
if let Some(t) = self.0.get(key) {
return Some(t.clone());
}
None
}
pub fn insert(&self, key: String, value: T) -> Option<Arc<T>> {
self.0.insert(key, Arc::new(value))
}
pub fn remove(&self, key: &str) -> Option<(String, Arc<T>)> {
self.0.remove(key)
}
pub fn clear(&self) {
self.0.clear()
}
}
use std::time::{SystemTime, UNIX_EPOCH};
pub fn get_current_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
use crate::peer::SdlanSock;
use super::{gen_uuid, Result};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
pub fn create_or_load_uuid() -> Result<String> {
let filepath = Path::new("./.id");
if filepath.exists() {
let mut result = String::new();
File::open(filepath)?.read_to_string(&mut result)?;
let result = result.trim().to_string();
return Ok(result);
} else {
let uuid = gen_uuid();
OpenOptions::new()
.create(true)
.write(true)
.open(filepath)?
.write_all(uuid.as_bytes())?;
return Ok(uuid);
}
}
// get sdlansock info from socketaddr
pub fn get_sdlan_sock_from_socketaddr(addr: SocketAddr) -> Result<SdlanSock> {
let port = addr.port();
let ip = addr.ip();
match ip {
IpAddr::V4(ipv4) => {
let v4: u32 = ipv4.into();
let res = SdlanSock {
family: 0,
port: port,
has_v6: false,
v6_port: 0,
v4: v4.to_be_bytes(),
v6: [0; 16],
};
Ok(res)
}
IpAddr::V6(_ipv6) => Err(SDLanError::NormalError("ipv6 found")),
}
}