using System;

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

		protected override Cast<TSource, TResult>._ CreateSink(IObserver<TResult> observer)
		{
			return new Cast<TSource, TResult>._(observer);
		}

		protected override void Run(Cast<TSource, TResult>._ sink)
		{
			sink.Run(this._source);
		}

		private readonly IObservable<TSource> _source;

		internal sealed class _ : Sink<TSource, TResult>
		{
			public _(IObserver<TResult> observer)
				: base(observer)
			{
			}

			public override void OnNext(TSource value)
			{
				TResult tresult;
				try
				{
					tresult = (TResult)((object)value);
				}
				catch (Exception ex)
				{
					base.ForwardOnError(ex);
					return;
				}
				base.ForwardOnNext(tresult);
			}
		}
	}
}
