static void Main(string[] args) { if (args.Length != 1) { return; } double phaseShift = double.Parse(args[0], CultureInfo.InvariantCulture); int width = 4096; int height = 1024; double percentNoise = 0; int fringeCount = 10; double minIntensity = 35; InterferogramInfo interferogramInfo = new InterferogramInfo(width, height, percentNoise, minIntensity); LinearFringeInterferogramCreator interferogramCreator = new LinearFringeInterferogramCreator(interferogramInfo, fringeCount); RealMatrix interferogramMatrix = interferogramCreator.CreateInterferogram(phaseShift); WriteableBitmap writeableBitmap = WriteableBitmapCreator.CreateGrayScaleWriteableBitmapFromMatrix(interferogramMatrix, OS.IntegerSystemDpiX, OS.IntegerSystemDpiY); MemoryWriter.Write <WriteableBitmap>(writeableBitmap, new WriteableBitmapSerialization()); SynchronizationManager.SetSignal(HoloCommon.Synchronization.Events.Image.IMAGE_CREATED); }
public static void write(int addr, int Length, int[] buffer, int offset) { Length = System.Math.Min(Length, buffer.Length - offset); if (log.TraceEnabled) { log.trace(string.Format("write addr=0x{0:X8}, Length=0x{1:X}", addr, Length)); } // Optimize the most common case if (RuntimeContext.hasMemoryInt()) { int length4 = Length >> 2; int addrOffset = addr >> 2; int[] memoryInt = RuntimeContext.MemoryInt; for (int i = 0, j = offset; i < length4; i++) { int value = buffer[j++] & 0xFF; value += (buffer[j++] & 0xFF) << 8; value += (buffer[j++] & 0xFF) << 16; value += buffer[j++] << 24; memoryInt[addrOffset++] = value; } } else { IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(addr, Length, 1); for (int i = 0, j = offset; i < Length; i++) { memoryWriter.writeNext(buffer[j++] & 0xFF); } memoryWriter.flush(); } }
public unsafe void Assemble(byte *byteptr_t, MemoryWriter mw) { mw.WriteNullTerminated(this._collection_name); mw.WriteNullTerminated(this._shop_filename); mw.WriteNullTerminated(this._shop_trigger); for (int a1 = 0; a1 < this._collection_name.Length; ++a1) { *(byteptr_t + a1) = (byte)this._collection_name[a1]; } if (this._intro_movie != BaseArguments.NULL) { mw.WriteNullTerminated(this.IntroMovie); for (int a1 = 0; a1 < this.IntroMovie.Length; ++a1) { *(byteptr_t + 0x20 + a1) = (byte)this.IntroMovie[a1]; } } *(uint *)(byteptr_t + 0x38) = this.BinKey; *(uint *)(byteptr_t + 0x3C) = Bin.SmartHash(this._shop_trigger); for (int a1 = 0; a1 < this._shop_filename.Length; ++a1) { *(byteptr_t + 0x40 + a1) = (byte)this._shop_filename[a1]; } *(byteptr_t + 0x50) = (byte)this.ShopType; *(byteptr_t + 0x51) = (this.InitiallyHidden == eBoolean.True) ? (byte)1 : (byte)0; *(uint *)(byteptr_t + 0x74) = Bin.SmartHash(this._event_to_complete); *(byteptr_t + 0x9C) = (byte)this.RequiresEventCompleted; *(byteptr_t + 0x9D) = this.BelongsToStage; }
/// <summary> /// Encodes the specified image data to png. /// </summary> /// <param name="pixels"> /// The pixel data (bottom line first). /// </param> /// <param name="dpi"> /// The image resolution in dots per inch. /// </param> /// <returns> /// The png image data. /// </returns> public static byte[] Encode(OxyColor[,] pixels, int dpi = 96) { int height = pixels.GetLength(0); int width = pixels.GetLength(1); var bytes = new byte[(width * height * 4) + height]; int k = 0; for (int i = height - 1; i >= 0; i--) { bytes[k++] = 0; // Filter for (int j = 0; j < width; j++) { bytes[k++] = pixels[i, j].R; bytes[k++] = pixels[i, j].G; bytes[k++] = pixels[i, j].B; bytes[k++] = pixels[i, j].A; } } var w = new MemoryWriter(); w.Write((byte)0x89); w.Write("PNG\r\n\x1a\n".ToCharArray()); WriteChunk(w, "IHDR", CreateHeaderData(width, height)); WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(dpi, dpi)); WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes)); WriteChunk(w, "IEND", new byte[0]); return(w.ToArray()); }
public static int Cast(Processor proc, ProgramReader reader) { TypeFlag returnType = (TypeFlag)reader.NextInt(); uint addr = reader.NextPtr(); object v1 = BytesToNative(proc.Registers.TypeRegisters[0], proc.Registers.OperationRegisters[0]); byte[] b = null; switch (returnType) { case TypeFlag.Char: v1 = Conversions.ToChar(v1); break; case TypeFlag.Int: v1 = Conversions.ToInteger(v1); break; case TypeFlag.Float: v1 = Conversions.ToSingle(v1); break; } b = Convert(v1, returnType); MemoryWriter w = MemoryWriter.GetWriter(2, proc, addr); w.Write(b); return(reader.Elapsed()); }
private void Form1_Load(object sender, EventArgs e) { double[] values = Clin(cl, 256, 4096); List <ChartPoint> chartPoints = new List <ChartPoint>(); for (int k = 0; k < values.Length; k++) { ChartPoint point = new ChartPoint(k, values[k]); chartPoints.Add(point); } Chart chart = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Graphic", ColorDescriptor = new ColorDescriptor(255, 0, 0), Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, Points = chartPoints } } }; MemoryWriter.Write <Chart>(chart, new ChartSerialization()); ProcessManager.RunProcess(@"d:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false); }
protected internal virtual int writeStringBytes(sbyte[] bytes, int addr, int maxSize, int trailingNulls) { int bytesWritten = 0; IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(addr, 1); if (bytes != null) { int Length = System.Math.Min(bytes.Length, maxSize - 1); for (int i = 0; i < Length; i++) { memoryWriter.writeNext(bytes[i] & 0xFF); } bytesWritten += Length; } // write trailing '\0' for (int i = 0; i < trailingNulls; i++) { memoryWriter.writeNext(0); } memoryWriter.flush(); return(bytesWritten); }
/// <summary> /// Encodes the specified image data to png. /// </summary> /// <param name="pixels">The pixel data indexed as [x,y] (bottom line first).</param> /// <returns>The png image data.</returns> public byte[] Encode(OxyColor[,] pixels) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); var bytes = new byte[(width * height * 4) + height]; int k = 0; for (int y = 0; y < height; y++) { bytes[k++] = 0; // Filter for (int x = 0; x < width; x++) { bytes[k++] = pixels[x, y].R; bytes[k++] = pixels[x, y].G; bytes[k++] = pixels[x, y].B; bytes[k++] = pixels[x, y].A; } } var w = new MemoryWriter(); w.Write((byte)0x89); w.Write("PNG\r\n\x1a\n".ToCharArray()); WriteChunk(w, "IHDR", CreateHeaderData(width, height)); WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(this.options.DpiX, this.options.DpiY)); WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes)); WriteChunk(w, "IEND", new byte[0]); return(w.ToArray()); }
/// <summary> /// Creates the uncompressed blocks. /// </summary> /// <param name="bytes"> /// The data. /// </param> /// <returns> /// The output data. /// </returns> private static byte[] CreateUncompressedBlocks(byte[] bytes) { // http://www.w3.org/TR/PNG-Compression.html const int MaxDeflate = 0xFFFF; var w = new MemoryWriter(); const uint CompressionMethod = 8; const uint Check = (31 - ((CompressionMethod << 8) % 31)) % 31; w.Write((byte)CompressionMethod); w.Write((byte)Check); for (int i = 0; i < bytes.Length; i += MaxDeflate) { var n = (ushort)Math.Min(bytes.Length - i, MaxDeflate); var last = (byte)(i + n < bytes.Length ? 0 : 1); w.Write(last); w.Write((byte)(n & 0xFF)); w.Write((byte)((n >> 8) & 0xFF)); var n2 = ~n; w.Write((byte)(n2 & 0xFF)); w.Write((byte)((n2 >> 8) & 0xFF)); w.Write(bytes, i, n); } WriteBigEndian(w, Adler32(bytes)); return(w.ToArray()); }
public IEnumerable <Announce> Scrap(ScrapParametersDto scrapParametersDto) { var memory = new MemoryWriter(); var scraper = new OlxScraper { TypesToScrap = new [] { AnnouncementType.Sale }, Logger = new CompositeLogger { Loggers = { new ConsoleLogger() } }, Writer = new CompositeWriter { Writers = { new ConsoleWriter(), memory } } }; var(startPage, stopPage) = scrapParametersDto.ConvertParameters(); scraper.Start(startPage, stopPage); scraper.ScrapeOffers(); return(memory.Announcements.Select(a => a.ToAnnounce())); }
public void WriteToFileTest() { var filePath = $@"{_logFolderPath}\LogTest{DateTime.Now.AddMinutes(1):yyyyMMdd HHmmss fff}.log"; var config = new Mock <IConfiguration>(); config.Setup(c => c.GetLogFileName()).Returns(filePath); config.Setup(c => c.GetLogFolderPath()).Returns(_logFolderPath); var fileWriter = new FileWriter(config.Object); var memoryWriter = new MemoryWriter(); var logLine = new LogLine { Timestamp = DateTime.Now, Text = "Test" }; fileWriter.Write(logLine); fileWriter.Close(); _filesCreatedPaths.Add(filePath); memoryWriter.Write(logLine); //try to find the file var fileExist = File.Exists(filePath); Assert.IsTrue(fileExist); //try to read from the file var file = new StreamReader(filePath); var text = file.ReadToEnd(); file.Close(); Assert.AreEqual(memoryWriter.MemoryLog, text); }
public virtual SmartBuffer EncryptUdp(ReadOnlyMemory <byte> plain) { if (plain.IsEmpty) { _logger?.LogInformation($"ShadowosocksAeadCipher EncryptUdp plain.IsEmpty."); return(null); } var cipherPacket = SmartBuffer.Rent(1500 + LEN_TAG + _keySize_SaltSize.Item2); var cipherPacketStream = new MemoryWriter(cipherPacket.Memory); byte[] salt = new byte[_keySize_SaltSize.Item2], key = new byte[_keySize_SaltSize.Item1]; RandomNumberGenerator.Fill(salt); DeriveSubKey(_masterKeyBytes, salt, SubkeyInfoBytes, key, key.Length); //[encrypted payload][tag] using (var payload = this.EncryptChunk(plain, key.AsSpan(), _nonceZero.AsSpan())) { cipherPacketStream.Write(salt.AsMemory()); cipherPacketStream.Write(payload.SignificantMemory); cipherPacket.SignificantLength = cipherPacketStream.Position; //[salt][encrypted payload][tag] } return(cipherPacket); }
/// <summary> /// Write a string in UTF16, including a trailing '\0\0' </summary> /// <param name="addr"> address where to write the string </param> /// <param name="s"> the string to write </param> /// <returns> the number of bytes written (not including the trailing '\0\0') </returns> protected internal virtual int writeStringUTF16Z(int addr, string s) { if (addr == 0 || string.ReferenceEquals(s, null)) { return(0); } sbyte[] bytes = s.GetBytes(charset16); if (bytes == null) { return(0); } IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(addr, bytes.Length + 2, 1); for (int i = 0; i < bytes.Length; i++) { memoryWriter.writeNext(bytes[i] & 0xFF); } // Write trailing '\0\0' memoryWriter.writeNext(0); memoryWriter.writeNext(0); memoryWriter.flush(); return(bytes.Length); }
private bool read(sbyte[] data) { if (data == null || data.Length == 0) { return(false); } inputLength = data.Length; IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(inputAddr, inputLength, 1); for (int i = 0; i < data.Length; i++) { memoryWriter.writeNext(data[i] & 0xFF); } memoryWriter.flush(); sceAtrac3plus.AtracFileInfo atracFileInfo = new sceAtrac3plus.AtracFileInfo(); int codecType = sceAtrac3plus.analyzeRiffFile(mem, inputAddr, inputLength, atracFileInfo); if (codecType < 0) { return(false); } bool result = read(codecType, atracFileInfo); return(result); }
private void btnBuildTable_Click(object sender, EventArgs e) { List <Point2D> points = ModularArithmeticHelper.BuildTable(M1, M2, MAX_RANGE_VALUE); List <ChartPoint> chartPoints = new List <ChartPoint>(); for (int k = 0; k < points.Count; k++) { Point2D p = points[k]; ChartPoint p1 = new ChartPoint(p.X, p.Y); chartPoints.Add(p1); } Chart chart1 = new Chart() { SeriesCollection = new List <ChartSeries>() { new ChartSeries() { Name = "Graph diagonals", Type = HoloCommon.Enumeration.Charting.ChartSeriesType.Linear, ColorDescriptor = new ColorDescriptor(255, 0, 0), Points = chartPoints } } }; MemoryWriter.Write <Chart>(chart1, new ChartSerialization()); ProcessManager.RunProcess(@"D:\Projects\HoloApplication\Modules\ChartApp\ChartApp\bin\Release\ChartApp.exe", null, false, false); Thread.Sleep(2000); }
internal DiskManager(EngineSettings settings, IPieceWriter writer = null) { ReadLimiter = new RateLimiter(); ReadMonitor = new SpeedMonitor(); ReadQueue = new Queue <BufferedIO> (); WriteLimiter = new RateLimiter(); WriteMonitor = new SpeedMonitor(); WriteQueue = new Queue <BufferedIO> (); UpdateTimer = ValueStopwatch.StartNew(); Settings = settings ?? throw new ArgumentNullException(nameof(settings)); // If we pass in an IPieceWriter it should be used *instead* of these. // However we still create these so the properties are non-null. DiskWriter = new DiskWriter(settings.MaximumOpenFiles) { ReadMonitor = ReadMonitor, WriteMonitor = WriteMonitor, }; MemoryWriter = new MemoryWriter(DiskWriter, settings.DiskCacheBytes); Writer = writer ?? MemoryWriter; }
public static void sortFloatArray8Reverse() { int addr = GprA0; int size = GprA1; if (size < 2) { return; } // Read the objects from memory Float8ObjectReverse[] objects = new Float8ObjectReverse[size]; IMemoryReader memoryReader = MemoryReader.getMemoryReader(addr, size << 3, 4); for (int i = 0; i < size; i++) { objects[i] = new Float8ObjectReverse(memoryReader); } // Sort the objects Array.Sort(objects); // Write back the objects to memory IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(addr, size << 3, 4); for (int i = 0; i < size; i++) { objects[i].write(memoryWriter); } memoryWriter.flush(); }
public async Task OverFillBuffer() { var writer = new MemoryWriter(); var cache = new MemoryCache(new MemoryPool(), Constants.BlockSize, writer); // Write 4 blocks to the stream and then verify they can all be read for (int i = 0; i < 4; i++) { var buffer = Enumerable.Repeat((byte)(i + 1), Constants.BlockSize).ToArray(); await cache.WriteAsync(torrent, new BlockInfo (0, Constants.BlockSize *i, Constants.BlockSize), buffer, false); Assert.AreEqual(Constants.BlockSize, cache.CacheUsed, "#0"); } Assert.AreEqual(3, writer.Writes.Count, "#1b"); Assert.AreEqual(0, writer.Reads.Count, "#1c"); // Read them all back out and verify them for (int i = 0; i < 4; i++) { var buffer = new byte[Constants.BlockSize]; await cache.ReadAsync(torrent, new BlockInfo (0, Constants.BlockSize *i, Constants.BlockSize), buffer); Assert.IsTrue(buffer.All(t => t == (byte)(i + 1)), "#2." + i); } Assert.AreEqual(Constants.BlockSize, cache.CacheHits, "#3"); Assert.AreEqual(Constants.BlockSize * 3, cache.CacheMisses, "#4"); Assert.AreEqual(4, writer.Writes.Count, "#5"); Assert.AreEqual(0, cache.CacheUsed, "#6"); }
static void Main(string[] args) { WriteableBitmap image = MemoryReader.Read <WriteableBitmap>(new WriteableBitmapSerialization()); image = image.Rotate(90); MemoryWriter.Write <WriteableBitmap>(image, new WriteableBitmapSerialization()); }
public virtual SmartBuffer EncryptTcp(ReadOnlyMemory <byte> plain) { if (plain.IsEmpty) { _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp plain.IsEmpty."); return(null); } int cipherLen = CalcTcpCipherStreamLength(plain.Length); SmartBuffer cihperBuffer = SmartBuffer.Rent(cipherLen); var cipherStream = new MemoryWriter(cihperBuffer.Memory); if (!_tcpCtx加密.HaveSalt()) { _tcpCtx加密.NewSalt(); cipherStream.Write(_tcpCtx加密.Salt.AsMemory()); _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp new salt wrote. { _tcpCtx加密.Salt.ToHexString()}"); DeriveSubKey(_masterKeyBytes, _tcpCtx加密.Salt, SubkeyInfoBytes, _tcpCtx加密.Key, _tcpCtx加密.Key.Length); _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp new subkey {_tcpCtx加密.Key.ToHexString()}."); } int remain = plain.Length; int chunkLen = 0, encrypted = 0; do { chunkLen = Math.Min(remain, LEN_TCP_MAX_CHUNK); //payload length. { byte[] payloadLenBytes = BitConverter.GetBytes((ushort)(System.Net.IPAddress.HostToNetworkOrder((short)chunkLen))); _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp chunklen={chunkLen}, payloadLenBytes={payloadLenBytes.ToHexString()}."); using (var payloadLenC = this.EncryptChunk(payloadLenBytes, _tcpCtx加密.Key, _tcpCtx加密.Nonce)) { //[encrypted payload length][length tag] cipherStream.Write(payloadLenC.Memory.Slice(0, payloadLenC.SignificantLength)); _tcpCtx加密.IncreaseNonce(); } } //payload. { var payload = plain.Slice(plain.Length - remain, chunkLen); using (var payloadC = this.EncryptChunk(payload, _tcpCtx加密.Key, _tcpCtx加密.Nonce)) { //[encrypted payload][payload tag] cipherStream.Write(payloadC.Memory.Slice(0, payloadC.SignificantLength)); _tcpCtx加密.IncreaseNonce(); } } //------------------------------- encrypted += chunkLen; _logger?.LogInformation($"ShadowosocksAeadCipher EncryptTcp encrypted {encrypted} bytes."); remain -= chunkLen; } while (remain > 0); cihperBuffer.SignificantLength = cipherStream.Position; return(cihperBuffer); }
public void WritingLogsFromDifferentDaysEndUpInDifferentFilesTest() { var filePathToday = $@"{_logFolderPath}\LogTest{DateTime.Now:yyyyMMdd HHmmss fff}.log"; var filePathTomorrow = $@"{_logFolderPath}\LogTest{DateTime.Now.AddDays(1):yyyyMMdd HHmmss fff}.log"; var configMock = new Mock <IConfiguration>(); //setup configuration to return a different file name on the second call configMock.SetupSequence(x => x.GetLogFileName()) .Returns(filePathToday) .Returns(filePathTomorrow); var fileWriter = new FileWriter(configMock.Object); var memoryWriter1 = new MemoryWriter(); var memoryWriter2 = new MemoryWriter(); //setup two different logLines, one with a timestamp from today and the other with a timestamp from tomorrow var logLine1 = new LogLine { Timestamp = DateTime.Now, Text = "Test" }; var logLine2 = new LogLine { Timestamp = DateTime.Now.AddDays(1), Text = "Test2" }; fileWriter.Write(logLine1); memoryWriter1.Write(logLine1); fileWriter.Write(logLine2); memoryWriter2.Write(logLine2); fileWriter.Close(); _filesCreatedPaths.Add(filePathToday); _filesCreatedPaths.Add(filePathTomorrow); //try to find the first file var fileExist = File.Exists(filePathToday); Assert.IsTrue(fileExist); //try to find the second file fileExist = File.Exists(filePathTomorrow); Assert.IsTrue(fileExist); //try to read from the first file var file1 = new StreamReader(filePathToday); var textFile1 = file1.ReadToEnd(); file1.Close(); Assert.AreEqual(memoryWriter1.MemoryLog, textFile1); //try to read from the second file var file2 = new StreamReader(filePathTomorrow); var textFile2 = file2.ReadToEnd(); file2.Close(); Assert.AreEqual(memoryWriter2.MemoryLog, textFile2); }
public static long Write <AddressT, DataT>(this Memory <AddressT, DataT> memory, byte[] buffer) where AddressT : BusData, new() where DataT : BusData, new() { var writer = new MemoryWriter <AddressT, DataT>(memory); return(writer.CopyFrom(CreateBinaryReader(buffer))); }
public void Given_CorruptedData_Then_ProgramWritesCorrectMessage(string firstArgument, string secondArgument) { var memory = new MemoryWriter(); var program = TestUtils.CreateTestProgram(memory); program.Run(new[] { firstArgument, secondArgument }); Assert.AreEqual(TestUtils.GetUnexpectedErrorMessage(), memory.ReadLast()); }
public void Given_WrongSecondArgument_Then_ProgramWritesErrorMessage(string firstArgument, string secondArgument) { var memory = new MemoryWriter(); var program = TestUtils.CreateTestProgram(memory); program.Run(new[] { firstArgument, secondArgument }); Assert.AreEqual(TestUtils.GetCannotParseMessage(secondArgument), memory.ReadLast()); }
/// <summary> /// Moves to a specified Waypoint. /// Other movement function rely on this. /// Implements CTM struct for movement currently. /// TODO: Facade this when Settings are implmented /// </summary> /// <param name="wp"></param> private void moveToLoc(Waypoint wp) { if (!isInRange(wp, 1.0f)) { int tries = 0; while (verifyWrite(wp.getX(), 0xC4D890) == false && tries < 3) { MemoryWriter.WriteMem(WoW_Instance.getProcess(), 0xC4D890, BitConverter.GetBytes(wp.getX())); tries++; if (tries >= 3) { return; } } tries = 0; Thread.Sleep(3); while (verifyWrite(wp.getY(), 0xC4D894) == false && tries < 3) { MemoryWriter.WriteMem(WoW_Instance.getProcess(), 0xC4D894, BitConverter.GetBytes(wp.getY())); tries++; if (tries >= 3) { return; } } tries = 0; Thread.Sleep(3); float z = wp.getZ(); if (z == 0) { // For glider imports z = this.getLocation().getZ(); } while (verifyWrite(wp.getZ(), 0xC4D898) == false && tries < 3) { MemoryWriter.WriteMem(WoW_Instance.getProcess(), 0xC4D898, BitConverter.GetBytes(wp.getZ())); tries++; if (tries >= 3) { return; } } tries = 0; Thread.Sleep(5); MemoryWriter.WriteMem(WoW_Instance.getProcess(), 0xC4D888, new byte[] { (byte)0x04 }); //MemoryWriter.WriteMem(WoW_Instance.getProcess(), 0xC4D888, new byte[] { (byte)0x04 }); //Thread.Sleep(200); //Debug.Print("Moving: " + isMoving()); //while (isMoving()) // Thread.Sleep(15); //Enjoy the ride //Thread.Sleep(20); } }
public void Setup() { var pieceLength = Constants.BlockSize * 8; var files = TorrentFileInfo.Create(pieceLength, ("Relative/Path.txt", Constants.BlockSize * 5, "Full/Path/Relative/Path.txt")); torrent = TestTorrentManagerInfo.Create(pieceLength: pieceLength, size: files.Single().Length, files: files); writer = new MemoryWriter(); cache = new MemoryCache(new MemoryPool(), Constants.BlockSize * 4, writer); }
public void Given_StartDateBefore_Then_ProgramWritesErrorMessage(string firstArgument, string secondArgument, string expectedOutput) { var memory = new MemoryWriter(); var program = TestUtils.CreateTestProgram(memory); program.Run(new[] { firstArgument, secondArgument }); Assert.AreEqual(expectedOutput, memory.ReadLast()); }
public void Given_HappyCases_Then_ProgramWritesCorrectInterval(string firstArgument, string secondArgument, string expectedOutput) { var memory = new MemoryWriter(); var program = TestUtils.CreateTestProgram(memory); program.Run(new[] { firstArgument, secondArgument }); Assert.AreEqual(expectedOutput, memory.ReadLast()); }
public void Given_WrongParameterCount_Then_ProgramWritesErrorMessage(int count) { var memory = new MemoryWriter(); var program = TestUtils.CreateTestProgram(memory); var parameters = TestDataSources.StringEmitter().Take(count).ToArray(); program.Run(parameters); Assert.AreEqual(TestUtils.GetWrongCountMessage(count), memory.ReadLast()); }
public async Task OverFillBuffer_CacheUsed() { var writer = new MemoryWriter(); var cache = new MemoryCache(new MemoryPool(), 4, writer); await cache.WriteAsync(torrent, new BlockInfo (0, 0, 3), Enumerable.Repeat ((byte)1, 3).ToArray(), false); await cache.WriteAsync(torrent, new BlockInfo (0, 3, 4), Enumerable.Repeat ((byte)2, 4).ToArray(), false); Assert.AreEqual(4, cache.CacheUsed); }
/// <summary> /// Encodes the specified image data to png. /// </summary> /// <param name="pixels">The pixel data indexed as [x,y] (bottom line first).</param> /// <returns>The png image data.</returns> public byte[] Encode(OxyColor[,] pixels) { int width = pixels.GetLength(0); int height = pixels.GetLength(1); var bytes = new byte[(width * height * 4) + height]; int k = 0; for (int y = 0; y < height; y++) { bytes[k++] = 0; // Filter for (int x = 0; x < width; x++) { bytes[k++] = pixels[x, y].R; bytes[k++] = pixels[x, y].G; bytes[k++] = pixels[x, y].B; bytes[k++] = pixels[x, y].A; } } var w = new MemoryWriter(); w.Write((byte)0x89); w.Write("PNG\r\n\x1a\n".ToCharArray()); WriteChunk(w, "IHDR", CreateHeaderData(width, height)); WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(this.options.DpiX, this.options.DpiY)); WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes)); WriteChunk(w, "IEND", new byte[0]); return w.ToArray(); }
/// <summary> /// Creates the header data. /// </summary> /// <param name="width"> /// The width. /// </param> /// <param name="height"> /// The height. /// </param> /// <returns> /// The header. /// </returns> private static byte[] CreateHeaderData(int width, int height) { // http://www.w3.org/TR/PNG-Chunks.html var w = new MemoryWriter(); WriteBigEndian(w, width); WriteBigEndian(w, height); w.Write((byte)8); // bit depth w.Write((byte)6); // color type RGBA w.Write((byte)0); // compression method w.Write((byte)0); // filter method w.Write((byte)0); // interlace method return w.ToArray(); }
/// <summary> /// Creates the physical dimensions data. /// </summary> /// <param name="dpix"> /// The horizontal resolution. /// </param> /// <param name="dpiy"> /// The vertical resolution. /// </param> /// <returns> /// The data. /// </returns> private static byte[] CreatePhysicalDimensionsData(int dpix, int dpiy) { var ppux = (int)(dpix / 0.0254); var ppuy = (int)(dpiy / 0.0254); var w = new MemoryWriter(); WriteBigEndian(w, ppux); WriteBigEndian(w, ppuy); w.Write((byte)1); // Unit: metre return w.ToArray(); }
/// <summary> /// Creates the uncompressed blocks. /// </summary> /// <param name="bytes"> /// The data. /// </param> /// <returns> /// The output data. /// </returns> private static byte[] CreateUncompressedBlocks(byte[] bytes) { // http://www.w3.org/TR/PNG-Compression.html const int MaxDeflate = 0xFFFF; var w = new MemoryWriter(); const uint CompressionMethod = 8; const uint Check = (31 - ((CompressionMethod << 8) % 31)) % 31; w.Write((byte)CompressionMethod); w.Write((byte)Check); for (int i = 0; i < bytes.Length; i += MaxDeflate) { var n = (ushort)Math.Min(bytes.Length - i, MaxDeflate); var last = (byte)(i + n < bytes.Length ? 0 : 1); w.Write(last); w.Write((byte)(n & 0xFF)); w.Write((byte)((n >> 8) & 0xFF)); var n2 = ~n; w.Write((byte)(n2 & 0xFF)); w.Write((byte)((n2 >> 8) & 0xFF)); w.Write(bytes, i, n); } WriteBigEndian(w, Adler32(bytes)); return w.ToArray(); }
public EngineTestRig(string savePath, int piecelength, PieceWriter writer) { if(writer == null) writer = new MemoryWriter(new NullWriter()); listener = new CustomListener(); engine = new ClientEngine(new EngineSettings(), listener, writer); torrentDict = CreateTorrent(piecelength); torrent = Torrent.Load(torrentDict); manager = new TorrentManager(torrent, savePath, new TorrentSettings()); engine.Register(manager); //manager.Start(); }
/// <summary> /// Encodes the specified image data to png. /// </summary> /// <param name="pixels"> /// The pixel data (bottom line first). /// </param> /// <param name="dpi"> /// The image resolution in dots per inch. /// </param> /// <returns> /// The png image data. /// </returns> public static byte[] Encode(OxyColor[,] pixels, int dpi = 96) { int height = pixels.GetLength(0); int width = pixels.GetLength(1); var bytes = new byte[(width * height * 4) + height]; int k = 0; for (int i = height - 1; i >= 0; i--) { bytes[k++] = 0; // Filter for (int j = 0; j < width; j++) { bytes[k++] = pixels[i, j].R; bytes[k++] = pixels[i, j].G; bytes[k++] = pixels[i, j].B; bytes[k++] = pixels[i, j].A; } } var w = new MemoryWriter(); w.Write((byte)0x89); w.Write("PNG\r\n\x1a\n".ToCharArray()); WriteChunk(w, "IHDR", CreateHeaderData(width, height)); WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(dpi, dpi)); WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes)); WriteChunk(w, "IEND", new byte[0]); return w.ToArray(); }
public void Setup() { Initialize(_buffer, 1); _level2 = new MemoryWriter(new NullWriter(), Piece.BlockSize*3); _level1 = new MemoryWriter(_level2, Piece.BlockSize*3); }