static_storage.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. use std::{
  2. fmt::Write,
  3. sync::atomic::{AtomicBool, Ordering},
  4. thread,
  5. };
  6. use thingbuf::{StaticStringBuf, StaticThingBuf};
  7. #[test]
  8. fn static_storage_thingbuf() {
  9. static BUF: StaticThingBuf<i32, 16> = StaticThingBuf::new();
  10. static PRODUCER_LIVE: AtomicBool = AtomicBool::new(true);
  11. let producer = thread::spawn(move || {
  12. for i in 0..32 {
  13. let mut thing = 'write: loop {
  14. match BUF.push_ref() {
  15. Ok(thing) => break 'write thing,
  16. _ => thread::yield_now(),
  17. }
  18. };
  19. thing.with_mut(|thing| *thing = i);
  20. }
  21. PRODUCER_LIVE.store(false, Ordering::Release);
  22. });
  23. let mut i = 0;
  24. // While the producer is writing to the queue, push each entry to the
  25. // results string.
  26. while PRODUCER_LIVE.load(Ordering::Acquire) {
  27. match BUF.pop_ref() {
  28. Some(thing) => thing.with(|thing| {
  29. assert_eq!(*thing, i);
  30. i += 1;
  31. }),
  32. None => thread::yield_now(),
  33. }
  34. }
  35. producer.join().unwrap();
  36. // drain the queue.
  37. while let Some(thing) = BUF.pop_ref() {
  38. thing.with(|thing| {
  39. assert_eq!(*thing, i);
  40. i += 1;
  41. })
  42. }
  43. }
  44. #[test]
  45. fn static_storage_stringbuf() {
  46. static BUF: StaticStringBuf<8> = StaticStringBuf::new();
  47. static PRODUCER_LIVE: AtomicBool = AtomicBool::new(true);
  48. let producer = thread::spawn(move || {
  49. for i in 0..16 {
  50. let mut string = 'write: loop {
  51. match BUF.write() {
  52. Ok(string) => break 'write string,
  53. _ => thread::yield_now(),
  54. }
  55. };
  56. write!(&mut string, "{:?}", i).unwrap();
  57. }
  58. PRODUCER_LIVE.store(false, Ordering::Release);
  59. println!("producer done");
  60. });
  61. let mut results = String::new();
  62. // While the producer is writing to the queue, push each entry to the
  63. // results string.
  64. while PRODUCER_LIVE.load(Ordering::Acquire) {
  65. if let Some(string) = BUF.pop_ref() {
  66. writeln!(results, "{}", string).unwrap();
  67. }
  68. thread::yield_now();
  69. }
  70. producer.join().unwrap();
  71. println!("producer done...");
  72. // drain the queue.
  73. while let Some(string) = BUF.pop_ref() {
  74. writeln!(results, "{}", string).unwrap();
  75. }
  76. println!("results:\n{}", results);
  77. for (n, ln) in results.lines().enumerate() {
  78. assert_eq!(ln.parse::<usize>(), Ok(n));
  79. }
  80. }