Skip to content

Commit

Permalink
chore: cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
guidiaz committed Jan 12, 2024
1 parent 2506613 commit d03ce84
Show file tree
Hide file tree
Showing 12 changed files with 226 additions and 169 deletions.
5 changes: 4 additions & 1 deletion rad/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,10 @@ impl RadError {
})
}
}
None => Err(RadError::DecodeRadonErrorEmptyArray),
None => {
println!("None");
Err(RadError::DecodeRadonErrorEmptyArray)
}
}
}

Expand Down
12 changes: 6 additions & 6 deletions rad/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,11 @@ async fn http_response(
let mut response_bytes = Vec::<u8>::default();

// todo: before reading the response buffer, an error should be thrown if it was too big
body.read_to_end(&mut response_bytes).await.map_err(|x| {
RadError::HttpOther {
body.read_to_end(&mut response_bytes)
.await
.map_err(|x| RadError::HttpOther {
message: x.to_string(),
}
})?;
})?;
response = RadonTypes::from(RadonBytes::from(response_bytes));
} else {
// response is a string
Expand All @@ -323,8 +323,8 @@ async fn http_response(
response = RadonTypes::from(RadonString::from(response_string));
}

let result = handle_response_with_data_report(retrieve, response, context, settings)
.map(|report| {
let result =
handle_response_with_data_report(retrieve, response, context, settings).map(|report| {
let completion_ts = std::time::SystemTime::now();
RadonReport {
context: ReportContext {
Expand Down
31 changes: 21 additions & 10 deletions rad/src/operators/array.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{
clone::Clone,
convert::{TryFrom, TryInto}
convert::{TryFrom, TryInto},
};

use serde_cbor::value::{from_value, Value};
Expand All @@ -11,7 +11,10 @@ use crate::{
filters::{self, RadonFilters},
operators::string,
reducers::{self, RadonReducers},
script::{execute_radon_script, unpack_subscript, RadonScriptExecutionSettings, partial_results_extract},
script::{
execute_radon_script, partial_results_extract, unpack_subscript,
RadonScriptExecutionSettings,
},
types::{array::RadonArray, integer::RadonInteger, string::RadonString, RadonType, RadonTypes},
};

Expand Down Expand Up @@ -108,10 +111,7 @@ fn get_numeric_string(input: &RadonArray, args: &[Value]) -> Result<RadonString,
)))
}

pub fn join(
input: &RadonArray,
args: &[Value]
) -> Result<RadonTypes, RadError> {
pub fn join(input: &RadonArray, args: &[Value]) -> Result<RadonTypes, RadError> {
// Join not applicable if the input array is not homogeneous
if !input.is_homogeneous() {
return Err(RadError::UnsupportedOpNonHomogeneous {
Expand Down Expand Up @@ -140,6 +140,17 @@ pub fn join(
_ => {
Err(RadError::EmptyArray)
}
.value()
.into_iter()
.map(|item| RadonString::try_from(item).unwrap_or_default().value())
.collect();
Ok(RadonTypes::from(RadonString::from(
string_list.join(separator.as_str()),
)))
operator: "ArrayJoin".to_string(),
args: Some(args.to_vec()),
}),
_ => Err(RadError::EmptyArray),
}
}

Expand Down Expand Up @@ -258,7 +269,7 @@ pub fn filter(
pub fn pick(
input: &RadonArray,
args: &[Value],
_context: &mut ReportContext<RadonTypes>
_context: &mut ReportContext<RadonTypes>,
) -> Result<RadonTypes, RadError> {
let not_found = |index: usize| RadError::ArrayIndexOutOfBounds {
index: i32::try_from(index).unwrap(),
Expand Down Expand Up @@ -286,7 +297,7 @@ pub fn pick(
let index = from_value::<usize>(first_arg.clone()).map_err(|_| wrong_args())?;
indexes.push(index);
}
_ => return Err(wrong_args())
_ => return Err(wrong_args()),
};
}

Expand Down Expand Up @@ -472,8 +483,8 @@ mod tests {
operators::{
Operable,
RadonOpCodes::{
IntegerGreaterThan, IntegerMultiply, MapGetBoolean, MapGetFloat, MapGetInteger,
MapGetString, self,
self, IntegerGreaterThan, IntegerMultiply, MapGetBoolean, MapGetFloat,
MapGetInteger, MapGetString,
},
},
types::{
Expand Down
45 changes: 27 additions & 18 deletions rad/src/operators/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,27 @@ use std::convert::TryFrom;
use crate::{
error::RadError,
hash_functions::{self, RadonHashFunctions},
types::{bytes::{RadonBytes, RadonBytesEncoding}, string::RadonString, integer::RadonInteger, RadonType},
types::{
bytes::{RadonBytes, RadonBytesEncoding},
integer::RadonInteger,
string::RadonString,
RadonType,
},
};

pub fn as_integer(input: &RadonBytes) -> Result<RadonInteger, RadError> {
let input_value_len = input.value().len();
match input_value_len {
1..=16 => {
let mut bytes_array = [0u8; 16];
bytes_array[16 - input_value_len ..].copy_from_slice(&input.value());
bytes_array[16 - input_value_len..].copy_from_slice(&input.value());
Ok(RadonInteger::from(i128::from_be_bytes(bytes_array)))
}
17.. => Err(RadError::ParseInt { message: "Input buffer too big".to_string() }),
_ => Err(RadError::EmptyArray)
}
17.. => Err(RadError::ParseInt {
message: "Input buffer too big".to_string(),
}),
_ => Err(RadError::EmptyArray),
}
}

pub fn hash(input: &RadonBytes, args: &[Value]) -> Result<RadonBytes, RadError> {
Expand All @@ -43,17 +50,21 @@ pub fn length(input: &RadonBytes) -> RadonInteger {
}

pub fn slice(input: &RadonBytes, args: &[Value]) -> Result<RadonBytes, RadError> {
let wrong_args = || RadError::WrongArguments {
let wrong_args = || RadError::WrongArguments {
input_type: RadonString::radon_type_name(),
operator: "BytesSlice".to_string(),
args: args.to_vec(),
};
let end_index = input.value().len();
if end_index > 0 {
let start_index = from_value::<i64>(args[0].clone()).unwrap_or_default().rem_euclid(end_index as i64) as usize;
let start_index = from_value::<i64>(args[0].clone())
.unwrap_or_default()
.rem_euclid(end_index as i64) as usize;
let mut slice = input.value().as_slice().split_at(start_index).1.to_vec();
if args.len() == 2 {
let end_index = from_value::<i64>(args[1].clone()).unwrap_or_default().rem_euclid(end_index as i64) as usize;
let end_index = from_value::<i64>(args[1].clone())
.unwrap_or_default()
.rem_euclid(end_index as i64) as usize;
slice.truncate(end_index - start_index);
}
Ok(RadonBytes::from(slice))
Expand All @@ -63,7 +74,7 @@ pub fn slice(input: &RadonBytes, args: &[Value]) -> Result<RadonBytes, RadError>
}

pub fn stringify(input: &RadonBytes, args: &Option<Vec<Value>>) -> Result<RadonString, RadError> {
let wrong_args = || RadError::WrongArguments {
let wrong_args = || RadError::WrongArguments {
input_type: RadonString::radon_type_name(),
operator: "Stringify".to_string(),
args: args.to_owned().unwrap_or_default().to_vec(),
Expand All @@ -74,20 +85,18 @@ pub fn stringify(input: &RadonBytes, args: &Option<Vec<Value>>) -> Result<RadonS
if !args.is_empty() {
let arg = args.first().ok_or_else(wrong_args)?.to_owned();
let bytes_encoding_u8 = from_value::<u8>(arg).map_err(|_| wrong_args())?;
bytes_encoding = RadonBytesEncoding::try_from(bytes_encoding_u8).map_err(|_| wrong_args())?;
bytes_encoding =
RadonBytesEncoding::try_from(bytes_encoding_u8).map_err(|_| wrong_args())?;
}
}
_ => ()
_ => (),
}
match bytes_encoding {
RadonBytesEncoding::Hex => {
RadonString::try_from(Value::Text(hex::encode(input.value())))
}
RadonBytesEncoding::Base64 => {
RadonString::try_from(Value::Text(base64::engine::general_purpose::STANDARD.encode(input.value())))
}
RadonBytesEncoding::Hex => RadonString::try_from(Value::Text(hex::encode(input.value()))),
RadonBytesEncoding::Base64 => RadonString::try_from(Value::Text(
base64::engine::general_purpose::STANDARD.encode(input.value()),
)),
}

}

#[cfg(test)]
Expand Down
6 changes: 3 additions & 3 deletions rad/src/operators/integer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use serde_cbor::value::{from_value, Value};
use crate::{
error::RadError,
types::{
boolean::RadonBoolean, float::RadonFloat, integer::RadonInteger, string::RadonString,
RadonType, bytes::RadonBytes,
boolean::RadonBoolean, bytes::RadonBytes, float::RadonFloat, integer::RadonInteger,
string::RadonString, RadonType,
},
};

Expand All @@ -26,7 +26,7 @@ pub fn to_bytes(input: RadonInteger) -> Result<RadonBytes, RadError> {
let mut leading_zeros = 0;
for i in 0..bytes_array.len() {
if bytes_array[i] != 0u8 {
break
break;
} else {
leading_zeros += 1;
}
Expand Down
59 changes: 30 additions & 29 deletions rad/src/operators/map.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
use std::{convert::TryInto, collections::BTreeMap};
use std::{collections::BTreeMap, convert::TryInto};

use serde_cbor::value::{from_value, Value};
use witnet_data_structures::radon_report::ReportContext;

use crate::{
error::RadError,
operators::string,
types::{array::RadonArray, map::RadonMap, string::RadonString, RadonType, RadonTypes},
script::{RadonScriptExecutionSettings, execute_radon_script, unpack_subscript, partial_results_extract},
script::{
execute_radon_script, partial_results_extract, unpack_subscript,
RadonScriptExecutionSettings,
},
types::{array::RadonArray, map::RadonMap, string::RadonString, RadonType, RadonTypes},
};

pub fn alter(
input: &RadonMap,
input: &RadonMap,
args: &[Value],
context: &mut ReportContext<RadonTypes>
context: &mut ReportContext<RadonTypes>,
) -> Result<RadonMap, RadError> {
let wrong_args = || RadError::WrongArguments {
input_type: RadonMap::radon_type_name(),
Expand All @@ -33,7 +36,7 @@ pub fn alter(
Value::Text(key) => {
input_keys.push(key.clone());
}
_ => return Err(wrong_args())
_ => return Err(wrong_args()),
};

let subscript = args.get(1).ok_or_else(wrong_args)?;
Expand All @@ -45,24 +48,22 @@ pub fn alter(
inner: Box::new(e),
};
let subscript = unpack_subscript(subscript).map_err(subscript_err)?;

let not_found = |key_str: &str| RadError::MapKeyNotFound { key: String::from(key_str) };

let not_found = |key_str: &str| RadError::MapKeyNotFound {
key: String::from(key_str),
};

let input_map = input.value();
let mut output_map = input.value().clone();
let mut reports = vec![];

let settings = RadonScriptExecutionSettings::tailored_to_stage(&context.stage);
for key in input_keys {
let value = input_map
.get(key.as_str())
.ok_or_else(|| not_found(key.as_str()))?;
let report = execute_radon_script(
value.clone(),
subscript.as_slice(),
context,
settings
)?;
let report =
execute_radon_script(value.clone(), subscript.as_slice(), context, settings)?;
// If there is an error while altering value, short-circuit and bubble up the error as it comes
// from the radon script execution
if let RadonTypes::RadonError(error) = &report.result {
Expand All @@ -71,14 +72,14 @@ pub fn alter(
output_map.insert(key, report.result.clone());
}
reports.push(report);
}
}

// Extract the partial results from the reports and put them in the execution context if needed
partial_results_extract(&subscript, &reports, context);

Ok(RadonMap::from(output_map))
}
_ => Err(wrong_args())
_ => Err(wrong_args()),
}
}

Expand Down Expand Up @@ -156,10 +157,10 @@ pub fn values(input: &RadonMap) -> RadonArray {
}

pub fn pick(input: &RadonMap, args: &[Value]) -> Result<RadonMap, RadError> {
let not_found = |key_str: &str| RadError::MapKeyNotFound {
key: String::from(key_str)
let not_found = |key_str: &str| RadError::MapKeyNotFound {
key: String::from(key_str),
};

let wrong_args = || RadError::WrongArguments {
input_type: RadonMap::radon_type_name(),
operator: "Pick".to_string(),
Expand All @@ -174,14 +175,15 @@ pub fn pick(input: &RadonMap, args: &[Value]) -> Result<RadonMap, RadError> {
match first_arg {
Value::Array(keys) => {
for key in keys.iter() {
let key_string = from_value::<String>(key.to_owned()).map_err(|_| wrong_args())?;
let key_string =
from_value::<String>(key.to_owned()).map_err(|_| wrong_args())?;
input_keys.push(key_string);
}
}
Value::Text(key) => {
input_keys.push(key.clone());
}
_ => return Err(wrong_args())
_ => return Err(wrong_args()),
};
}

Expand All @@ -190,18 +192,17 @@ pub fn pick(input: &RadonMap, args: &[Value]) -> Result<RadonMap, RadError> {
if let Some(value) = input.value().get(&key) {
output_map.insert(key, value.clone());
} else {
return Err(not_found(key.as_str()))
return Err(not_found(key.as_str()));
}
}
Ok(RadonMap::from(output_map))
}

pub fn stringify(input: &RadonMap) -> Result<RadonString, RadError> {
let json_string = serde_json::to_string(&input.value())
.map_err(|_| RadError::Decode {
from: "RadonMap",
to: "RadonString"
})?;
let json_string = serde_json::to_string(&input.value()).map_err(|_| RadError::Decode {
from: "RadonMap",
to: "RadonString",
})?;
Ok(RadonString::from(json_string))
}

Expand Down
2 changes: 1 addition & 1 deletion rad/src/operators/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub enum RadonOpCodes {
BooleanNegate = 0x22,
BooleanToString = 0x20,
///////////////////////////////////////////////////////////////////////
// Bytes operator codes (start at 0x30)
// Bytes operator codes (start at 0x30)
BytesAsInteger = 0x32,
BytesHash = 0x31,
BytesLength = 0x34,
Expand Down
Loading

0 comments on commit d03ce84

Please sign in to comment.