Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. use std::cell::RefCell;
  2.  
  3. // Wrapper holding (amoung other things) a vec of entries
  4. // as well as some values that are constant for all entries
  5. struct Wrapper {
  6. entries: Vec<Entry>,
  7. some_values_constant_for_all_entries: Vec<usize>
  8. }
  9.  
  10. impl Wrapper {
  11. pub fn new() -> Self {
  12. let mut entries = Vec::with_capacity(3);
  13. for val in 0..3 {
  14. entries.push(Entry { val });
  15. }
  16. Wrapper {
  17. entries,
  18. some_values_constant_for_all_entries: vec![1,2,4]
  19. }
  20. }
  21.  
  22. pub fn entries_mut(&mut self) -> &mut Vec<Entry> {
  23. &mut self.entries
  24. }
  25.  
  26. pub fn constant_values(&self) -> &Vec<usize> {
  27. &self.some_values_constant_for_all_entries
  28. }
  29. }
  30.  
  31. // Entry holding a value (and various other things)
  32. struct Entry {
  33. val: usize
  34. }
  35.  
  36. impl Entry {
  37. pub fn update_val(&mut self, update_value: usize, constant_values: &Vec<usize>) {
  38. //update value based off the update_value and constant_values
  39. }
  40.  
  41. pub fn val(&self) -> usize {
  42. self.val
  43. }
  44. }
  45.  
  46. // implementations of the trait define how the values get updated
  47. trait MyTrait {
  48. fn calculate_update_value(&self, wrapper: &RefCell<Wrapper>);
  49. }
  50.  
  51. struct SomeImpl {
  52. some_val: usize
  53. }
  54.  
  55. impl MyTrait for SomeImpl {
  56. fn calculate_update_value(&self, wrapper: &RefCell<Wrapper>) {
  57. for entry in wrapper.borrow_mut().entries_mut().iter_mut() {
  58. let val = entry.val % self.some_val;
  59. entry.update_val(val, wrapper.borrow().constant_values());
  60. }
  61. }
  62. }
  63.  
  64. struct Algorithm<T> where T: MyTrait {
  65. wrapper: RefCell<Wrapper>,
  66. implementation: T
  67. }
  68.  
  69. impl<T> Algorithm<T> where T: MyTrait {
  70. fn update(&mut self) {
  71. self.implementation.calculate_update_value(&self.wrapper);
  72. }
  73. }
  74.  
  75.  
  76.  
  77. fn main() {
  78. let wrapper = Wrapper::new();
  79. let implementation = SomeImpl { some_val: 5 };
  80. let mut algorithm = Algorithm {wrapper: RefCell::new(wrapper), implementation};
  81. algorithm.update();
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement