tycho/read/async_/
value.rs

1use tokio::io::AsyncRead;
2
3use crate::error::{TychoError, TychoResult};
4use crate::ident::ValueIdent;
5use crate::read::async_::func::{read_byte_async, read_bytes_async};
6use crate::read::async_::length::read_length_async;
7use crate::read::async_::number::{read_number_async, read_number_ident_async};
8use crate::read::async_::string::{read_char_async, read_string_async};
9use crate::{Value, Uuid};
10
11pub(crate) async fn read_value_ident_async<R: AsyncRead + Unpin>(reader: &mut R) -> TychoResult<ValueIdent> {
12    let byte = read_byte_async(reader).await?;
13
14    match byte {
15        0x00 => Ok(ValueIdent::Null),
16        0x01 => Ok(ValueIdent::Boolean),
17        0x02 => Ok(ValueIdent::String),
18        0x03 => Ok(ValueIdent::Char),
19        0x04 => Ok(ValueIdent::Number(read_number_ident_async(reader).await?)),
20        0x05 => Ok(ValueIdent::Bytes),
21        0x06 => Ok(ValueIdent::UUID),
22
23        _ => Err(TychoError::InvalidIdent { found: byte, expecting: "value ident".to_string() })
24    }
25}
26
27pub(crate) async fn read_value_async<R: AsyncRead + Unpin>(reader: &mut R, ident: &ValueIdent) -> TychoResult<Value> {
28    match ident {
29        ValueIdent::Null => Ok(Value::Null),
30        ValueIdent::Boolean => Ok(Value::Boolean(read_byte_async(reader).await? == 0x01)),
31        ValueIdent::String => Ok(Value::String(read_string_async(reader).await?)),
32        ValueIdent::Char => Ok(Value::Char(read_char_async(reader).await?)),
33        ValueIdent::Number(n) => Ok(Value::Number(read_number_async(reader, n).await?)),
34        ValueIdent::Bytes => {
35            let length = read_length_async(reader).await?;
36            Ok(Value::Bytes(read_bytes_async(reader, length).await?))
37        }
38        ValueIdent::UUID => {
39            // suffering
40            let bytes = [
41                read_byte_async(reader).await?, read_byte_async(reader).await?,
42                read_byte_async(reader).await?, read_byte_async(reader).await?,
43                read_byte_async(reader).await?, read_byte_async(reader).await?,
44                read_byte_async(reader).await?, read_byte_async(reader).await?,
45                read_byte_async(reader).await?, read_byte_async(reader).await?,
46                read_byte_async(reader).await?, read_byte_async(reader).await?,
47                read_byte_async(reader).await?, read_byte_async(reader).await?,
48                read_byte_async(reader).await?, read_byte_async(reader).await?,
49            ];
50            Ok(Value::UUID(Uuid::from_slice(bytes)))
51        }
52    }
53}