using System;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class SumInt32 : Producer<int, SumInt32._>
	{
		public SumInt32(IObservable<int> source)
		{
			this._source = source;
		}

		protected override SumInt32._ CreateSink(IObserver<int> observer)
		{
			return new SumInt32._(observer);
		}

		protected override void Run(SumInt32._ sink)
		{
			sink.Run(this._source);
		}

		private readonly IObservable<int> _source;

		internal sealed class _ : IdentitySink<int>
		{
			public _(IObserver<int> observer)
				: base(observer)
			{
			}

			public override void OnNext(int value)
			{
				checked
				{
					try
					{
						this._sum += value;
					}
					catch (Exception ex)
					{
						base.ForwardOnError(ex);
					}
				}
			}

			public override void OnCompleted()
			{
				base.ForwardOnNext(this._sum);
				base.ForwardOnCompleted();
			}

			private int _sum;
		}
	}
}
