Buffer.cs 28 KB

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