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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
use crate::{StringToken, Token};
use fuels_types::errors::Error;
use fuels_types::param_types::ParamType;
use fuels_types::utils::has_array_format;
use hex::FromHex;
#[derive(Default)]
pub struct Tokenizer;
impl Tokenizer {
pub fn new() -> Self {
Self {}
}
}
impl Tokenizer {
/// Takes a ParamType and a value string and joins them as a single
/// Token that holds the value within it. This Token is used
/// in the encoding process.
pub fn tokenize(param: &ParamType, value: String) -> Result<Token, Error> {
if !value.is_ascii() {
return Err(Error::InvalidData(
"value string can only contain ascii characters".into(),
));
}
let trimmed_value = value.trim();
match param {
ParamType::Generic(_name) => panic!("Cannot tokenize an unresolved generic parameter!"),
ParamType::Unit => Ok(Token::Unit),
ParamType::U8 => Ok(Token::U8(trimmed_value.parse::<u8>()?)),
ParamType::U16 => Ok(Token::U16(trimmed_value.parse::<u16>()?)),
ParamType::U32 => Ok(Token::U32(trimmed_value.parse::<u32>()?)),
ParamType::U64 => Ok(Token::U64(trimmed_value.parse::<u64>()?)),
ParamType::Bool => Ok(Token::Bool(trimmed_value.parse::<bool>()?)),
ParamType::Byte => Ok(Token::Byte(trimmed_value.parse::<u8>()?)),
ParamType::B256 => {
const B256_HEX_ENC_LENGTH: usize = 64;
if trimmed_value.len() != B256_HEX_ENC_LENGTH {
return Err(Error::InvalidData(format!(
"the hex encoding of the b256 must have {} characters",
B256_HEX_ENC_LENGTH
)));
}
let v = Vec::from_hex(trimmed_value)?;
let s: [u8; 32] = v.as_slice().try_into().unwrap();
Ok(Token::B256(s))
}
ParamType::Array(t, _) => Ok(Self::tokenize_array(trimmed_value, t)?),
ParamType::String(length) => Ok(Token::String(StringToken::new(
trimmed_value.into(),
*length,
))),
ParamType::Struct(struct_params) => {
Ok(Self::tokenize_struct(trimmed_value, struct_params)?)
}
ParamType::Enum(variants) => {
let discriminant = get_enum_discriminant_from_string(trimmed_value);
let value = get_enum_value_from_string(trimmed_value);
let token = Self::tokenize(&variants.param_types()[discriminant], value)?;
Ok(Token::Enum(Box::new((
discriminant as u8,
token,
variants.clone(),
))))
}
ParamType::Tuple(tuple_params) => {
Ok(Self::tokenize_tuple(trimmed_value, tuple_params)?)
}
}
}
/// Creates a `Token::Struct` from an array of parameter types and a string of values.
/// I.e. it takes a string containing values "value_1, value_2, value_3" and an array
/// of `ParamType` containing the type of each value, in order:
/// [ParamType::<Type of value_1>, ParamType::<Type of value_2>, ParamType::<Type of value_3>]
/// And attempts to return a `Token::Struct()` containing the inner types.
/// It works for nested/recursive structs.
pub fn tokenize_struct(value: &str, params: &[ParamType]) -> Result<Token, Error> {
if !value.starts_with('(') || !value.ends_with(')') {
return Err(Error::InvalidData(
"struct value string must start and end with round brackets".into(),
));
}
if value.chars().count() == 2 {
return Ok(Token::Struct(vec![]));
}
// To parse the value string, we use a two-pointer/index approach.
// The items are comma-separated, and if an item is tokenized, the last_item
// index is moved to the current position.
// The variable nested is incremented and decremented if a bracket is encountered,
// and appropriate errors are returned if the nested count is not 0.
// If the struct has an array inside its values, the current position will be incremented
// until the opening and closing bracket are inside the new item.
// Characters inside quotes are ignored, and they are tokenized as one item.
// An error is returned if there is an odd number of quotes.
let mut result = vec![];
let mut nested = 0isize;
let mut ignore = false;
let mut last_item = 1;
let mut params_iter = params.iter();
for (pos, ch) in value.chars().enumerate() {
match ch {
'(' if !ignore => {
nested += 1;
}
')' if !ignore => {
nested -= 1;
match nested.cmp(&0) {
std::cmp::Ordering::Less => {
return Err(Error::InvalidData(
"struct value string has excess closing brackets".into(),
));
}
std::cmp::Ordering::Equal => {
let sub = &value[last_item..pos];
let token = Self::tokenize(
params_iter.next().ok_or_else(|| {
Error::InvalidData(
"struct value contains more elements than the parameter types provided".into(),
)
})?,
sub.to_string(),
)?;
result.push(token);
last_item = pos + 1;
}
_ => {}
}
}
'"' => {
ignore = !ignore;
}
',' if nested == 1 && !ignore => {
let sub = &value[last_item..pos];
// If we've encountered an array within a struct property
// keep iterating until we see the end of it "]".
if sub.contains('[') && !sub.contains(']') {
continue;
}
let token = Self::tokenize(
params_iter.next().ok_or_else(|| {
Error::InvalidData(
"struct value contains more elements than the parameter types provided".into(),
)
})?,
sub.to_string(),
)?;
result.push(token);
last_item = pos + 1;
}
_ => (),
}
}
if ignore {
return Err(Error::InvalidData(
"struct value string has excess quotes".into(),
));
}
if nested > 0 {
return Err(Error::InvalidData(
"struct value string has excess opening brackets".into(),
));
}
Ok(Token::Struct(result))
}
/// Creates a `Token::Array` from one parameter type and a string of values. I.e. it takes a
/// string containing values "value_1, value_2, value_3" and a `ParamType` sepecifying the type.
/// It works for nested/recursive arrays.
pub fn tokenize_array(value: &str, param: &ParamType) -> Result<Token, Error> {
if !value.starts_with('[') || !value.ends_with(']') {
return Err(Error::InvalidData(
"array value string must start and end with square brackets".into(),
));
}
if value.chars().count() == 2 {
return Ok(Token::Array(vec![]));
}
// For more details about this algorithm, refer to the tokenize_struct method.
let mut result = vec![];
let mut nested = 0isize;
let mut ignore = false;
let mut last_item = 1;
for (i, ch) in value.chars().enumerate() {
match ch {
'[' if !ignore => {
nested += 1;
}
']' if !ignore => {
nested -= 1;
match nested.cmp(&0) {
std::cmp::Ordering::Less => {
return Err(Error::InvalidData(
"array value string has excess closing brackets".into(),
));
}
std::cmp::Ordering::Equal => {
// Last element of this nest level; proceed to tokenize.
let sub = &value[last_item..i];
match has_array_format(sub) {
true => {
let arr_param = ParamType::Array(
Box::new(param.to_owned()),
get_array_length_from_string(sub),
);
result.push(Self::tokenize(&arr_param, sub.to_string())?);
}
false => {
result.push(Self::tokenize(param, sub.to_string())?);
}
}
last_item = i + 1;
}
_ => {}
}
}
'"' => {
ignore = !ignore;
}
',' if nested == 1 && !ignore => {
let sub = &value[last_item..i];
match has_array_format(sub) {
true => {
let arr_param = ParamType::Array(
Box::new(param.to_owned()),
get_array_length_from_string(sub),
);
result.push(Self::tokenize(&arr_param, sub.to_string())?);
}
false => {
result.push(Self::tokenize(param, sub.to_string())?);
}
}
last_item = i + 1;
}
_ => (),
}
}
if ignore {
return Err(Error::InvalidData(
"array value string has excess quotes".into(),
));
}
if nested > 0 {
return Err(Error::InvalidData(
"array value string has excess opening brackets".into(),
));
}
Ok(Token::Array(result))
}
/// Creates `Token::Tuple` from an array of parameter types and a string of values.
/// I.e. it takes a string containing values "value_1, value_2, value_3" and an array
/// of `ParamType` containing the type of each value, in order:
/// [ParamType::<Type of value_1>, ParamType::<Type of value_2>, ParamType::<Type of value_3>]
/// And attempts to return a `Token::Tuple()` containing the inner types.
/// It works for nested/recursive tuples.
pub fn tokenize_tuple(value: &str, params: &[ParamType]) -> Result<Token, Error> {
if !value.starts_with('(') || !value.ends_with(')') {
return Err(Error::InvalidData(
"tuple value string must start and end with round brackets".into(),
));
}
if value.chars().count() == 2 {
return Ok(Token::Tuple(vec![]));
}
// For more details about this algorithm, refer to the tokenize_struct method.
let mut result = vec![];
let mut nested = 0isize;
let mut ignore = false;
let mut last_item = 1;
let mut params_iter = params.iter();
for (pos, ch) in value.chars().enumerate() {
match ch {
'(' if !ignore => {
nested += 1;
}
')' if !ignore => {
nested -= 1;
match nested.cmp(&0) {
std::cmp::Ordering::Less => {
return Err(Error::InvalidData(
"tuple value string has excess closing brackets".into(),
));
}
std::cmp::Ordering::Equal => {
let sub = &value[last_item..pos];
let token = Self::tokenize(
params_iter.next().ok_or_else(|| {
Error::InvalidData(
"tuple value contains more elements than the parameter types provided".into(),
)
})?,
sub.to_string(),
)?;
result.push(token);
last_item = pos + 1;
}
_ => {}
}
}
'"' => {
ignore = !ignore;
}
',' if nested == 1 && !ignore => {
let sub = &value[last_item..pos];
// If we've encountered an array within a tuple property
// keep iterating until we see the end of it "]".
if sub.contains('[') && !sub.contains(']') {
continue;
}
let token = Self::tokenize(
params_iter.next().ok_or_else(|| {
Error::InvalidData(
"tuple value contains more elements than the parameter types provided".into(),
)
})?,
sub.to_string(),
)?;
result.push(token);
last_item = pos + 1;
}
_ => (),
}
}
if ignore {
return Err(Error::InvalidData(
"tuple value string has excess quotes".into(),
));
}
if nested > 0 {
return Err(Error::InvalidData(
"tuple value string has excess opening brackets".into(),
));
}
Ok(Token::Tuple(result))
}
}
fn get_enum_discriminant_from_string(ele: &str) -> usize {
let mut chars = ele.chars();
chars.next(); // Remove "("
chars.next_back(); // Remove ")"
let v: Vec<_> = chars.as_str().split(',').collect();
v[0].parse().unwrap()
}
fn get_enum_value_from_string(ele: &str) -> String {
let mut chars = ele.chars();
chars.next(); // Remove "("
chars.next_back(); // Remove ")"
let v: Vec<_> = chars.as_str().split(',').collect();
v[1].to_string()
}
fn get_array_length_from_string(ele: &str) -> usize {
let mut chars = ele.chars();
chars.next();
chars.next_back();
chars.as_str().split(',').count()
}
#[cfg(test)]
mod tests {
use super::*;
// TODO: Move tests using the old abigen to the new one.
// Currently, they will be skipped. Even though we're not fully testing these at
// unit level, they're tested at integration level, in the main harness.rs file.
// #[test]
// fn tokenize_struct_excess_value_elements_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "struct MyStruct".to_string(),
// components: Some(vec![
// Property {
// name: "num".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "arr".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Struct(struct_params) = ParamType::parse_custom_type_param(¶ms)? {
// let error_message = Tokenizer::tokenize_struct("(0, [0,0,0], 0, 0)", &struct_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: struct value contains more elements than the parameter types provided",
// error_message
// );
// let error_message = Tokenizer::tokenize_struct("(0, [0,0,0], 0)", &struct_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: struct value contains more elements than the parameter types provided",
// error_message
// );
// }
// Ok(())
// }
// #[test]
// fn tokenize_struct_excess_quotes_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "struct MyStruct".to_string(),
// components: Some(vec![
// Property {
// name: "num".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "arr".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Struct(struct_params) = ParamType::parse_custom_type_param(¶ms)? {
// let error_message = Tokenizer::tokenize_struct("(0, \"[0,0,0])", &struct_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: struct value string has excess quotes",
// error_message
// );
// }
// Ok(())
// }
#[test]
fn tokenize_uint_types_expected_error() {
// We test only on U8 as it is the same error on all other unsigned int types
let error_message = Tokenizer::tokenize(&ParamType::U8, "2,".to_string())
.unwrap_err()
.to_string();
assert_eq!(
"Parse integer error: invalid digit found in string",
error_message
);
}
#[test]
fn tokenize_bool_expected_error() {
let error_message = Tokenizer::tokenize(&ParamType::Bool, "True".to_string())
.unwrap_err()
.to_string();
assert_eq!(
"Parse boolean error: provided string was not `true` or `false`",
error_message
);
}
#[test]
fn tokenize_b256_invalid_length_expected_error() {
let value = "d57a9c46dfcc7f18207013e65b44e4cb4e2c2298f4ac457ba8f82743f31e90b".to_string();
let error_message = Tokenizer::tokenize(&ParamType::B256, value)
.unwrap_err()
.to_string();
assert_eq!(
"Invalid data: the hex encoding of the b256 must have 64 characters",
error_message
);
}
#[test]
fn tokenize_b256_invalid_character_expected_error() {
let value = "Hd57a9c46dfcc7f18207013e65b44e4cb4e2c2298f4ac457ba8f82743f31e90b".to_string();
let error_message = Tokenizer::tokenize(&ParamType::B256, value)
.unwrap_err()
.to_string();
assert!(error_message.contains("Parse hex error: Invalid character"));
}
// #[test]
// fn tokenize_tuple_invalid_start_end_bracket_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "(u64, [u64; 3])".to_string(),
// components: Some(vec![
// Property {
// name: "__tuple_element".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "__tuple_element".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Tuple(tuple_params) = ParamType::parse_tuple_param(¶ms)? {
// let error_message = Tokenizer::tokenize_tuple("0, [0,0,0])", &tuple_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: tuple value string must start and end with round brackets",
// error_message
// );
// }
// Ok(())
// }
// #[test]
// fn tokenize_tuple_excess_opening_bracket_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "(u64, [u64; 3])".to_string(),
// components: Some(vec![
// Property {
// name: "__tuple_element".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "__tuple_element".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Tuple(tuple_params) = ParamType::parse_tuple_param(¶ms)? {
// let error_message = Tokenizer::tokenize_tuple("((0, [0,0,0])", &tuple_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: tuple value string has excess opening brackets",
// error_message
// );
// }
// Ok(())
// }
// #[test]
// fn tokenize_tuple_excess_closing_bracket_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "(u64, [u64; 3])".to_string(),
// components: Some(vec![
// Property {
// name: "__tuple_element".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "__tuple_element".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Tuple(tuple_params) = ParamType::parse_tuple_param(¶ms)? {
// let error_message = Tokenizer::tokenize_tuple("(0, [0,0,0]))", &tuple_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: tuple value string has excess closing brackets",
// error_message
// );
// }
// Ok(())
// }
// #[test]
// fn tokenize_tuple_excess_quotes_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "(u64, [u64; 3])".to_string(),
// components: Some(vec![
// Property {
// name: "__tuple_element".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "__tuple_element".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Tuple(tuple_params) = ParamType::parse_tuple_param(¶ms)? {
// let error_message = Tokenizer::tokenize_tuple("(0, \"[0,0,0])", &tuple_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: tuple value string has excess quotes",
// error_message
// );
// }
// Ok(())
// }
// #[test]
// fn tokenize_tuple_excess_value_elements_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "(u64, [u64; 3])".to_string(),
// components: Some(vec![
// Property {
// name: "__tuple_element".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "__tuple_element".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Tuple(tuple_params) = ParamType::parse_tuple_param(¶ms)? {
// let error_message = Tokenizer::tokenize_tuple("(0, [0,0,0], 0, 0)", &tuple_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: tuple value contains more elements than the parameter types provided",
// error_message
// );
// let error_message = Tokenizer::tokenize_tuple("(0, [0,0,0], 0)", &tuple_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: tuple value contains more elements than the parameter types provided",
// error_message
// );
// }
// Ok(())
// }
#[test]
fn tokenize_array_invalid_start_end_bracket_expected_error() {
let param = ParamType::U16;
let error_message = Tokenizer::tokenize_array("1,2],[3],4]", ¶m)
.unwrap_err()
.to_string();
assert_eq!(
"Invalid data: array value string must start and end with square brackets",
error_message
);
}
#[test]
fn tokenize_array_excess_opening_bracket_expected_error() {
let param = ParamType::U16;
let error_message = Tokenizer::tokenize_array("[[[1,2],[3],4]", ¶m)
.unwrap_err()
.to_string();
assert_eq!(
"Invalid data: array value string has excess opening brackets",
error_message
);
}
#[test]
fn tokenize_array_excess_closing_bracket_expected_error() {
let param = ParamType::U16;
let error_message = Tokenizer::tokenize_array("[[1,2],[3],4]]", ¶m)
.unwrap_err()
.to_string();
assert_eq!(
"Invalid data: array value string has excess closing brackets",
error_message
);
}
#[test]
fn tokenize_array_excess_quotes_expected_error() {
let param = ParamType::U16;
let error_message = Tokenizer::tokenize_array("[[1,\"2],[3],4]]", ¶m)
.unwrap_err()
.to_string();
assert_eq!(
"Invalid data: array value string has excess quotes",
error_message
);
}
// #[test]
// fn tokenize_struct_invalid_start_end_bracket_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "struct MyStruct".to_string(),
// components: Some(vec![
// Property {
// name: "num".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "arr".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Struct(struct_params) = ParamType::parse_custom_type_param(¶ms)? {
// let error_message = Tokenizer::tokenize_struct("0, [0,0,0])", &struct_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: struct value string must start and end with round brackets",
// error_message
// );
// }
// Ok(())
// }
// #[test]
// fn tokenize_struct_excess_opening_bracket_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "struct MyStruct".to_string(),
// components: Some(vec![
// Property {
// name: "num".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "arr".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Struct(struct_params) = ParamType::parse_custom_type_param(¶ms)? {
// let error_message = Tokenizer::tokenize_struct("((0, [0,0,0])", &struct_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: struct value string has excess opening brackets",
// error_message
// );
// }
// Ok(())
// }
// #[test]
// fn tokenize_struct_excess_closing_bracket_expected_error() -> Result<(), Error> {
// let params = Property {
// name: "input".to_string(),
// type_field: "struct MyStruct".to_string(),
// components: Some(vec![
// Property {
// name: "num".to_string(),
// type_field: "u64".to_string(),
// components: None,
// },
// Property {
// name: "arr".to_string(),
// type_field: "[u64; 3]".to_string(),
// components: None,
// },
// ]),
// };
// if let ParamType::Struct(struct_params) = ParamType::parse_custom_type_param(¶ms)? {
// let error_message = Tokenizer::tokenize_struct("(0, [0,0,0]))", &struct_params)
// .unwrap_err()
// .to_string();
// assert_eq!(
// "Invalid data: struct value string has excess closing brackets",
// error_message
// );
// }
// Ok(())
// }
#[test]
fn tokenize_array() -> Result<(), Error> {
let value = "[[1,2],[3],4]";
let param = ParamType::U16;
let tokens = Tokenizer::tokenize_array(value, ¶m)?;
let expected_tokens = Token::Array(vec![
Token::Array(vec![Token::U16(1), Token::U16(2)]), // First element, a sub-array with 2 elements
Token::Array(vec![Token::U16(3)]), // Second element, a sub-array with 1 element
Token::U16(4), // Third element
]);
assert_eq!(tokens, expected_tokens);
let value = "[1,[2],[3],[4,5]]";
let param = ParamType::U16;
let tokens = Tokenizer::tokenize_array(value, ¶m)?;
let expected_tokens = Token::Array(vec![
Token::U16(1),
Token::Array(vec![Token::U16(2)]),
Token::Array(vec![Token::U16(3)]),
Token::Array(vec![Token::U16(4), Token::U16(5)]),
]);
assert_eq!(tokens, expected_tokens);
let value = "[1,2,3,4,5]";
let param = ParamType::U16;
let tokens = Tokenizer::tokenize_array(value, ¶m)?;
let expected_tokens = Token::Array(vec![
Token::U16(1),
Token::U16(2),
Token::U16(3),
Token::U16(4),
Token::U16(5),
]);
assert_eq!(tokens, expected_tokens);
let value = "[[1,2,3,[4,5]]]";
let param = ParamType::U16;
let tokens = Tokenizer::tokenize_array(value, ¶m)?;
let expected_tokens = Token::Array(vec![Token::Array(vec![
Token::U16(1),
Token::U16(2),
Token::U16(3),
Token::Array(vec![Token::U16(4), Token::U16(5)]),
])]);
assert_eq!(tokens, expected_tokens);
Ok(())
}
}