Ejemplo n.º 1
0
        public void Seek(long position)
        {
            providers.Clear();

            SourceStream.Position = position;

            if (position > start && position < end)
            {
                providers.Enqueue(new OffsetSampleProvider(SourceStream.ToSampleProvider())
                {
                    TakeSamples = (end - (int)position) * 2
                });
            }
            else if (position < start)
            {
                providers.Enqueue(new OffsetSampleProvider(SourceStream.ToSampleProvider())
                {
                    TakeSamples = (start - (int)position) * 2
                });
            }
            else
            {
                providers.Enqueue(new OffsetSampleProvider(SourceStream.ToSampleProvider()));
            }

            currentProvider = providers.Dequeue();
        }
Ejemplo n.º 2
0
        protected override IEnumerable <SevenZipVolume> LoadVolumes(SourceStream srcStream)
        {
            base.SrcStream.LoadAllParts(); //request all streams
            int idx = 0;

            return(new SevenZipVolume(srcStream, ReaderOptions, idx++).AsEnumerable()); //simple single volume or split, multivolume not supported
        }
        //Utilities
        public void TryMatch(string input)
        {
            SourceStream source = new SourceStream(_language.ScannerData, 0);

            source.SetText(input, 0, false);
            _token = _terminal.TryMatch(_context, source);
        }
Ejemplo n.º 4
0
        public override DataBlock Next()
        {
            lock (SourceStream)
            {
                var buf       = new byte[Constants.HeaderSize];
                var bytesRead = SourceStream.Read(buf, 0, buf.Length);
                if (bytesRead == 0)
                {
                    return(new DataBlock(PartNumber++, new byte[0]));
                }
                if (buf[0] != Constants.HeaderByte1 || buf[1] != Constants.HeaderByte2 || buf[2] != Constants.CompressionMethodDeflate)
                {
                    throw new InvalidDataException("Archive is not valid or it was not created by this program.");
                }

                var blockSize = BitConverter.ToInt32(buf, sizeof(int));
                buf = new byte[blockSize];

                SourceStream.Position -= Constants.HeaderSize;
                var offset = 0;
                do
                {
                    bytesRead = SourceStream.Read(buf, offset, buf.Length - offset);
                    offset   += bytesRead;
                }while (offset != blockSize && bytesRead != 0);

                return(new DataBlock(PartNumber++, buf));
            }
        }
Ejemplo n.º 5
0
        public void Dispose()
        {
            if (SourceReader != null)
            {
                SourceReader.Close();
                SourceReader.Dispose();
            }
            if (TargetWriter != null)
            {
                TargetWriter.Flush();
                TargetWriter.Close();
                TargetWriter.Dispose();
            }

            if (SourceStream != null)
            {
                SourceStream.Close();
                SourceStream.Dispose();
            }
            if (TargetStream != null)
            {
                TargetStream.Close();
                TargetStream.Dispose();
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     Write the JSON message to the output stream.
        /// </summary>
        /// <param name="message">
        ///     The message to write.
        /// </param>
        private void WriteJsonMessage(string message)
        {
            // Build the header message.
            var header     = string.Format("Content-Length: {0}{1}{2}{1}{2}", message.Length, (char)0x0D, (char)0x0A);
            var headerData = Encoding.UTF8.GetBytes(header);

            SourceStream.Write(headerData, 0, headerData.Length);

            // Write the body data.
            var bodyData = Encoding.UTF8.GetBytes(message);

            SourceStream.Write(bodyData, 0, bodyData.Length);

            SourceStream.Flush();

            // debug the new message.
            if (DebugStream != null)
            {
                lock (DebugStream)
                {
                    DebugStream.WriteLine("*****************************************");
                    DebugStream.WriteLine(" Direction: {0}", Direction);
                    DebugStream.WriteLine(" Timestamp: {0}", DateTime.Now);
                    DebugStream.WriteLine("*****************************************");
                    DebugStream.WriteLine(message);
                    DebugStream.WriteLine("*****************************************");
                    DebugStream.Flush();
                }
            }
        }
Ejemplo n.º 7
0
        public override async Task ExecuteResultAsync(ActionContext context)
        {
            var response = context.HttpContext.Response;

            response.ContentType = ContentType;
            var targetStream = response.Body;

            if (CopyStream is not null)
            {
                await Task.Factory.StartNew(() =>
                {
                    CopyStream(targetStream);
                });
            }
            else if (Content is not null)
            {
                await targetStream.WriteAsync(Content, 0, Content.Length);
            }
            else
            {
                using (SourceStream)
                {
                    if (SourceStream.CanSeek)
                    {
                        SourceStream.Seek(0, SeekOrigin.Begin);
                    }
                    await SourceStream.CopyToAsync(targetStream);
                }
            }
        }
Ejemplo n.º 8
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            int  read         = SourceStream.Read(buffer, offset, count);
            bool applyEffects = false;

            if (Effects.Count % WaveFormat.Channels == 0)
            {
                applyEffects = true;
            }

            for (int i = 0; i < read / 4; i++)
            {
                float sample = BitConverter.ToSingle(buffer, i * 4);

                if (applyEffects == true)
                {
                    for (int j = channel; j < Effects.Count; j += WaveFormat.Channels)
                    {
                        sample = Effects[j].ApplyEffect(sample);
                    }
                    channel = (channel + 1) % WaveFormat.Channels;
                }

                byte[] bytes = BitConverter.GetBytes(sample);
                bytes.CopyTo(buffer, i * 4);
            }

            return(read);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Creates a new <see cref="StreamCommand{T}"/>.
 /// </summary>
 /// <param name="info">A <see cref="CommandInfo"/> object which contains documentation and identifying info for the action this <see cref="ICommand{T}"/> provides.</param>
 /// <param name="enableStream">An <see cref="IStream{T}"/> that emits <see cref="bool"/> values indicating whether this <see cref="StreamCommand{T}"/> should be enabled or not.</param>
 public StreamCommand(CommandInfo info, IStream <bool> enableStream = null)
 {
     Info          = info;
     TriggerStream = new SourceStream <bool>();
     ValueEmitted  = TriggerStream.ValueEmitted;
     EnabledStream = enableStream ?? true.AsStream();
 }
Ejemplo n.º 10
0
        protected override IEnumerable <GZipVolume> LoadVolumes(SourceStream srcStream)
        {
            srcStream.LoadAllParts();
            int idx = 0;

            return(srcStream.Streams.Select(a => new GZipVolume(a, ReaderOptions, idx++)));
        }
Ejemplo n.º 11
0
        protected void Redirect(string FirstBlockInput, params string[] ToInput)
        {
            const string binaryName    = "TestBinary";
            const string binaryNameExe = binaryName + ".exe";
            string       temp          = Path.GetTempPath();
            string       fullName      = Path.Combine(temp, binaryNameExe);
            string       input         = "program " + binaryName + ";" + FirstBlockInput;

            using (StringReader stringReader = new StringReader(input))
            {
                SourceStream ss = new SourceStream(stringReader);
                Compiler.Compile(ss, temp);
            }
            proc = new Process();
            proc.StartInfo.CreateNoWindow         = true;
            proc.StartInfo.WorkingDirectory       = temp;
            proc.StartInfo.FileName               = fullName;
            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardInput  = true;

            proc.Start();

            foreach (string toInput in ToInput)
            {
                proc.StandardInput.WriteLine(toInput);
            }

            proc.WaitForExit(7500);
        }
Ejemplo n.º 12
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            int bytesRead = SourceStream.Read(buffer, offset, count);

            ProcessData(buffer, offset, bytesRead);
            return(bytesRead);
        }
Ejemplo n.º 13
0
        void InvokeWriter()
        {
            bool writerWasInvoked = false;

            try
            {
                SourceStream srcStream = new SourceStream(this);
                if (onWriterInvokeCompleted == null)
                {
                    onWriterInvokeCompleted = new AsyncCallback(OnWriterInvokeCompleted);
                }
                IAsyncResult invokeResult = this.writer.BeginInvoke(srcStream,
                                                                    onWriterInvokeCompleted, srcStream);
                if (invokeResult.CompletedSynchronously)
                {
                    this.writer.EndInvoke(invokeResult);
                    CompleteWriterInvocation(srcStream);
                }

                writerWasInvoked = true;
            }
            finally
            {
                // If something went wrong, let's reset the state :
                if (!writerWasInvoked)
                {
                    this.wasWriterInvoked = false;
                }
            }
        }
Ejemplo n.º 14
0
        protected override IEnumerable <ZipVolume> LoadVolumes(SourceStream srcStream)
        {
            base.SrcStream.LoadAllParts(); //request all streams
            base.SrcStream.Position = 0;

            List <Stream> streams = base.SrcStream.Streams.ToList();

            if (streams.Count > 1)        //test part 2 - true = multipart not split
            {
                streams[1].Position += 4; //skip the POST_DATA_DESCRIPTOR to prevent an exception
                bool isZip = IsZipFile(streams[1], ReaderOptions.Password);
                streams[1].Position -= 4;
                if (isZip)
                {
                    base.SrcStream.IsVolumes = true;

                    var tmp = streams[0]; //arcs as zip, z01 ... swap the zip the end
                    streams.RemoveAt(0);
                    streams.Add(tmp);

                    //streams[0].Position = 4; //skip the POST_DATA_DESCRIPTOR to prevent an exception
                    return(streams.Select(a => new ZipVolume(a, ReaderOptions)));
                }
            }

            //split mode or single file
            return(new ZipVolume(base.SrcStream, ReaderOptions).AsEnumerable());
        }
Ejemplo n.º 15
0
            public int Read(float[] buffer, int offset, int count)
            {
                #region sample setup
                int read = SourceStream.Read(buffer, offset, count);

                for (int i = 0; i < read; i++)
                {
                    float sample = buffer[i];

                    #endregion

                    #region FX processing


                    samples.Enqueue(sample);
                    sample = sample + EchoFactor * samples.Dequeue();

                    //clip range
                    sample = Math.Min(1f, Math.Max(-1f, sample));

                    #endregion

                    #region sample copy and exit
                    buffer[i] = sample;
                }

                return(read);

                #endregion
            }
        public T DeserializeFromFile(string FileName, BasicFileInformation FileInfo, ObjectSerializer <T> .SerializeType Type, bool isZip)
        {
            T          ret = default(T);
            FileStream fs  = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

            fs.Seek(BasicInformationSize(FileInfo), SeekOrigin.Begin);
            Stream SourceStream;

            if (FileInfo.SavePassword.Length > 0)
            {
                CryptoStream cs = DesCooler.CreateDecryptStream(FileInfo.SavePassword, fs);
                if (isZip)
                {
                    SourceStream = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(cs);
                }
                else
                {
                    SourceStream = cs;
                }
            }
            else
            {
                if (isZip)
                {
                    SourceStream = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(fs);
                }
                else
                {
                    SourceStream = fs;
                }
            }
            try
            {
                switch (Type)
                {
                case ObjectSerializer <T> .SerializeType.JSON: ret = Deserialize_JSON(SourceStream); break;

                case ObjectSerializer <T> .SerializeType.Binary: ret = Deserialize_Binary(SourceStream); break;
                }
            }
            catch (Exception e) { fs.Close(); throw e; return(ret); }
            try
            {
                SourceStream.Close();
            }
            catch {; }
            fs.Close();
            if (ret != null)
            {
                BasicFileInformation bfi = GetBasicFileInformation(ret);
                if (bfi != null)
                {
                    bfi.VersionString   = FileInfo.VersionString;
                    bfi.IntroduceText   = FileInfo.IntroduceText;
                    bfi.ProjectFilePath = (new System.IO.FileInfo(FileName)).FullName;
                }
            }
            return(ret);
        }
Ejemplo n.º 17
0
 internal AbstractArchive(ArchiveType type, SourceStream srcStream)
 {
     Type          = type;
     ReaderOptions = srcStream.ReaderOptions;
     SrcStream     = srcStream;
     lazyVolumes   = new LazyReadOnlyCollection <TVolume>(LoadVolumes(SrcStream));
     lazyEntries   = new LazyReadOnlyCollection <TEntry>(LoadEntries(Volumes));
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Dispose - by default (IgnoreDispose = true) will do nothing,
 /// leaving the underlying stream undisposed
 /// </summary>
 protected override void Dispose(bool disposing)
 {
     if (!IgnoreDispose)
     {
         SourceStream.Dispose();
         SourceStream = null;
     }
 }
Ejemplo n.º 19
0
 private void Parse(Grammar grammar, string script, bool expectError) {
   var compiler = new Compiler(grammar);
   var context = new CompilerContext(compiler);
   var source = new SourceStream(script, "source");
   AstNode root = compiler.Parse(context, source);
   compiler.AnalyzeCode(root, context);
   if (!expectError && context.Errors.Count > 0)
     Assert.Fail("Unexpected source error(s) found: " + context.Errors[0].Message);
 }
Ejemplo n.º 20
0
        protected override Block ReadBlock(int index, [NotNull] PipelineInfo pipelineInfo)
        {
            var uncompressedStream = MemoryStreamManager.GetStream("Uncompressed");

            SourceStream.CopyBlockTo(uncompressedStream, pipelineInfo.BlockSize);
            uncompressedStream.Position = 0;

            return(new Block(index, uncompressedStream));
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Creates a new <see cref="Core"/>.
 /// </summary>
 public Core(RuntimeConfiguration config, IEnumerable <ISignal> signals, ICommandProvider commandProvider)
 {
     Stack           = new Stack <string>();
     chunks          = new List <MemoryChunk>();
     Signals         = signals.ToDictionary(s => s.Signal);
     ExecutionStream = new SourceStream <uint>();
     ExecutionStream.BindResult(Execute);
     CommandProvider = commandProvider;
     Configuration   = config;
 }
Ejemplo n.º 22
0
        public int Read(int sectorIndex, byte[] buffer, int position, int offset, int count)
        {
            var idIndex        = IdIndexList[sectorIndex];
            var sectorPosition = SectorSize + idIndex * SectorSize;

            var streamPosition = sectorPosition + position;

            SourceStream.Seek(streamPosition, SeekOrigin.Begin);
            return(SourceStream.Read(buffer, offset, count));
        }
Ejemplo n.º 23
0
 public override Task <bool> StaunchFlow()
 {
     if (Socket.Connected)
     {
         Socket.Disconnect(true);
         SourceStream.Dispose();
         SourceStream = null;
     }
     return(base.StaunchFlow());
 }
        static SourceStream ForFileStream()
        {
            //定义一个文件流,并将文件内容写入该流
            string fName = "text.txt";
            //创建文件流,准备输入数据
            FileStream   fStream   = new FileStream(fName, FileMode.Open);
            SourceStream srcStream = new SourceStream(fStream);

            return(srcStream);
        }
        /// <summary>
        /// Cleans up the underlying stream.
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                SourceStream.Dispose();
                SourceStream = null;
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Creates a new <see cref="NavigationHistory"/> history.
        /// </summary>
        public NavigationHistory(Func <INavigationLayer> createLayer)
        {
            requestStream = new SourceStream <NavigationRequest>();
            RequestStream = requestStream.UniqueEq();

            layers      = new List <INavigationLayer>();
            CreateLayer = createLayer;

            Clear();
        }
Ejemplo n.º 27
0
        public override int ReadByte()
        {
            var b = SourceStream.ReadByte();

            if (b > -1)
            {
                outStream.WriteByte((byte)b);
            }

            return(b);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Writes 4 floating point bytes at a time, inputting from <see cref="AbstractPcmConversionStream.BytesPerSample"/>
        /// bytes per PCM sample write.
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        protected override void InternalWrite(byte[] buffer, int offset, int count)
        {
            var wrote = 0;

            while (wrote < count)
            {
                PCMToFloat(buffer, offset + wrote, tempBuffer, 0);
                SourceStream.Write(tempBuffer, 0, sizeof(float));
                wrote += BytesPerSample;
            }
        }
        //定义一个内存流,并初始化内容
        static SourceStream ForMemoryStream()
        {
            string       aString = "I am a good student,you are not a good student!";
            UTF8Encoding ue      = new UTF8Encoding();

            byte[] bytes = ue.GetBytes(aString);
            //创建内存流MemoryStream存储数据
            MemoryStream memStream = new MemoryStream(bytes);
            SourceStream srcStream = new SourceStream(memStream);

            return(srcStream);
        }
Ejemplo n.º 30
0
 public override void Close()
 {
     if (_sourceStream != null)
     {
         Flush();
         _stream.Close();
         _stream = null;
         SourceStream.Close();
         _sourceStream = null;
     }
     base.Close();
 }
Ejemplo n.º 31
0
 private void Evaluate(Grammar grammar, string script, bool expectError, object result) {
   var compiler = new Compiler(grammar);
   var context = new CompilerContext(compiler);
   var source = new SourceStream(script, "source"); 
   AstNode root = compiler.Parse(context, source);
   compiler.AnalyzeCode(root, context); 
   if (!expectError && context.Errors.Count > 0)
     Assert.Fail("Unexpected source error(s) found: " + context.Errors[0].Message);
   var evalContext = new EvaluationContext(context.Runtime, root);
   root.Evaluate(evalContext);
   Assert.AreEqual(evalContext.CurrentResult, result, "Evaluation result is null, expected " + result);
 }
Ejemplo n.º 32
0
        void SourceQueue_Process(object sender, ProcessQueueEventArgs <Tuple <byte[], int, int> > e)
        {
            var ar = SourceStream.BeginWrite(e.Item.Item1, e.Item.Item2, e.Item.Item3, null, null);

            using (ar.AsyncWaitHandle)
            {
                if (ar.AsyncWaitHandle.WaitOne(-1))
                {
                    SourceStream.EndWrite(ar);
                }
            }
        }
Ejemplo n.º 33
0
        void CompleteWriterInvocation(SourceStream srcStream)
        {
            srcStream.Close();
            lock (this.thisLock)
            {
                this.noMoreData = true;
                while (this.readQueue.HasPendingRequests)
                {
                    if (this.writerException != null)
                    {
                        this.readQueue.Dequeue().CompleteWithException(srcStream.Owner.writerException);
                        this.writerException = null;
                    }
                    else
                    {
                        this.readQueue.Dequeue().Complete(0);
                    }
                }
            }

        }
Ejemplo n.º 34
0
        void InvokeWriter()
        {
            bool writerWasInvoked = false;
            try
            {
                SourceStream srcStream = new SourceStream(this);
                if (onWriterInvokeCompleted == null)
                {
                    onWriterInvokeCompleted = new AsyncCallback(OnWriterInvokeCompleted);
                }
                IAsyncResult invokeResult = this.writer.BeginInvoke(srcStream,
                    onWriterInvokeCompleted, srcStream);
                if (invokeResult.CompletedSynchronously)
                {
                    this.writer.EndInvoke(invokeResult);
                    CompleteWriterInvocation(srcStream);
                }

                writerWasInvoked = true;
            }
            finally
            {
                // If something went wrong, let's reset the state :
                if (!writerWasInvoked)
                    this.wasWriterInvoked = false;
            }
        }