Buffer.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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 CountExact : Producer<IList<TSource>, CountExact.ExactSink>
  12. {
  13. private readonly IObservable<TSource> _source;
  14. private readonly int _count;
  15. public CountExact(IObservable<TSource> source, int count)
  16. {
  17. _source = source;
  18. _count = count;
  19. }
  20. protected override ExactSink CreateSink(IObserver<IList<TSource>> observer) => new ExactSink(observer, _count);
  21. protected override void Run(ExactSink sink) => sink.Run(_source);
  22. internal sealed class ExactSink : Sink<TSource, IList<TSource>>
  23. {
  24. private readonly int _count;
  25. private int _index;
  26. private IList<TSource> _buffer;
  27. internal ExactSink(IObserver<IList<TSource>> observer, int count) : base(observer)
  28. {
  29. _count = count;
  30. }
  31. public override void OnNext(TSource value)
  32. {
  33. var buffer = _buffer;
  34. if (buffer == null)
  35. {
  36. buffer = new List<TSource>();
  37. _buffer = buffer;
  38. }
  39. buffer.Add(value);
  40. var idx = _index + 1;
  41. if (idx == _count)
  42. {
  43. _buffer = null;
  44. _index = 0;
  45. ForwardOnNext(buffer);
  46. }
  47. else
  48. {
  49. _index = idx;
  50. }
  51. }
  52. public override void OnError(Exception error)
  53. {
  54. _buffer = null;
  55. ForwardOnError(error);
  56. }
  57. public override void OnCompleted()
  58. {
  59. var buffer = _buffer;
  60. _buffer = null;
  61. if (buffer != null)
  62. {
  63. ForwardOnNext(buffer);
  64. }
  65. ForwardOnCompleted();
  66. }
  67. }
  68. }
  69. internal sealed class CountSkip : Producer<IList<TSource>, CountSkip.SkipSink>
  70. {
  71. private readonly IObservable<TSource> _source;
  72. private readonly int _count;
  73. private readonly int _skip;
  74. public CountSkip(IObservable<TSource> source, int count, int skip)
  75. {
  76. _source = source;
  77. _count = count;
  78. _skip = skip;
  79. }
  80. protected override SkipSink CreateSink(IObserver<IList<TSource>> observer) => new SkipSink(observer, _count, _skip);
  81. protected override void Run(SkipSink sink) => sink.Run(_source);
  82. internal sealed class SkipSink : Sink<TSource, IList<TSource>>
  83. {
  84. private readonly int _count;
  85. private readonly int _skip;
  86. private int _index;
  87. private IList<TSource> _buffer;
  88. internal SkipSink(IObserver<IList<TSource>> observer, int count, int skip) : base(observer)
  89. {
  90. _count = count;
  91. _skip = skip;
  92. }
  93. public override void OnNext(TSource value)
  94. {
  95. var idx = _index;
  96. var buffer = _buffer;
  97. if (idx == 0)
  98. {
  99. buffer = new List<TSource>();
  100. _buffer = buffer;
  101. }
  102. buffer?.Add(value);
  103. if (++idx == _count)
  104. {
  105. _buffer = null;
  106. ForwardOnNext(buffer);
  107. }
  108. if (idx == _skip)
  109. {
  110. _index = 0;
  111. }
  112. else
  113. {
  114. _index = idx;
  115. }
  116. }
  117. public override void OnError(Exception error)
  118. {
  119. _buffer = null;
  120. ForwardOnError(error);
  121. }
  122. public override void OnCompleted()
  123. {
  124. var buffer = _buffer;
  125. _buffer = null;
  126. if (buffer != null)
  127. {
  128. ForwardOnNext(buffer);
  129. }
  130. ForwardOnCompleted();
  131. }
  132. }
  133. }
  134. internal sealed class CountOverlap : Producer<IList<TSource>, CountOverlap.OverlapSink>
  135. {
  136. private readonly IObservable<TSource> _source;
  137. private readonly int _count;
  138. private readonly int _skip;
  139. public CountOverlap(IObservable<TSource> source, int count, int skip)
  140. {
  141. _source = source;
  142. _count = count;
  143. _skip = skip;
  144. }
  145. protected override OverlapSink CreateSink(IObserver<IList<TSource>> observer) => new OverlapSink(observer, _count, _skip);
  146. protected override void Run(OverlapSink sink) => sink.Run(_source);
  147. internal sealed class OverlapSink : Sink<TSource, IList<TSource>>
  148. {
  149. private readonly Queue<IList<TSource>> _queue;
  150. private readonly int _count;
  151. private readonly int _skip;
  152. private int _n;
  153. public OverlapSink(IObserver<IList<TSource>> observer, int count, int skip)
  154. : base(observer)
  155. {
  156. _queue = new Queue<IList<TSource>>();
  157. _count = count;
  158. _skip = skip;
  159. CreateWindow();
  160. }
  161. private void CreateWindow()
  162. {
  163. var s = new List<TSource>();
  164. _queue.Enqueue(s);
  165. }
  166. public override void OnNext(TSource value)
  167. {
  168. foreach (var s in _queue)
  169. {
  170. s.Add(value);
  171. }
  172. var c = _n - _count + 1;
  173. if (c >= 0 && c % _skip == 0)
  174. {
  175. var s = _queue.Dequeue();
  176. if (s.Count > 0)
  177. {
  178. ForwardOnNext(s);
  179. }
  180. }
  181. _n++;
  182. if (_n % _skip == 0)
  183. {
  184. CreateWindow();
  185. }
  186. }
  187. public override void OnError(Exception error)
  188. {
  189. // just drop the ILists on the GC floor, no reason to clear them
  190. _queue.Clear();
  191. ForwardOnError(error);
  192. }
  193. public override void OnCompleted()
  194. {
  195. while (_queue.Count > 0)
  196. {
  197. var s = _queue.Dequeue();
  198. if (s.Count > 0)
  199. {
  200. ForwardOnNext(s);
  201. }
  202. }
  203. ForwardOnCompleted();
  204. }
  205. }
  206. }
  207. internal sealed class TimeSliding : Producer<IList<TSource>, TimeSliding._>
  208. {
  209. private readonly IObservable<TSource> _source;
  210. private readonly TimeSpan _timeSpan;
  211. private readonly TimeSpan _timeShift;
  212. private readonly IScheduler _scheduler;
  213. public TimeSliding(IObservable<TSource> source, TimeSpan timeSpan, TimeSpan timeShift, IScheduler scheduler)
  214. {
  215. _source = source;
  216. _timeSpan = timeSpan;
  217. _timeShift = timeShift;
  218. _scheduler = scheduler;
  219. }
  220. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  221. protected override void Run(_ sink) => sink.Run(this);
  222. internal sealed class _ : Sink<TSource, IList<TSource>>
  223. {
  224. private readonly TimeSpan _timeShift;
  225. private readonly IScheduler _scheduler;
  226. private readonly object _gate = new object();
  227. private readonly Queue<List<TSource>> _q = new Queue<List<TSource>>();
  228. private IDisposable _timerSerial;
  229. public _(TimeSliding parent, IObserver<IList<TSource>> observer)
  230. : base(observer)
  231. {
  232. _timeShift = parent._timeShift;
  233. _scheduler = parent._scheduler;
  234. }
  235. private TimeSpan _totalTime;
  236. private TimeSpan _nextShift;
  237. private TimeSpan _nextSpan;
  238. public void Run(TimeSliding parent)
  239. {
  240. _totalTime = TimeSpan.Zero;
  241. _nextShift = parent._timeShift;
  242. _nextSpan = parent._timeSpan;
  243. CreateWindow();
  244. CreateTimer();
  245. Run(parent._source);
  246. }
  247. protected override void Dispose(bool disposing)
  248. {
  249. if (disposing)
  250. {
  251. Disposable.TryDispose(ref _timerSerial);
  252. }
  253. base.Dispose(disposing);
  254. }
  255. private void CreateWindow()
  256. {
  257. var s = new List<TSource>();
  258. _q.Enqueue(s);
  259. }
  260. private void CreateTimer()
  261. {
  262. var m = new SingleAssignmentDisposable();
  263. Disposable.TrySetSerial(ref _timerSerial, m);
  264. var isSpan = false;
  265. var isShift = false;
  266. if (_nextSpan == _nextShift)
  267. {
  268. isSpan = true;
  269. isShift = true;
  270. }
  271. else if (_nextSpan < _nextShift)
  272. {
  273. isSpan = true;
  274. }
  275. else
  276. {
  277. isShift = true;
  278. }
  279. var newTotalTime = isSpan ? _nextSpan : _nextShift;
  280. var ts = newTotalTime - _totalTime;
  281. _totalTime = newTotalTime;
  282. if (isSpan)
  283. {
  284. _nextSpan += _timeShift;
  285. }
  286. if (isShift)
  287. {
  288. _nextShift += _timeShift;
  289. }
  290. m.Disposable = _scheduler.ScheduleAction((@this: this, isSpan, isShift), ts, tuple => [email protected](tuple.isSpan, tuple.isShift));
  291. }
  292. private void Tick(bool isSpan, bool isShift)
  293. {
  294. lock (_gate)
  295. {
  296. //
  297. // Before v2, the two operations below were reversed. This doesn't have an observable
  298. // difference for Buffer, but is done to keep code consistent with Window, where we
  299. // took a breaking change in v2 to ensure consistency across overloads. For more info,
  300. // see the comment in Tick for Window.
  301. //
  302. if (isSpan)
  303. {
  304. if (_q.Count > 0)
  305. {
  306. var s = _q.Dequeue();
  307. ForwardOnNext(s);
  308. }
  309. }
  310. if (isShift)
  311. {
  312. CreateWindow();
  313. }
  314. }
  315. CreateTimer();
  316. }
  317. public override void OnNext(TSource value)
  318. {
  319. lock (_gate)
  320. {
  321. foreach (var s in _q)
  322. {
  323. s.Add(value);
  324. }
  325. }
  326. }
  327. public override void OnError(Exception error)
  328. {
  329. lock (_gate)
  330. {
  331. while (_q.Count > 0)
  332. {
  333. _q.Dequeue().Clear();
  334. }
  335. ForwardOnError(error);
  336. }
  337. }
  338. public override void OnCompleted()
  339. {
  340. lock (_gate)
  341. {
  342. while (_q.Count > 0)
  343. {
  344. ForwardOnNext(_q.Dequeue());
  345. }
  346. ForwardOnCompleted();
  347. }
  348. }
  349. }
  350. }
  351. internal sealed class TimeHopping : Producer<IList<TSource>, TimeHopping._>
  352. {
  353. private readonly IObservable<TSource> _source;
  354. private readonly TimeSpan _timeSpan;
  355. private readonly IScheduler _scheduler;
  356. public TimeHopping(IObservable<TSource> source, TimeSpan timeSpan, IScheduler scheduler)
  357. {
  358. _source = source;
  359. _timeSpan = timeSpan;
  360. _scheduler = scheduler;
  361. }
  362. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
  363. protected override void Run(_ sink) => sink.Run(this);
  364. internal sealed class _ : Sink<TSource, IList<TSource>>
  365. {
  366. private readonly object _gate = new object();
  367. public _(IObserver<IList<TSource>> observer)
  368. : base(observer)
  369. {
  370. }
  371. private List<TSource> _list;
  372. private IDisposable _periodicDisposable;
  373. public void Run(TimeHopping parent)
  374. {
  375. _list = new List<TSource>();
  376. Disposable.SetSingle(ref _periodicDisposable, parent._scheduler.SchedulePeriodic(this, parent._timeSpan, @this => @this.Tick()));
  377. Run(parent._source);
  378. }
  379. protected override void Dispose(bool disposing)
  380. {
  381. if (disposing)
  382. {
  383. Disposable.TryDispose(ref _periodicDisposable);
  384. }
  385. base.Dispose(disposing);
  386. }
  387. private void Tick()
  388. {
  389. lock (_gate)
  390. {
  391. ForwardOnNext(_list);
  392. _list = new List<TSource>();
  393. }
  394. }
  395. public override void OnNext(TSource value)
  396. {
  397. lock (_gate)
  398. {
  399. _list.Add(value);
  400. }
  401. }
  402. public override void OnError(Exception error)
  403. {
  404. lock (_gate)
  405. {
  406. _list.Clear();
  407. ForwardOnError(error);
  408. }
  409. }
  410. public override void OnCompleted()
  411. {
  412. lock (_gate)
  413. {
  414. ForwardOnNext(_list);
  415. ForwardOnCompleted();
  416. }
  417. }
  418. }
  419. }
  420. internal sealed class Ferry : Producer<IList<TSource>, Ferry._>
  421. {
  422. private readonly IObservable<TSource> _source;
  423. private readonly int _count;
  424. private readonly TimeSpan _timeSpan;
  425. private readonly IScheduler _scheduler;
  426. public Ferry(IObservable<TSource> source, TimeSpan timeSpan, int count, IScheduler scheduler)
  427. {
  428. _source = source;
  429. _timeSpan = timeSpan;
  430. _count = count;
  431. _scheduler = scheduler;
  432. }
  433. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  434. protected override void Run(_ sink) => sink.Run();
  435. internal sealed class _ : Sink<TSource, IList<TSource>>
  436. {
  437. private readonly Ferry _parent;
  438. private readonly object _gate = new object();
  439. private IDisposable _timerSerial;
  440. public _(Ferry parent, IObserver<IList<TSource>> observer)
  441. : base(observer)
  442. {
  443. _parent = parent;
  444. }
  445. private IList<TSource> _s;
  446. private int _n;
  447. private int _windowId;
  448. public void Run()
  449. {
  450. _s = new List<TSource>();
  451. _n = 0;
  452. _windowId = 0;
  453. CreateTimer(0);
  454. SetUpstream(_parent._source.SubscribeSafe(this));
  455. }
  456. protected override void Dispose(bool disposing)
  457. {
  458. if (disposing)
  459. {
  460. Disposable.TryDispose(ref _timerSerial);
  461. }
  462. base.Dispose(disposing);
  463. }
  464. private void CreateTimer(int id)
  465. {
  466. var m = new SingleAssignmentDisposable();
  467. Disposable.TrySetSerial(ref _timerSerial, m);
  468. m.Disposable = _parent._scheduler.ScheduleAction((@this: this, id), _parent._timeSpan, tuple => [email protected](tuple.id));
  469. }
  470. private void Tick(int id)
  471. {
  472. lock (_gate)
  473. {
  474. if (id != _windowId)
  475. {
  476. return;
  477. }
  478. _n = 0;
  479. var newId = ++_windowId;
  480. var res = _s;
  481. _s = new List<TSource>();
  482. ForwardOnNext(res);
  483. CreateTimer(newId);
  484. }
  485. }
  486. public override void OnNext(TSource value)
  487. {
  488. var newWindow = false;
  489. var newId = 0;
  490. lock (_gate)
  491. {
  492. _s.Add(value);
  493. _n++;
  494. if (_n == _parent._count)
  495. {
  496. newWindow = true;
  497. _n = 0;
  498. newId = ++_windowId;
  499. var res = _s;
  500. _s = new List<TSource>();
  501. ForwardOnNext(res);
  502. }
  503. if (newWindow)
  504. {
  505. CreateTimer(newId);
  506. }
  507. }
  508. }
  509. public override void OnError(Exception error)
  510. {
  511. lock (_gate)
  512. {
  513. _s.Clear();
  514. ForwardOnError(error);
  515. }
  516. }
  517. public override void OnCompleted()
  518. {
  519. lock (_gate)
  520. {
  521. ForwardOnNext(_s);
  522. ForwardOnCompleted();
  523. }
  524. }
  525. }
  526. }
  527. }
  528. internal static class Buffer<TSource, TBufferClosing>
  529. {
  530. internal sealed class Selector : Producer<IList<TSource>, Selector._>
  531. {
  532. private readonly IObservable<TSource> _source;
  533. private readonly Func<IObservable<TBufferClosing>> _bufferClosingSelector;
  534. public Selector(IObservable<TSource> source, Func<IObservable<TBufferClosing>> bufferClosingSelector)
  535. {
  536. _source = source;
  537. _bufferClosingSelector = bufferClosingSelector;
  538. }
  539. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  540. protected override void Run(_ sink) => sink.Run(_source);
  541. internal sealed class _ : Sink<TSource, IList<TSource>>
  542. {
  543. private readonly object _gate = new object();
  544. private readonly AsyncLock _bufferGate = new AsyncLock();
  545. private IDisposable _bufferClosingSerialDisposable;
  546. private readonly Func<IObservable<TBufferClosing>> _bufferClosingSelector;
  547. public _(Selector parent, IObserver<IList<TSource>> observer)
  548. : base(observer)
  549. {
  550. _bufferClosingSelector = parent._bufferClosingSelector;
  551. }
  552. private IList<TSource> _buffer;
  553. public override void Run(IObservable<TSource> source)
  554. {
  555. _buffer = new List<TSource>();
  556. base.Run(source);
  557. _bufferGate.Wait(this, @this => @this.CreateBufferClose());
  558. }
  559. protected override void Dispose(bool disposing)
  560. {
  561. if (disposing)
  562. {
  563. Disposable.TryDispose(ref _bufferClosingSerialDisposable);
  564. }
  565. base.Dispose(disposing);
  566. }
  567. private void CreateBufferClose()
  568. {
  569. IObservable<TBufferClosing> bufferClose;
  570. try
  571. {
  572. bufferClose = _bufferClosingSelector();
  573. }
  574. catch (Exception exception)
  575. {
  576. lock (_gate)
  577. {
  578. ForwardOnError(exception);
  579. }
  580. return;
  581. }
  582. var closingObserver = new BufferClosingObserver(this);
  583. Disposable.TrySetSerial(ref _bufferClosingSerialDisposable, closingObserver);
  584. closingObserver.SetResource(bufferClose.SubscribeSafe(closingObserver));
  585. }
  586. private void CloseBuffer(IDisposable closingSubscription)
  587. {
  588. closingSubscription.Dispose();
  589. lock (_gate)
  590. {
  591. var res = _buffer;
  592. _buffer = new List<TSource>();
  593. ForwardOnNext(res);
  594. }
  595. _bufferGate.Wait(this, @this => @this.CreateBufferClose());
  596. }
  597. private sealed class BufferClosingObserver : SafeObserver<TBufferClosing>
  598. {
  599. private readonly _ _parent;
  600. public BufferClosingObserver(_ parent)
  601. {
  602. _parent = parent;
  603. }
  604. public override void OnNext(TBufferClosing value)
  605. {
  606. _parent.CloseBuffer(this);
  607. }
  608. public override void OnError(Exception error)
  609. {
  610. _parent.OnError(error);
  611. }
  612. public override void OnCompleted()
  613. {
  614. _parent.CloseBuffer(this);
  615. }
  616. }
  617. public override void OnNext(TSource value)
  618. {
  619. lock (_gate)
  620. {
  621. _buffer.Add(value);
  622. }
  623. }
  624. public override void OnError(Exception error)
  625. {
  626. lock (_gate)
  627. {
  628. _buffer.Clear();
  629. ForwardOnError(error);
  630. }
  631. }
  632. public override void OnCompleted()
  633. {
  634. lock (_gate)
  635. {
  636. ForwardOnNext(_buffer);
  637. ForwardOnCompleted();
  638. }
  639. }
  640. }
  641. }
  642. internal sealed class Boundaries : Producer<IList<TSource>, Boundaries._>
  643. {
  644. private readonly IObservable<TSource> _source;
  645. private readonly IObservable<TBufferClosing> _bufferBoundaries;
  646. public Boundaries(IObservable<TSource> source, IObservable<TBufferClosing> bufferBoundaries)
  647. {
  648. _source = source;
  649. _bufferBoundaries = bufferBoundaries;
  650. }
  651. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
  652. protected override void Run(_ sink) => sink.Run(this);
  653. internal sealed class _ : Sink<TSource, IList<TSource>>
  654. {
  655. private readonly object _gate = new object();
  656. public _(IObserver<IList<TSource>> observer)
  657. : base(observer)
  658. {
  659. }
  660. private IList<TSource> _buffer;
  661. private IDisposable _boundariesDisposable;
  662. public void Run(Boundaries parent)
  663. {
  664. _buffer = new List<TSource>();
  665. Run(parent._source);
  666. Disposable.SetSingle(ref _boundariesDisposable, parent._bufferBoundaries.SubscribeSafe(new BufferClosingObserver(this)));
  667. }
  668. protected override void Dispose(bool disposing)
  669. {
  670. if (disposing)
  671. {
  672. Disposable.TryDispose(ref _boundariesDisposable);
  673. }
  674. base.Dispose(disposing);
  675. }
  676. private sealed class BufferClosingObserver : IObserver<TBufferClosing>
  677. {
  678. private readonly _ _parent;
  679. public BufferClosingObserver(_ parent)
  680. {
  681. _parent = parent;
  682. }
  683. public void OnNext(TBufferClosing value)
  684. {
  685. lock (_parent._gate)
  686. {
  687. var res = _parent._buffer;
  688. _parent._buffer = new List<TSource>();
  689. _parent.ForwardOnNext(res);
  690. }
  691. }
  692. public void OnError(Exception error)
  693. {
  694. _parent.OnError(error);
  695. }
  696. public void OnCompleted()
  697. {
  698. _parent.OnCompleted();
  699. }
  700. }
  701. public override void OnNext(TSource value)
  702. {
  703. lock (_gate)
  704. {
  705. _buffer.Add(value);
  706. }
  707. }
  708. public override void OnError(Exception error)
  709. {
  710. lock (_gate)
  711. {
  712. _buffer.Clear();
  713. ForwardOnError(error);
  714. }
  715. }
  716. public override void OnCompleted()
  717. {
  718. lock (_gate)
  719. {
  720. ForwardOnNext(_buffer);
  721. ForwardOnCompleted();
  722. }
  723. }
  724. }
  725. }
  726. }
  727. }