improved_plain.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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. fn compute_prefix_sum(arr: &[u16]) -> Vec<u16> {
  19. let mut sum = 0;
  20. arr.iter()
  21. .map(|a| {
  22. sum += a;
  23. sum
  24. })
  25. .collect()
  26. }
  27. fn fill_orders(total_orders: u16, orders: &mut [u16], prefix_sum_arr: &[u16]) {
  28. for (i, order) in orders.iter_mut().enumerate() {
  29. let previous_prefix_sum = if i == 0 { 0 } else { prefix_sum_arr[i - 1] };
  30. *order = (total_orders as i64 - previous_prefix_sum as i64)
  31. .max(0)
  32. .min(*order as i64) as u16;
  33. }
  34. }
  35. pub fn volume_match(sell_orders: &mut [u16], buy_orders: &mut [u16]) {
  36. let prefix_sum_sell_orders = compute_prefix_sum(sell_orders);
  37. let prefix_sum_buy_orders = compute_prefix_sum(buy_orders);
  38. let total_buy_orders = *prefix_sum_buy_orders.last().unwrap_or(&0);
  39. let total_sell_orders = *prefix_sum_sell_orders.last().unwrap_or(&0);
  40. fill_orders(total_sell_orders, buy_orders, &prefix_sum_buy_orders);
  41. fill_orders(total_buy_orders, sell_orders, &prefix_sum_sell_orders);
  42. }