1
0

Buffer.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Reactive.Concurrency;
  6. using System.Reactive.Disposables;
  7. namespace System.Reactive.Linq.ObservableImpl
  8. {
  9. internal static class Buffer<TSource>
  10. {
  11. internal sealed class Count : Producer<IList<TSource>, Count._>
  12. {
  13. private readonly IObservable<TSource> _source;
  14. private readonly int _count;
  15. private readonly int _skip;
  16. public Count(IObservable<TSource> source, int count, int skip)
  17. {
  18. _source = source;
  19. _count = count;
  20. _skip = skip;
  21. }
  22. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  23. protected override void Run(_ sink) => sink.Run(_source);
  24. internal sealed class _ : Sink<TSource, IList<TSource>>
  25. {
  26. private readonly Queue<IList<TSource>> _queue = new Queue<IList<TSource>>();
  27. private readonly int _count;
  28. private readonly int _skip;
  29. public _(Count parent, IObserver<IList<TSource>> observer)
  30. : base(observer)
  31. {
  32. _count = parent._count;
  33. _skip = parent._skip;
  34. }
  35. private int _n;
  36. public override void Run(IObservable<TSource> source)
  37. {
  38. _n = 0;
  39. CreateWindow();
  40. base.Run(source);
  41. }
  42. private void CreateWindow()
  43. {
  44. var s = new List<TSource>();
  45. _queue.Enqueue(s);
  46. }
  47. public override void OnNext(TSource value)
  48. {
  49. foreach (var s in _queue)
  50. s.Add(value);
  51. var c = _n - _count + 1;
  52. if (c >= 0 && c % _skip == 0)
  53. {
  54. var s = _queue.Dequeue();
  55. if (s.Count > 0)
  56. ForwardOnNext(s);
  57. }
  58. _n++;
  59. if (_n % _skip == 0)
  60. CreateWindow();
  61. }
  62. public override void OnError(Exception error)
  63. {
  64. while (_queue.Count > 0)
  65. _queue.Dequeue().Clear();
  66. ForwardOnError(error);
  67. }
  68. public override void OnCompleted()
  69. {
  70. while (_queue.Count > 0)
  71. {
  72. var s = _queue.Dequeue();
  73. if (s.Count > 0)
  74. ForwardOnNext(s);
  75. }
  76. ForwardOnCompleted();
  77. }
  78. }
  79. }
  80. internal sealed class TimeSliding : Producer<IList<TSource>, TimeSliding._>
  81. {
  82. private readonly IObservable<TSource> _source;
  83. private readonly TimeSpan _timeSpan;
  84. private readonly TimeSpan _timeShift;
  85. private readonly IScheduler _scheduler;
  86. public TimeSliding(IObservable<TSource> source, TimeSpan timeSpan, TimeSpan timeShift, IScheduler scheduler)
  87. {
  88. _source = source;
  89. _timeSpan = timeSpan;
  90. _timeShift = timeShift;
  91. _scheduler = scheduler;
  92. }
  93. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  94. protected override void Run(_ sink) => sink.Run(this);
  95. internal sealed class _ : Sink<TSource, IList<TSource>>
  96. {
  97. private readonly TimeSpan _timeShift;
  98. private readonly IScheduler _scheduler;
  99. private readonly object _gate = new object();
  100. private readonly Queue<List<TSource>> _q = new Queue<List<TSource>>();
  101. private IDisposable _timerSerial;
  102. public _(TimeSliding parent, IObserver<IList<TSource>> observer)
  103. : base(observer)
  104. {
  105. _timeShift = parent._timeShift;
  106. _scheduler = parent._scheduler;
  107. }
  108. private TimeSpan _totalTime;
  109. private TimeSpan _nextShift;
  110. private TimeSpan _nextSpan;
  111. public void Run(TimeSliding parent)
  112. {
  113. _totalTime = TimeSpan.Zero;
  114. _nextShift = parent._timeShift;
  115. _nextSpan = parent._timeSpan;
  116. CreateWindow();
  117. CreateTimer();
  118. base.Run(parent._source);
  119. }
  120. protected override void Dispose(bool disposing)
  121. {
  122. if (disposing)
  123. {
  124. Disposable.TryDispose(ref _timerSerial);
  125. }
  126. base.Dispose(disposing);
  127. }
  128. private void CreateWindow()
  129. {
  130. var s = new List<TSource>();
  131. _q.Enqueue(s);
  132. }
  133. private void CreateTimer()
  134. {
  135. var m = new SingleAssignmentDisposable();
  136. Disposable.TrySetSerial(ref _timerSerial, m);
  137. var isSpan = false;
  138. var isShift = false;
  139. if (_nextSpan == _nextShift)
  140. {
  141. isSpan = true;
  142. isShift = true;
  143. }
  144. else if (_nextSpan < _nextShift)
  145. isSpan = true;
  146. else
  147. isShift = true;
  148. var newTotalTime = isSpan ? _nextSpan : _nextShift;
  149. var ts = newTotalTime - _totalTime;
  150. _totalTime = newTotalTime;
  151. if (isSpan)
  152. _nextSpan += _timeShift;
  153. if (isShift)
  154. _nextShift += _timeShift;
  155. m.Disposable = _scheduler.Schedule(new State { isSpan = isSpan, isShift = isShift }, ts, Tick);
  156. }
  157. private struct State
  158. {
  159. public bool isSpan;
  160. public bool isShift;
  161. }
  162. private IDisposable Tick(IScheduler self, State state)
  163. {
  164. lock (_gate)
  165. {
  166. //
  167. // Before v2, the two operations below were reversed. This doesn't have an observable
  168. // difference for Buffer, but is done to keep code consistent with Window, where we
  169. // took a breaking change in v2 to ensure consistency across overloads. For more info,
  170. // see the comment in Tick for Window.
  171. //
  172. if (state.isSpan)
  173. {
  174. var s = _q.Dequeue();
  175. ForwardOnNext(s);
  176. }
  177. if (state.isShift)
  178. {
  179. CreateWindow();
  180. }
  181. }
  182. CreateTimer();
  183. return Disposable.Empty;
  184. }
  185. public override void OnNext(TSource value)
  186. {
  187. lock (_gate)
  188. {
  189. foreach (var s in _q)
  190. s.Add(value);
  191. }
  192. }
  193. public override void OnError(Exception error)
  194. {
  195. lock (_gate)
  196. {
  197. while (_q.Count > 0)
  198. _q.Dequeue().Clear();
  199. ForwardOnError(error);
  200. }
  201. }
  202. public override void OnCompleted()
  203. {
  204. lock (_gate)
  205. {
  206. while (_q.Count > 0)
  207. ForwardOnNext(_q.Dequeue());
  208. ForwardOnCompleted();
  209. }
  210. }
  211. }
  212. }
  213. internal sealed class TimeHopping : Producer<IList<TSource>, TimeHopping._>
  214. {
  215. private readonly IObservable<TSource> _source;
  216. private readonly TimeSpan _timeSpan;
  217. private readonly IScheduler _scheduler;
  218. public TimeHopping(IObservable<TSource> source, TimeSpan timeSpan, IScheduler scheduler)
  219. {
  220. _source = source;
  221. _timeSpan = timeSpan;
  222. _scheduler = scheduler;
  223. }
  224. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
  225. protected override void Run(_ sink) => sink.Run(this);
  226. internal sealed class _ : Sink<TSource, IList<TSource>>
  227. {
  228. private readonly object _gate = new object();
  229. public _(IObserver<IList<TSource>> observer)
  230. : base(observer)
  231. {
  232. }
  233. private List<TSource> _list;
  234. private IDisposable _periodicDisposable;
  235. public void Run(TimeHopping parent)
  236. {
  237. _list = new List<TSource>();
  238. Disposable.SetSingle(ref _periodicDisposable, parent._scheduler.SchedulePeriodic(parent._timeSpan, Tick));
  239. base.Run(parent._source);
  240. }
  241. protected override void Dispose(bool disposing)
  242. {
  243. if (disposing)
  244. {
  245. Disposable.TryDispose(ref _periodicDisposable);
  246. }
  247. base.Dispose(disposing);
  248. }
  249. private void Tick()
  250. {
  251. lock (_gate)
  252. {
  253. ForwardOnNext(_list);
  254. _list = new List<TSource>();
  255. }
  256. }
  257. public override void OnNext(TSource value)
  258. {
  259. lock (_gate)
  260. {
  261. _list.Add(value);
  262. }
  263. }
  264. public override void OnError(Exception error)
  265. {
  266. lock (_gate)
  267. {
  268. _list.Clear();
  269. ForwardOnError(error);
  270. }
  271. }
  272. public override void OnCompleted()
  273. {
  274. lock (_gate)
  275. {
  276. ForwardOnNext(_list);
  277. ForwardOnCompleted();
  278. }
  279. }
  280. }
  281. }
  282. internal sealed class Ferry : Producer<IList<TSource>, Ferry._>
  283. {
  284. private readonly IObservable<TSource> _source;
  285. private readonly int _count;
  286. private readonly TimeSpan _timeSpan;
  287. private readonly IScheduler _scheduler;
  288. public Ferry(IObservable<TSource> source, TimeSpan timeSpan, int count, IScheduler scheduler)
  289. {
  290. _source = source;
  291. _timeSpan = timeSpan;
  292. _count = count;
  293. _scheduler = scheduler;
  294. }
  295. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  296. protected override void Run(_ sink) => sink.Run();
  297. internal sealed class _ : Sink<TSource, IList<TSource>>
  298. {
  299. private readonly Ferry _parent;
  300. private readonly object _gate = new object();
  301. private IDisposable _timerSerial;
  302. public _(Ferry parent, IObserver<IList<TSource>> observer)
  303. : base(observer)
  304. {
  305. _parent = parent;
  306. }
  307. private IList<TSource> _s;
  308. private int _n;
  309. private int _windowId;
  310. public void Run()
  311. {
  312. _s = new List<TSource>();
  313. _n = 0;
  314. _windowId = 0;
  315. CreateTimer(0);
  316. SetUpstream(_parent._source.SubscribeSafe(this));
  317. }
  318. protected override void Dispose(bool disposing)
  319. {
  320. if (disposing)
  321. {
  322. Disposable.TryDispose(ref _timerSerial);
  323. }
  324. base.Dispose(disposing);
  325. }
  326. private void CreateTimer(int id)
  327. {
  328. var m = new SingleAssignmentDisposable();
  329. Disposable.TrySetSerial(ref _timerSerial, m);
  330. m.Disposable = _parent._scheduler.Schedule(id, _parent._timeSpan, Tick);
  331. }
  332. private IDisposable Tick(IScheduler self, int id)
  333. {
  334. var d = Disposable.Empty;
  335. var newId = 0;
  336. lock (_gate)
  337. {
  338. if (id != _windowId)
  339. return d;
  340. _n = 0;
  341. newId = ++_windowId;
  342. var res = _s;
  343. _s = new List<TSource>();
  344. ForwardOnNext(res);
  345. CreateTimer(newId);
  346. }
  347. return d;
  348. }
  349. public override void OnNext(TSource value)
  350. {
  351. var newWindow = false;
  352. var newId = 0;
  353. lock (_gate)
  354. {
  355. _s.Add(value);
  356. _n++;
  357. if (_n == _parent._count)
  358. {
  359. newWindow = true;
  360. _n = 0;
  361. newId = ++_windowId;
  362. var res = _s;
  363. _s = new List<TSource>();
  364. ForwardOnNext(res);
  365. }
  366. if (newWindow)
  367. CreateTimer(newId);
  368. }
  369. }
  370. public override void OnError(Exception error)
  371. {
  372. lock (_gate)
  373. {
  374. _s.Clear();
  375. ForwardOnError(error);
  376. }
  377. }
  378. public override void OnCompleted()
  379. {
  380. lock (_gate)
  381. {
  382. ForwardOnNext(_s);
  383. ForwardOnCompleted();
  384. }
  385. }
  386. }
  387. }
  388. }
  389. internal static class Buffer<TSource, TBufferClosing>
  390. {
  391. internal sealed class Selector : Producer<IList<TSource>, Selector._>
  392. {
  393. private readonly IObservable<TSource> _source;
  394. private readonly Func<IObservable<TBufferClosing>> _bufferClosingSelector;
  395. public Selector(IObservable<TSource> source, Func<IObservable<TBufferClosing>> bufferClosingSelector)
  396. {
  397. _source = source;
  398. _bufferClosingSelector = bufferClosingSelector;
  399. }
  400. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  401. protected override void Run(_ sink) => sink.Run(_source);
  402. internal sealed class _ : Sink<TSource, IList<TSource>>
  403. {
  404. private readonly object _gate = new object();
  405. private readonly AsyncLock _bufferGate = new AsyncLock();
  406. private IDisposable _bufferClosingSerialDisposable;
  407. private readonly Func<IObservable<TBufferClosing>> _bufferClosingSelector;
  408. public _(Selector parent, IObserver<IList<TSource>> observer)
  409. : base(observer)
  410. {
  411. _bufferClosingSelector = parent._bufferClosingSelector;
  412. }
  413. private IList<TSource> _buffer;
  414. public override void Run(IObservable<TSource> source)
  415. {
  416. _buffer = new List<TSource>();
  417. base.Run(source);
  418. _bufferGate.Wait(this, @this => @this.CreateBufferClose());
  419. }
  420. protected override void Dispose(bool disposing)
  421. {
  422. if (disposing)
  423. {
  424. Disposable.TryDispose(ref _bufferClosingSerialDisposable);
  425. }
  426. base.Dispose(disposing);
  427. }
  428. private void CreateBufferClose()
  429. {
  430. var bufferClose = default(IObservable<TBufferClosing>);
  431. try
  432. {
  433. bufferClose = _bufferClosingSelector();
  434. }
  435. catch (Exception exception)
  436. {
  437. lock (_gate)
  438. {
  439. ForwardOnError(exception);
  440. }
  441. return;
  442. }
  443. var closingSubscription = new SingleAssignmentDisposable();
  444. Disposable.TrySetSerial(ref _bufferClosingSerialDisposable, closingSubscription);
  445. closingSubscription.Disposable = bufferClose.SubscribeSafe(new BufferClosingObserver(this, closingSubscription));
  446. }
  447. private void CloseBuffer(IDisposable closingSubscription)
  448. {
  449. closingSubscription.Dispose();
  450. lock (_gate)
  451. {
  452. var res = _buffer;
  453. _buffer = new List<TSource>();
  454. ForwardOnNext(res);
  455. }
  456. _bufferGate.Wait(this, @this => @this.CreateBufferClose());
  457. }
  458. private sealed class BufferClosingObserver : IObserver<TBufferClosing>
  459. {
  460. private readonly _ _parent;
  461. private readonly IDisposable _self;
  462. public BufferClosingObserver(_ parent, IDisposable self)
  463. {
  464. _parent = parent;
  465. _self = self;
  466. }
  467. public void OnNext(TBufferClosing value)
  468. {
  469. _parent.CloseBuffer(_self);
  470. }
  471. public void OnError(Exception error)
  472. {
  473. _parent.OnError(error);
  474. }
  475. public void OnCompleted()
  476. {
  477. _parent.CloseBuffer(_self);
  478. }
  479. }
  480. public override void OnNext(TSource value)
  481. {
  482. lock (_gate)
  483. {
  484. _buffer.Add(value);
  485. }
  486. }
  487. public override void OnError(Exception error)
  488. {
  489. lock (_gate)
  490. {
  491. _buffer.Clear();
  492. ForwardOnError(error);
  493. }
  494. }
  495. public override void OnCompleted()
  496. {
  497. lock (_gate)
  498. {
  499. ForwardOnNext(_buffer);
  500. ForwardOnCompleted();
  501. }
  502. }
  503. }
  504. }
  505. internal sealed class Boundaries : Producer<IList<TSource>, Boundaries._>
  506. {
  507. private readonly IObservable<TSource> _source;
  508. private readonly IObservable<TBufferClosing> _bufferBoundaries;
  509. public Boundaries(IObservable<TSource> source, IObservable<TBufferClosing> bufferBoundaries)
  510. {
  511. _source = source;
  512. _bufferBoundaries = bufferBoundaries;
  513. }
  514. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
  515. protected override void Run(_ sink) => sink.Run(this);
  516. internal sealed class _ : Sink<TSource, IList<TSource>>
  517. {
  518. private readonly object _gate = new object();
  519. public _(IObserver<IList<TSource>> observer)
  520. : base(observer)
  521. {
  522. }
  523. private IList<TSource> _buffer;
  524. private IDisposable _boundariesDisposable;
  525. public void Run(Boundaries parent)
  526. {
  527. _buffer = new List<TSource>();
  528. base.Run(parent._source);
  529. Disposable.SetSingle(ref _boundariesDisposable, parent._bufferBoundaries.SubscribeSafe(new BufferClosingObserver(this)));
  530. }
  531. protected override void Dispose(bool disposing)
  532. {
  533. if (disposing)
  534. {
  535. Disposable.TryDispose(ref _boundariesDisposable);
  536. }
  537. base.Dispose(disposing);
  538. }
  539. private sealed class BufferClosingObserver : IObserver<TBufferClosing>
  540. {
  541. private readonly _ _parent;
  542. public BufferClosingObserver(_ parent)
  543. {
  544. _parent = parent;
  545. }
  546. public void OnNext(TBufferClosing value)
  547. {
  548. lock (_parent._gate)
  549. {
  550. var res = _parent._buffer;
  551. _parent._buffer = new List<TSource>();
  552. _parent.ForwardOnNext(res);
  553. }
  554. }
  555. public void OnError(Exception error)
  556. {
  557. _parent.OnError(error);
  558. }
  559. public void OnCompleted()
  560. {
  561. _parent.OnCompleted();
  562. }
  563. }
  564. public override void OnNext(TSource value)
  565. {
  566. lock (_gate)
  567. {
  568. _buffer.Add(value);
  569. }
  570. }
  571. public override void OnError(Exception error)
  572. {
  573. lock (_gate)
  574. {
  575. _buffer.Clear();
  576. ForwardOnError(error);
  577. }
  578. }
  579. public override void OnCompleted()
  580. {
  581. lock (_gate)
  582. {
  583. ForwardOnNext(_buffer);
  584. ForwardOnCompleted();
  585. }
  586. }
  587. }
  588. }
  589. }
  590. }