rpc.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. pub fn format_callback(function_name: String, arg: String) -> String {
  2. let formatted_string = &format!("window[\"{}\"]({})", function_name, arg);
  3. formatted_string.to_string()
  4. }
  5. pub fn format_callback_result(
  6. result: Result<String, String>,
  7. callback: String,
  8. error_callback: String,
  9. ) -> String {
  10. match result {
  11. Ok(res) => format_callback(callback, res),
  12. Err(err) => format_callback(error_callback, format!("\"{}\"", err)),
  13. }
  14. }
  15. #[cfg(test)]
  16. mod test {
  17. use crate::rpc::*;
  18. use quickcheck_macros::quickcheck;
  19. // check abritrary strings in the format callback function
  20. #[quickcheck]
  21. fn qc_formating(f: String, a: String) -> bool {
  22. // can not accept empty strings
  23. if f != "" && a != "" {
  24. // get length of function and argument
  25. let alen = &a.len();
  26. let flen = &f.len();
  27. // call format callback
  28. let fc = format_callback(f, a);
  29. // get length of the resulting string
  30. let fclen = fc.len();
  31. // if formatted string equals the length of the argument and the function plus 12 then its correct.
  32. fclen == alen + flen + 12
  33. } else {
  34. true
  35. }
  36. }
  37. // check arbitrary strings in format_callback_result
  38. #[quickcheck]
  39. fn qc_format_res(result: Result<String, String>, c: String, ec: String) -> bool {
  40. // match on result to decide how to call the function.
  41. match result {
  42. // if ok, get length of result and callback strings.
  43. Ok(r) => {
  44. let rlen = r.len();
  45. let clen = c.len();
  46. // take the ok string from result and pass it into format_callback_result as an ok.
  47. let resp = format_callback_result(Ok(r), c, ec);
  48. // get response string length
  49. let reslen = resp.len();
  50. // if response string length equals result and callback length plus 12 characters then it is correct.
  51. reslen == rlen + clen + 12
  52. }
  53. // If Err, get length of Err and Error callback
  54. Err(err) => {
  55. let eclen = ec.len();
  56. let errlen = err.len();
  57. // pass err as Err into format_callback_result with callback and error callback
  58. let resp = format_callback_result(Err(err), c, ec);
  59. // get response string length
  60. let reslen = resp.len();
  61. // if length of response string equals the error length and the error callback length plus 14 characters then its is correct.
  62. reslen == eclen + errlen + 14
  63. }
  64. }
  65. }
  66. }