using System;

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

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

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

		private readonly IObservable<long> _source;

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

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

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

			private long _sum;
		}
	}
}
