Buffer.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  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 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. var s = _q.Dequeue();
  305. ForwardOnNext(s);
  306. }
  307. if (isShift)
  308. {
  309. CreateWindow();
  310. }
  311. }
  312. CreateTimer();
  313. }
  314. public override void OnNext(TSource value)
  315. {
  316. lock (_gate)
  317. {
  318. foreach (var s in _q)
  319. {
  320. s.Add(value);
  321. }
  322. }
  323. }
  324. public override void OnError(Exception error)
  325. {
  326. lock (_gate)
  327. {
  328. while (_q.Count > 0)
  329. {
  330. _q.Dequeue().Clear();
  331. }
  332. ForwardOnError(error);
  333. }
  334. }
  335. public override void OnCompleted()
  336. {
  337. lock (_gate)
  338. {
  339. while (_q.Count > 0)
  340. {
  341. ForwardOnNext(_q.Dequeue());
  342. }
  343. ForwardOnCompleted();
  344. }
  345. }
  346. }
  347. }
  348. internal sealed class TimeHopping : Producer<IList<TSource>, TimeHopping._>
  349. {
  350. private readonly IObservable<TSource> _source;
  351. private readonly TimeSpan _timeSpan;
  352. private readonly IScheduler _scheduler;
  353. public TimeHopping(IObservable<TSource> source, TimeSpan timeSpan, IScheduler scheduler)
  354. {
  355. _source = source;
  356. _timeSpan = timeSpan;
  357. _scheduler = scheduler;
  358. }
  359. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
  360. protected override void Run(_ sink) => sink.Run(this);
  361. internal sealed class _ : Sink<TSource, IList<TSource>>
  362. {
  363. private readonly object _gate = new object();
  364. public _(IObserver<IList<TSource>> observer)
  365. : base(observer)
  366. {
  367. }
  368. private List<TSource> _list;
  369. private IDisposable _periodicDisposable;
  370. public void Run(TimeHopping parent)
  371. {
  372. _list = new List<TSource>();
  373. Disposable.SetSingle(ref _periodicDisposable, parent._scheduler.SchedulePeriodic(this, parent._timeSpan, @this => @this.Tick()));
  374. Run(parent._source);
  375. }
  376. protected override void Dispose(bool disposing)
  377. {
  378. if (disposing)
  379. {
  380. Disposable.TryDispose(ref _periodicDisposable);
  381. }
  382. base.Dispose(disposing);
  383. }
  384. private void Tick()
  385. {
  386. lock (_gate)
  387. {
  388. ForwardOnNext(_list);
  389. _list = new List<TSource>();
  390. }
  391. }
  392. public override void OnNext(TSource value)
  393. {
  394. lock (_gate)
  395. {
  396. _list.Add(value);
  397. }
  398. }
  399. public override void OnError(Exception error)
  400. {
  401. lock (_gate)
  402. {
  403. _list.Clear();
  404. ForwardOnError(error);
  405. }
  406. }
  407. public override void OnCompleted()
  408. {
  409. lock (_gate)
  410. {
  411. ForwardOnNext(_list);
  412. ForwardOnCompleted();
  413. }
  414. }
  415. }
  416. }
  417. internal sealed class Ferry : Producer<IList<TSource>, Ferry._>
  418. {
  419. private readonly IObservable<TSource> _source;
  420. private readonly int _count;
  421. private readonly TimeSpan _timeSpan;
  422. private readonly IScheduler _scheduler;
  423. public Ferry(IObservable<TSource> source, TimeSpan timeSpan, int count, IScheduler scheduler)
  424. {
  425. _source = source;
  426. _timeSpan = timeSpan;
  427. _count = count;
  428. _scheduler = scheduler;
  429. }
  430. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  431. protected override void Run(_ sink) => sink.Run();
  432. internal sealed class _ : Sink<TSource, IList<TSource>>
  433. {
  434. private readonly Ferry _parent;
  435. private readonly object _gate = new object();
  436. private IDisposable _timerSerial;
  437. public _(Ferry parent, IObserver<IList<TSource>> observer)
  438. : base(observer)
  439. {
  440. _parent = parent;
  441. }
  442. private IList<TSource> _s;
  443. private int _n;
  444. private int _windowId;
  445. public void Run()
  446. {
  447. _s = new List<TSource>();
  448. _n = 0;
  449. _windowId = 0;
  450. CreateTimer(0);
  451. SetUpstream(_parent._source.SubscribeSafe(this));
  452. }
  453. protected override void Dispose(bool disposing)
  454. {
  455. if (disposing)
  456. {
  457. Disposable.TryDispose(ref _timerSerial);
  458. }
  459. base.Dispose(disposing);
  460. }
  461. private void CreateTimer(int id)
  462. {
  463. var m = new SingleAssignmentDisposable();
  464. Disposable.TrySetSerial(ref _timerSerial, m);
  465. m.Disposable = _parent._scheduler.ScheduleAction((@this: this, id), _parent._timeSpan, tuple => [email protected](tuple.id));
  466. }
  467. private void Tick(int id)
  468. {
  469. var newId = 0;
  470. lock (_gate)
  471. {
  472. if (id != _windowId)
  473. {
  474. return;
  475. }
  476. _n = 0;
  477. newId = ++_windowId;
  478. var res = _s;
  479. _s = new List<TSource>();
  480. ForwardOnNext(res);
  481. CreateTimer(newId);
  482. }
  483. }
  484. public override void OnNext(TSource value)
  485. {
  486. var newWindow = false;
  487. var newId = 0;
  488. lock (_gate)
  489. {
  490. _s.Add(value);
  491. _n++;
  492. if (_n == _parent._count)
  493. {
  494. newWindow = true;
  495. _n = 0;
  496. newId = ++_windowId;
  497. var res = _s;
  498. _s = new List<TSource>();
  499. ForwardOnNext(res);
  500. }
  501. if (newWindow)
  502. {
  503. CreateTimer(newId);
  504. }
  505. }
  506. }
  507. public override void OnError(Exception error)
  508. {
  509. lock (_gate)
  510. {
  511. _s.Clear();
  512. ForwardOnError(error);
  513. }
  514. }
  515. public override void OnCompleted()
  516. {
  517. lock (_gate)
  518. {
  519. ForwardOnNext(_s);
  520. ForwardOnCompleted();
  521. }
  522. }
  523. }
  524. }
  525. }
  526. internal static class Buffer<TSource, TBufferClosing>
  527. {
  528. internal sealed class Selector : Producer<IList<TSource>, Selector._>
  529. {
  530. private readonly IObservable<TSource> _source;
  531. private readonly Func<IObservable<TBufferClosing>> _bufferClosingSelector;
  532. public Selector(IObservable<TSource> source, Func<IObservable<TBufferClosing>> bufferClosingSelector)
  533. {
  534. _source = source;
  535. _bufferClosingSelector = bufferClosingSelector;
  536. }
  537. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  538. protected override void Run(_ sink) => sink.Run(_source);
  539. internal sealed class _ : Sink<TSource, IList<TSource>>
  540. {
  541. private readonly object _gate = new object();
  542. private readonly AsyncLock _bufferGate = new AsyncLock();
  543. private IDisposable _bufferClosingSerialDisposable;
  544. private readonly Func<IObservable<TBufferClosing>> _bufferClosingSelector;
  545. public _(Selector parent, IObserver<IList<TSource>> observer)
  546. : base(observer)
  547. {
  548. _bufferClosingSelector = parent._bufferClosingSelector;
  549. }
  550. private IList<TSource> _buffer;
  551. public override void Run(IObservable<TSource> source)
  552. {
  553. _buffer = new List<TSource>();
  554. base.Run(source);
  555. _bufferGate.Wait(this, @this => @this.CreateBufferClose());
  556. }
  557. protected override void Dispose(bool disposing)
  558. {
  559. if (disposing)
  560. {
  561. Disposable.TryDispose(ref _bufferClosingSerialDisposable);
  562. }
  563. base.Dispose(disposing);
  564. }
  565. private void CreateBufferClose()
  566. {
  567. var bufferClose = default(IObservable<TBufferClosing>);
  568. try
  569. {
  570. bufferClose = _bufferClosingSelector();
  571. }
  572. catch (Exception exception)
  573. {
  574. lock (_gate)
  575. {
  576. ForwardOnError(exception);
  577. }
  578. return;
  579. }
  580. var closingObserver = new BufferClosingObserver(this);
  581. Disposable.TrySetSerial(ref _bufferClosingSerialDisposable, closingObserver);
  582. closingObserver.SetResource(bufferClose.SubscribeSafe(closingObserver));
  583. }
  584. private void CloseBuffer(IDisposable closingSubscription)
  585. {
  586. closingSubscription.Dispose();
  587. lock (_gate)
  588. {
  589. var res = _buffer;
  590. _buffer = new List<TSource>();
  591. ForwardOnNext(res);
  592. }
  593. _bufferGate.Wait(this, @this => @this.CreateBufferClose());
  594. }
  595. private sealed class BufferClosingObserver : SafeObserver<TBufferClosing>
  596. {
  597. private readonly _ _parent;
  598. public BufferClosingObserver(_ parent)
  599. {
  600. _parent = parent;
  601. }
  602. public override void OnNext(TBufferClosing value)
  603. {
  604. _parent.CloseBuffer(this);
  605. }
  606. public override void OnError(Exception error)
  607. {
  608. _parent.OnError(error);
  609. }
  610. public override void OnCompleted()
  611. {
  612. _parent.CloseBuffer(this);
  613. }
  614. }
  615. public override void OnNext(TSource value)
  616. {
  617. lock (_gate)
  618. {
  619. _buffer.Add(value);
  620. }
  621. }
  622. public override void OnError(Exception error)
  623. {
  624. lock (_gate)
  625. {
  626. _buffer.Clear();
  627. ForwardOnError(error);
  628. }
  629. }
  630. public override void OnCompleted()
  631. {
  632. lock (_gate)
  633. {
  634. ForwardOnNext(_buffer);
  635. ForwardOnCompleted();
  636. }
  637. }
  638. }
  639. }
  640. internal sealed class Boundaries : Producer<IList<TSource>, Boundaries._>
  641. {
  642. private readonly IObservable<TSource> _source;
  643. private readonly IObservable<TBufferClosing> _bufferBoundaries;
  644. public Boundaries(IObservable<TSource> source, IObservable<TBufferClosing> bufferBoundaries)
  645. {
  646. _source = source;
  647. _bufferBoundaries = bufferBoundaries;
  648. }
  649. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
  650. protected override void Run(_ sink) => sink.Run(this);
  651. internal sealed class _ : Sink<TSource, IList<TSource>>
  652. {
  653. private readonly object _gate = new object();
  654. public _(IObserver<IList<TSource>> observer)
  655. : base(observer)
  656. {
  657. }
  658. private IList<TSource> _buffer;
  659. private IDisposable _boundariesDisposable;
  660. public void Run(Boundaries parent)
  661. {
  662. _buffer = new List<TSource>();
  663. Run(parent._source);
  664. Disposable.SetSingle(ref _boundariesDisposable, parent._bufferBoundaries.SubscribeSafe(new BufferClosingObserver(this)));
  665. }
  666. protected override void Dispose(bool disposing)
  667. {
  668. if (disposing)
  669. {
  670. Disposable.TryDispose(ref _boundariesDisposable);
  671. }
  672. base.Dispose(disposing);
  673. }
  674. private sealed class BufferClosingObserver : IObserver<TBufferClosing>
  675. {
  676. private readonly _ _parent;
  677. public BufferClosingObserver(_ parent)
  678. {
  679. _parent = parent;
  680. }
  681. public void OnNext(TBufferClosing value)
  682. {
  683. lock (_parent._gate)
  684. {
  685. var res = _parent._buffer;
  686. _parent._buffer = new List<TSource>();
  687. _parent.ForwardOnNext(res);
  688. }
  689. }
  690. public void OnError(Exception error)
  691. {
  692. _parent.OnError(error);
  693. }
  694. public void OnCompleted()
  695. {
  696. _parent.OnCompleted();
  697. }
  698. }
  699. public override void OnNext(TSource value)
  700. {
  701. lock (_gate)
  702. {
  703. _buffer.Add(value);
  704. }
  705. }
  706. public override void OnError(Exception error)
  707. {
  708. lock (_gate)
  709. {
  710. _buffer.Clear();
  711. ForwardOnError(error);
  712. }
  713. }
  714. public override void OnCompleted()
  715. {
  716. lock (_gate)
  717. {
  718. ForwardOnNext(_buffer);
  719. ForwardOnCompleted();
  720. }
  721. }
  722. }
  723. }
  724. }
  725. }