plain.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::time::Instant;
  19. fn fill_orders(orders: &mut [u16], total_volume: u16) {
  20. let mut volume_left_to_transact = total_volume;
  21. for order in orders {
  22. let filled_amount = std::cmp::min(volume_left_to_transact, *order);
  23. *order = filled_amount;
  24. volume_left_to_transact -= filled_amount;
  25. }
  26. }
  27. /// Plain implementation of the volume matching algorithm.
  28. ///
  29. /// Matches the given [sell_orders] with [buy_orders].
  30. /// The amount of the orders that are successfully filled is written over the original order count.
  31. pub fn volume_match(sell_orders: &mut [u16], buy_orders: &mut [u16]) {
  32. let total_sell_volume: u16 = sell_orders.iter().sum();
  33. let total_buy_volume: u16 = buy_orders.iter().sum();
  34. let total_volume = std::cmp::min(total_buy_volume, total_sell_volume);
  35. fill_orders(sell_orders, total_volume);
  36. fill_orders(buy_orders, total_volume);
  37. }
  38. pub fn tester(
  39. input_sell_orders: &[u16],
  40. input_buy_orders: &[u16],
  41. expected_filled_sells: &[u16],
  42. expected_filled_buys: &[u16],
  43. function: fn(&mut [u16], &mut [u16]),
  44. ) {
  45. let mut sell_orders = input_sell_orders.to_vec();
  46. let mut buy_orders = input_buy_orders.to_vec();
  47. println!("Running plain implementation...");
  48. let time = Instant::now();
  49. function(&mut sell_orders, &mut buy_orders);
  50. println!("Ran plain implementation in {:?}", time.elapsed());
  51. assert_eq!(sell_orders, expected_filled_sells);
  52. assert_eq!(buy_orders, expected_filled_buys);
  53. }