use std::net::SocketAddr;
use bytes::BytesMut;
use super::InputBufVOTrait;
#[derive(Clone)]
#[cfg(any(feature = "server", feature = "client"))]
pub struct InputBufVO {
data: BytesMut,
index: usize,
input_addr: Option<SocketAddr>,
}
impl InputBufVO {
pub(crate) fn new(buf: BytesMut, input_addr: SocketAddr) -> Self {
Self {
data: buf,
index: 3,
input_addr: Some(input_addr),
}
}
pub(crate) fn new_none() -> Self {
Self {
data: BytesMut::new(),
index: 3,
input_addr: None,
}
}
pub(crate) fn new_without_socket_addr(buf: BytesMut) -> Self {
Self {
data: buf,
index: 3,
input_addr: None,
}
}
pub fn get_input_addr(&self) -> Option<SocketAddr> {
self.input_addr
}
}
impl InputBufVOTrait for InputBufVO {
fn get_constructor_id(&mut self) -> Option<u8> {
let length = self.data.len();
if length < 1 {
return None;
} else {
let bytes = &self.data[0..1];
match bytes.try_into() {
Ok(value) => {
return Some(u8::from_le_bytes(value));
}
Err(_) => {
return None;
}
}
}
}
fn get_method_id(&mut self) -> Option<u16> {
let length = self.data.len();
if length < 3 {
return None;
} else {
let bytes = &self.data[1..3];
match bytes.try_into() {
Ok(value) => {
return Some(u16::from_le_bytes(value));
}
Err(_) => {
return None;
}
}
}
}
fn next_u64(&mut self) -> Option<u64> {
let length = self.data.len();
if length < self.index + 8 {
return None;
} else {
let bytes = &self.data[self.index..self.index + 8];
match bytes.try_into() {
Ok(value) => {
self.index = self.index + 8;
return Some(u64::from_le_bytes(value));
}
Err(_) => {
return None;
}
}
}
}
fn next_u8(&mut self) -> Option<u8> {
let length = self.data.len();
if length < self.index + 1 {
return None;
} else {
let bytes = &self.data[self.index..self.index + 1];
match bytes.try_into() {
Ok(value) => {
self.index = self.index + 1;
return Some(u8::from_le_bytes(value));
}
Err(_) => {
return None;
}
}
}
}
fn next_str_with_len(&mut self, len: u64) -> Option<String> {
let len = len as usize;
let length = self.data.len();
if length < self.index + len {
return None;
} else {
let bytes = &mut self.data[self.index..self.index + len].to_vec();
self.index = self.index + len;
Some(String::from_utf8_lossy(bytes).to_string())
}
}
fn get_all_bytes(&self) -> BytesMut {
let mut vec = self.data.clone();
if vec.len() > 3 {
return vec.split_off(3);
} else {
vec = BytesMut::new();
}
vec
}
fn get_remaining_data_len(&self) -> usize {
let data_len = self.data.len();
let index = self.index;
if data_len <= 0 {
0
} else if data_len - 1 >= index {
data_len - index
} else {
0
}
}
}