static_storage.rs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. use std::{fmt::Write, sync::Arc, thread};
  2. use thingbuf::{Slot, StringBuf, ThingBuf};
  3. #[test]
  4. fn static_storage_thingbuf() {
  5. let thingbuf = Arc::new(ThingBuf::from_array([
  6. Slot::new(0),
  7. Slot::new(0),
  8. Slot::new(0),
  9. Slot::new(0),
  10. Slot::new(0),
  11. Slot::new(0),
  12. Slot::new(0),
  13. Slot::new(0),
  14. ]));
  15. let producer = {
  16. let thingbuf = thingbuf.clone();
  17. thread::spawn(move || {
  18. for i in 0..32 {
  19. let mut thing = 'write: loop {
  20. match thingbuf.push_ref() {
  21. Ok(thing) => break 'write thing,
  22. _ => thread::yield_now(),
  23. }
  24. };
  25. thing.with_mut(|thing| *thing = i);
  26. }
  27. })
  28. };
  29. let mut i = 0;
  30. // While the producer is writing to the queue, push each entry to the
  31. // results string.
  32. while Arc::strong_count(&thingbuf) > 1 {
  33. match thingbuf.pop_ref() {
  34. Some(thing) => thing.with(|thing| {
  35. assert_eq!(*thing, i);
  36. i += 1;
  37. }),
  38. None => thread::yield_now(),
  39. }
  40. }
  41. producer.join().unwrap();
  42. // drain the queue.
  43. while let Some(thing) = thingbuf.pop_ref() {
  44. thing.with(|thing| {
  45. assert_eq!(*thing, i);
  46. i += 1;
  47. })
  48. }
  49. }
  50. #[test]
  51. fn static_storage_stringbuf() {
  52. let stringbuf = Arc::new(StringBuf::from_array([
  53. Slot::new(String::new()),
  54. Slot::new(String::new()),
  55. Slot::new(String::new()),
  56. Slot::new(String::new()),
  57. Slot::new(String::new()),
  58. Slot::new(String::new()),
  59. Slot::new(String::new()),
  60. Slot::new(String::new()),
  61. ]));
  62. let producer = {
  63. let stringbuf = stringbuf.clone();
  64. thread::spawn(move || {
  65. for i in 0..16 {
  66. let mut string = 'write: loop {
  67. match stringbuf.write() {
  68. Ok(string) => break 'write string,
  69. _ => thread::yield_now(),
  70. }
  71. };
  72. write!(&mut string, "{:?}", i).unwrap();
  73. }
  74. })
  75. };
  76. let mut results = String::new();
  77. // While the producer is writing to the queue, push each entry to the
  78. // results string.
  79. while Arc::strong_count(&stringbuf) > 1 {
  80. if let Some(string) = stringbuf.pop_ref() {
  81. writeln!(results, "{}", string).unwrap();
  82. }
  83. thread::yield_now();
  84. }
  85. producer.join().unwrap();
  86. // drain the queue.
  87. while let Some(string) = stringbuf.pop_ref() {
  88. writeln!(results, "{}", string).unwrap();
  89. }
  90. let results = dbg!(results);
  91. for (n, ln) in results.lines().enumerate() {
  92. assert_eq!(ln.parse::<usize>(), Ok(n));
  93. }
  94. }