Buffer.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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!); // NB: Counting logic with _index ensures non-null.
  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.Dispose(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, static 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. private List<TSource> _list = new List<TSource>();
  368. public _(IObserver<IList<TSource>> observer)
  369. : base(observer)
  370. {
  371. }
  372. private IDisposable? _periodicDisposable;
  373. public void Run(TimeHopping parent)
  374. {
  375. Disposable.SetSingle(ref _periodicDisposable, parent._scheduler.SchedulePeriodic(this, parent._timeSpan, static @this => @this.Tick()));
  376. Run(parent._source);
  377. }
  378. protected override void Dispose(bool disposing)
  379. {
  380. if (disposing)
  381. {
  382. Disposable.Dispose(ref _periodicDisposable);
  383. }
  384. base.Dispose(disposing);
  385. }
  386. private void Tick()
  387. {
  388. lock (_gate)
  389. {
  390. ForwardOnNext(_list);
  391. _list = new List<TSource>();
  392. }
  393. }
  394. public override void OnNext(TSource value)
  395. {
  396. lock (_gate)
  397. {
  398. _list.Add(value);
  399. }
  400. }
  401. public override void OnError(Exception error)
  402. {
  403. lock (_gate)
  404. {
  405. _list.Clear();
  406. ForwardOnError(error);
  407. }
  408. }
  409. public override void OnCompleted()
  410. {
  411. lock (_gate)
  412. {
  413. ForwardOnNext(_list);
  414. ForwardOnCompleted();
  415. }
  416. }
  417. }
  418. }
  419. internal sealed class Ferry : Producer<IList<TSource>, Ferry._>
  420. {
  421. private readonly IObservable<TSource> _source;
  422. private readonly int _count;
  423. private readonly TimeSpan _timeSpan;
  424. private readonly IScheduler _scheduler;
  425. public Ferry(IObservable<TSource> source, TimeSpan timeSpan, int count, IScheduler scheduler)
  426. {
  427. _source = source;
  428. _timeSpan = timeSpan;
  429. _count = count;
  430. _scheduler = scheduler;
  431. }
  432. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(this, observer);
  433. protected override void Run(_ sink) => sink.Run();
  434. internal sealed class _ : Sink<TSource, IList<TSource>>
  435. {
  436. private readonly Ferry _parent;
  437. private readonly object _gate = new object();
  438. private List<TSource> _s = new List<TSource>();
  439. public _(Ferry parent, IObserver<IList<TSource>> observer)
  440. : base(observer)
  441. {
  442. _parent = parent;
  443. }
  444. private IDisposable? _timerSerial;
  445. private int _n;
  446. private int _windowId;
  447. public void Run()
  448. {
  449. _n = 0;
  450. _windowId = 0;
  451. CreateTimer(0);
  452. SetUpstream(_parent._source.SubscribeSafe(this));
  453. }
  454. protected override void Dispose(bool disposing)
  455. {
  456. if (disposing)
  457. {
  458. Disposable.Dispose(ref _timerSerial);
  459. }
  460. base.Dispose(disposing);
  461. }
  462. private void CreateTimer(int id)
  463. {
  464. var m = new SingleAssignmentDisposable();
  465. Disposable.TrySetSerial(ref _timerSerial, m);
  466. m.Disposable = _parent._scheduler.ScheduleAction((@this: this, id), _parent._timeSpan, static tuple => [email protected](tuple.id));
  467. }
  468. private void Tick(int id)
  469. {
  470. lock (_gate)
  471. {
  472. if (id != _windowId)
  473. {
  474. return;
  475. }
  476. _n = 0;
  477. var 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 readonly Func<IObservable<TBufferClosing>> _bufferClosingSelector;
  544. private List<TSource> _buffer = new List<TSource>();
  545. private IDisposable? _bufferClosingSerialDisposable;
  546. public _(Selector parent, IObserver<IList<TSource>> observer)
  547. : base(observer)
  548. {
  549. _bufferClosingSelector = parent._bufferClosingSelector;
  550. }
  551. public override void Run(IObservable<TSource> source)
  552. {
  553. base.Run(source);
  554. _bufferGate.Wait(this, static @this => @this.CreateBufferClose());
  555. }
  556. protected override void Dispose(bool disposing)
  557. {
  558. if (disposing)
  559. {
  560. Disposable.Dispose(ref _bufferClosingSerialDisposable);
  561. }
  562. base.Dispose(disposing);
  563. }
  564. private void CreateBufferClose()
  565. {
  566. IObservable<TBufferClosing> bufferClose;
  567. try
  568. {
  569. bufferClose = _bufferClosingSelector();
  570. }
  571. catch (Exception exception)
  572. {
  573. lock (_gate)
  574. {
  575. ForwardOnError(exception);
  576. }
  577. return;
  578. }
  579. var closingObserver = new BufferClosingObserver(this);
  580. Disposable.TrySetSerial(ref _bufferClosingSerialDisposable, closingObserver);
  581. closingObserver.SetResource(bufferClose.SubscribeSafe(closingObserver));
  582. }
  583. private void CloseBuffer(IDisposable closingSubscription)
  584. {
  585. closingSubscription.Dispose();
  586. lock (_gate)
  587. {
  588. var res = _buffer;
  589. _buffer = new List<TSource>();
  590. ForwardOnNext(res);
  591. }
  592. _bufferGate.Wait(this, static @this => @this.CreateBufferClose());
  593. }
  594. private sealed class BufferClosingObserver : SafeObserver<TBufferClosing>
  595. {
  596. private readonly _ _parent;
  597. public BufferClosingObserver(_ parent)
  598. {
  599. _parent = parent;
  600. }
  601. public override void OnNext(TBufferClosing value)
  602. {
  603. _parent.CloseBuffer(this);
  604. }
  605. public override void OnError(Exception error)
  606. {
  607. _parent.OnError(error);
  608. }
  609. public override void OnCompleted()
  610. {
  611. _parent.CloseBuffer(this);
  612. }
  613. }
  614. public override void OnNext(TSource value)
  615. {
  616. lock (_gate)
  617. {
  618. _buffer.Add(value);
  619. }
  620. }
  621. public override void OnError(Exception error)
  622. {
  623. lock (_gate)
  624. {
  625. _buffer.Clear();
  626. ForwardOnError(error);
  627. }
  628. }
  629. public override void OnCompleted()
  630. {
  631. lock (_gate)
  632. {
  633. ForwardOnNext(_buffer);
  634. ForwardOnCompleted();
  635. }
  636. }
  637. }
  638. }
  639. internal sealed class Boundaries : Producer<IList<TSource>, Boundaries._>
  640. {
  641. private readonly IObservable<TSource> _source;
  642. private readonly IObservable<TBufferClosing> _bufferBoundaries;
  643. public Boundaries(IObservable<TSource> source, IObservable<TBufferClosing> bufferBoundaries)
  644. {
  645. _source = source;
  646. _bufferBoundaries = bufferBoundaries;
  647. }
  648. protected override _ CreateSink(IObserver<IList<TSource>> observer) => new _(observer);
  649. protected override void Run(_ sink) => sink.Run(this);
  650. internal sealed class _ : Sink<TSource, IList<TSource>>
  651. {
  652. private readonly object _gate = new object();
  653. private List<TSource> _buffer = new List<TSource>();
  654. private IDisposable? _boundariesDisposable;
  655. public _(IObserver<IList<TSource>> observer)
  656. : base(observer)
  657. {
  658. }
  659. public void Run(Boundaries parent)
  660. {
  661. Run(parent._source);
  662. Disposable.SetSingle(ref _boundariesDisposable, parent._bufferBoundaries.SubscribeSafe(new BufferClosingObserver(this)));
  663. }
  664. protected override void Dispose(bool disposing)
  665. {
  666. if (disposing)
  667. {
  668. Disposable.Dispose(ref _boundariesDisposable);
  669. }
  670. base.Dispose(disposing);
  671. }
  672. private sealed class BufferClosingObserver : IObserver<TBufferClosing>
  673. {
  674. private readonly _ _parent;
  675. public BufferClosingObserver(_ parent)
  676. {
  677. _parent = parent;
  678. }
  679. public void OnNext(TBufferClosing value)
  680. {
  681. lock (_parent._gate)
  682. {
  683. var res = _parent._buffer;
  684. _parent._buffer = new List<TSource>();
  685. _parent.ForwardOnNext(res);
  686. }
  687. }
  688. public void OnError(Exception error)
  689. {
  690. _parent.OnError(error);
  691. }
  692. public void OnCompleted()
  693. {
  694. _parent.OnCompleted();
  695. }
  696. }
  697. public override void OnNext(TSource value)
  698. {
  699. lock (_gate)
  700. {
  701. _buffer.Add(value);
  702. }
  703. }
  704. public override void OnError(Exception error)
  705. {
  706. lock (_gate)
  707. {
  708. _buffer.Clear();
  709. ForwardOnError(error);
  710. }
  711. }
  712. public override void OnCompleted()
  713. {
  714. lock (_gate)
  715. {
  716. ForwardOnNext(_buffer);
  717. ForwardOnCompleted();
  718. }
  719. }
  720. }
  721. }
  722. }
  723. }