Beispiel #1
0
        public static BitmapHeader GetHeader(MemoryMappedViewAccessor Reader, out long MMPosition)
        {
            MMPosition = 0;

            var header = new BitmapHeader();

            header.Type = Encoding.ASCII.GetString(new byte[] { Reader.ReadByte(MMPosition) });
            MMPosition++;

            header.Type += Encoding.ASCII.GetString(new byte[] { Reader.ReadByte(MMPosition) });
            MMPosition++;

            header.FileSize = Reader.ReadInt32(MMPosition);
            MMPosition     += 4;

            header.Reserved = Reader.ReadInt32(MMPosition);
            MMPosition     += 4;

            header.Offset = Reader.ReadInt32(MMPosition);
            MMPosition   += 4;

            header.BitmapInfoHeaderSize = Reader.ReadInt32(MMPosition);
            MMPosition += 4;

            return(header);
        }
Beispiel #2
0
        public byte ReadByte()
        {
            byte b = m_view.ReadByte(Next);

            Next += sizeof(byte);
            return(b);
        }
Beispiel #3
0
 public ItemData <byte> ReadByte(DeviceAddress address)
 {
     try
     {
         return(new ItemData <byte>(accessor.ReadByte(FindPosition(address)), 0, QUALITIES.QUALITY_GOOD));
     }
     catch { return(new ItemData <byte>(0, 0, QUALITIES.QUALITY_BAD)); }
 }
        public void RandomAccessReadWriteMemoryMappedProjectedFile()
        {
            string filename        = @"Test_EPF_WorkingDirectoryTests\RandomAccessReadWriteMemoryMappedProjectedFile.cs";
            string fileVirtualPath = this.Enlistment.GetVirtualPathTo(filename);

            string        contents        = fileVirtualPath.ShouldBeAFile(this.fileSystem).WithContents();
            StringBuilder contentsBuilder = new StringBuilder(contents);

            using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileVirtualPath))
            {
                // Length of the Byte-order-mark that will be at the start of the memory mapped file.
                // See https://msdn.microsoft.com/en-us/library/windows/desktop/dd374101(v=vs.85).aspx
                int bomOffset = 3;

                // offset -> Number of bytes from the start of the file where the view starts
                int    offset     = 64;
                int    size       = contents.Length;
                string newContent = "**NEWCONTENT**";

                using (MemoryMappedViewAccessor randomAccessor = mmf.CreateViewAccessor(offset, size - offset + bomOffset))
                {
                    randomAccessor.CanRead.ShouldEqual(true);
                    randomAccessor.CanWrite.ShouldEqual(true);

                    for (int i = 0; i < size - offset; ++i)
                    {
                        ((char)randomAccessor.ReadByte(i)).ShouldEqual(contents[i + offset - bomOffset]);
                    }

                    for (int i = 0; i < newContent.Length; ++i)
                    {
                        // Convert to byte before writing rather than writing as char, because char version will write a 16-bit
                        // unicode char
                        randomAccessor.Write(i, Convert.ToByte(newContent[i]));
                        ((char)randomAccessor.ReadByte(i)).ShouldEqual(newContent[i]);
                    }

                    for (int i = 0; i < newContent.Length; ++i)
                    {
                        contentsBuilder[offset + i - bomOffset] = newContent[i];
                    }

                    contents = contentsBuilder.ToString();
                }

                // Verify the file has the new contents inserted into it
                using (MemoryMappedViewAccessor randomAccessor = mmf.CreateViewAccessor(offset: 0, size: size + bomOffset))
                {
                    for (int i = 0; i < size; ++i)
                    {
                        ((char)randomAccessor.ReadByte(i + bomOffset)).ShouldEqual(contents[i]);
                    }
                }
            }

            // Confirm the new contents was written to disk
            fileVirtualPath.ShouldBeAFile(this.fileSystem).WithContents(contents);
        }
        /// <summary>Performs validation on a view accessor.</summary>
        /// <param name="accessor">The accessor to validate.</param>
        /// <param name="capacity">The capacity specified when creating the accessor.</param>
        /// <param name="access">The access specified when creating the accessor.</param>
        protected static void ValidateMemoryMappedViewAccessor(MemoryMappedViewAccessor accessor, long capacity, MemoryMappedFileAccess access)
        {
            // Validate the accessor and its handle
            Assert.NotNull(accessor);
            Assert.NotNull(accessor.SafeMemoryMappedViewHandle);
            Assert.Same(accessor.SafeMemoryMappedViewHandle, accessor.SafeMemoryMappedViewHandle);

            // Ensure its properties match the criteria specified when it was created
            Assert.InRange(capacity, 0, accessor.Capacity); // the capacity may be rounded up to page size, so all we guarantee is that the accessor's capacity >= capacity
            Assert.Equal(0, accessor.PointerOffset);

            // If it's supposed to be readable, try to read from it.
            // Otherwise, verify we can't.
            if (IsReadable(access))
            {
                Assert.True(accessor.CanRead);
                Assert.Equal(0, accessor.ReadByte(0));
                Assert.Equal(0, accessor.ReadByte(capacity - 1));
            }
            else
            {
                Assert.False(accessor.CanRead);
                Assert.Throws <NotSupportedException>(() => accessor.ReadByte(0));
            }

            // If it's supposed to be writable, try to write to it
            if (IsWritable(access) || access == MemoryMappedFileAccess.CopyOnWrite)
            {
                Assert.True(accessor.CanWrite);

                // Write some data
                accessor.Write(0, (byte)42);
                accessor.Write(capacity - 1, (byte)42);

                // If possible, ensure we can read it back
                if (IsReadable(access))
                {
                    Assert.Equal(42, accessor.ReadByte(0));
                    Assert.Equal(42, accessor.ReadByte(capacity - 1));
                }

                // Write 0 back where we wrote data
                accessor.Write(0, (byte)0);
                accessor.Write(capacity - 1, (byte)0);
            }
            else
            {
                Assert.False(accessor.CanWrite);
                Assert.Throws <NotSupportedException>(() => accessor.Write(0, (byte)0));
            }
        }
        internal bool IsNullTranslated(long translatedRowIndex, long translatedColumnIndex)
        {
            var columnMetadata    = Metadata.Columns[translatedColumnIndex];
            var nullBitmaskOffset = columnMetadata.NullBitmaskOffset;

            var nullBitmaskByteOffset = nullBitmaskOffset + (translatedRowIndex / 8);
            var nullBitmaskBitmask    = (byte)(1 << (byte)(translatedRowIndex % 8));

            var nullBitmaskByte = View.ReadByte(nullBitmaskByteOffset);

            var isNull = (nullBitmaskByte & nullBitmaskBitmask) == 0;

            return(isNull);
        }
Beispiel #7
0
        public int Read()
        {
            long position = _position + _origin;

            if (position >= _length)
            {
                return(-1);
            }

            var value = _accessor.ReadByte(position);

            _position++;

            return(value);
        }
Beispiel #8
0
        private static void Function_MapowaniePlikowWPamięci()
        {
            //niedostepne dla sklepu windows

            //losowe operacje plikowe lepiej ta metoda gdy kiilka wątków ,
            //filestream dla sekwencyjnego dostepu do danych

            //File.WriteAllBytes("long.bin",new byte[1000000]);
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("long.bin"))
                using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor())
                {
                    accessor.Write(500000, (byte)77);
                    Console.WriteLine(accessor.ReadByte(500000));
                }


            ////pamiec wspóldzielona
            //using (MemoryMappedFile mmFile = MemoryMappedFile.CreateNew("Demo", 500))
            //using (MemoryMappedViewAccessor accessor = mmFile.CreateViewAccessor())
            //{
            //    accessor.Write(0, 12345);
            //    Console.ReadLine();//pamiec wspoldzileona pozostaje aktywna ąz do naciśniecia enter
            //}

            ////może być w innym pliku exe
            //using (MemoryMappedFile mmFile = MemoryMappedFile.OpenExisting("Demo"))
            //{
            //    using (MemoryMappedViewAccessor accessor = mmFile.CreateViewAccessor())
            //    {
            //        Console.WriteLine(accessor.ReadInt32(0));//12345
            //    }
            //}
        }
Beispiel #9
0
    /// START HELPER FUNCTIONS
    public void VerifyWrite <T>(String strLoc, MemoryMappedViewAccessor view, long position, T value)
    {
        iCountTestcases++;
        try
        {
            // write the value
            MethodInfo writeMethod = GetWriteMethod(typeof(T));
            writeMethod.Invoke(view, new Object[] { position, value });

            // read the value and compare
            MethodInfo readMethod = GetReadMethod(typeof(T));
            T          ret        = (T)readMethod.Invoke(view, new Object[] { position });
            Eval <T>(value, ret, "ERROR, {0}_{1}:  Returned value was wrong.", strLoc, typeof(T).Name);

            // read the bytes and compare
            Byte[] expectedBytes = GetExpectedBytes(typeof(T), value);
            for (int i = 0; i < expectedBytes.Length; i++)
            {
                Eval <Byte>(expectedBytes[i], view.ReadByte(position + i), "ERROR, {0}_{1}:  Byte at position {2} was wrong.", strLoc, typeof(T).Name, position + i);
            }
        }
        catch (TargetInvocationException ex)
        {
            Exception inner = ex.InnerException;
            iCountErrors++;
            Console.WriteLine("ERROR, {0}_{1}: Unexpected exception, {2}", strLoc, typeof(T).Name, inner);
        }
        catch (Exception ex)
        {
            iCountErrors++;
            Console.WriteLine("ERROR, {0}_{1}: Unexpected exception, {2}", strLoc, typeof(T).Name, ex);
        }
    }
Beispiel #10
0
        private byte Get()
        {
            byte rv = mapAccess.ReadByte(rdPtr);

            rdPtr = incPtr(rdPtr);
            return(rv);
        }
Beispiel #11
0
        public override byte ReadByte()
        {
            byte b = _mma.ReadByte(Position);

            Position++;
            return(b);
        }
Beispiel #12
0
        public void DataShared()
        {
            // Create a new file and load it into an MMF
            using (TempFile file = new TempFile(GetTestFilePath(), 4096))
                using (FileStream fs = new FileStream(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                    using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, fs.Length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
                        using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor())
                        {
                            // Write some known data to the map
                            long capacity = acc.Capacity;
                            for (int i = 0; i < capacity; i++)
                            {
                                acc.Write(i, unchecked ((byte)i));
                            }
                            acc.Flush();

                            // Spawn and then wait for the other process, which will verify the data and write its own known pattern
                            RemoteInvoke(DataShared_OtherProcess, $"\"{file.Path}\"").Dispose();

                            // Now verify we're seeing the data from the other process
                            for (int i = 0; i < capacity; i++)
                            {
                                Assert.Equal(unchecked ((byte)(capacity - i - 1)), acc.ReadByte(i));
                            }
                        }
        }
Beispiel #13
0
        public static string ReadString(this MemoryMappedViewAccessor accessor, int offset, int maxLength, int minLength = 0)
        {
            StringBuilder sb;

            if (minLength > 0)
            {
                sb = new(minLength);
            }
            else
            {
                sb = new();
            }
            char c;

            for (int i = 0; i < maxLength; i++)
            {
                c = (char)accessor.ReadByte(offset + i);
                if (c == '\0')
                {
                    break;
                }
                sb.Append(c);
            }
            return(sb.ToString());
        }
Beispiel #14
0
        public void MultipleMapsForTheSameFileStream()
        {
            const int Capacity = 4096;

            using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
                using (FileStream fs = new FileStream(file.Path, FileMode.Open))
                    using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
                        using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
                            using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor())
                                using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor())
                                {
                                    // The capacity of the two maps should be equal
                                    Assert.Equal(acc1.Capacity, acc2.Capacity);

                                    var rand = new Random();
                                    for (int i = 1; i <= 10; i++)
                                    {
                                        // Write a value to one map, then read it from the other,
                                        // ping-ponging between the two.
                                        int pos = rand.Next((int)acc1.Capacity - 1);
                                        MemoryMappedViewAccessor reader = acc1, writer = acc2;
                                        if (i % 2 == 0)
                                        {
                                            reader = acc2;
                                            writer = acc1;
                                        }
                                        writer.Write(pos, (byte)i);
                                        writer.Flush();
                                        Assert.Equal(i, reader.ReadByte(pos));
                                    }
                                }
        }
        public async void ReadThread()
        {
            try
            {
                while (true)
                {
                    while (receiverAccessor.ReadByte(0) != 1)
                    {
                        if (readCts.Token.IsCancellationRequested)
                        {
                            return;
                        }
                        Thread.Sleep(1);// await Task.Delay(1);
                    }
                    System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread DataReceived");
                    long position = 1;
                    //CommandType
                    var length = receiverAccessor.ReadInt32(position);
                    position += sizeof(int);
                    var typeNameArray = new byte[length];
                    receiverAccessor.ReadArray(position, typeNameArray, 0, typeNameArray.Length);
                    position += typeNameArray.Length;
                    System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread GetCommandType");
                    //RequestID
                    length    = receiverAccessor.ReadInt32(position);
                    position += sizeof(int);
                    var requestIdArray = new byte[length];
                    receiverAccessor.ReadArray(position, requestIdArray, 0, requestIdArray.Length);
                    position += requestIdArray.Length;
                    System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread GetRequestID");
                    //Data
                    length    = receiverAccessor.ReadInt32(position);
                    position += sizeof(int);
                    var dataArray = new byte[length];
                    receiverAccessor.ReadArray(position, dataArray, 0, dataArray.Length);
                    System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread GetData");
                    //Write finish flag
                    receiverAccessor.Write(0, (byte)0);
                    System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread Write finish flag");

                    var commandType = PipeCommands.GetCommandType(Encoding.UTF8.GetString(typeNameArray));
                    var requestId   = Encoding.UTF8.GetString(requestIdArray);
                    var data        = BinarySerializer.Deserialize(dataArray, commandType);
                    System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread Parsed Type:{commandType.Name} requestId = {requestId}");
                    if (WaitReceivedDictionary.ContainsKey(requestId))
                    {
                        System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread ContainsKey");
                        WaitReceivedDictionary[requestId] = data;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread Raise Event");
                        ReceivedEvent?.Invoke(this, new DataReceivedEventArgs(commandType, requestId, data));
                    }
                }
            }
            catch (NullReferenceException) { }
        }
Beispiel #16
0
        public Bitmap ConvertToBitmap()
        {
            if (FileHeader.FileSize > int.MaxValue - 70)
            {
                throw new InvalidOperationException("File Size is too big, Try using \"Chunk\" method to get smaller Picture Size");
            }

            if (FileInfoHeader.BitmapHeight > int.MaxValue || FileInfoHeader.BitmapWidth > int.MaxValue || FileInfoHeader.ColorDataSize > int.MaxValue)
            {
                throw new InvalidOperationException("Color Data (Height or Width) is(are) too high, Cant fit one (or more) in \"Int\" DataType");
            }

            Bitmap map = null;

            using (var ms = new MemoryStream())
            {
                var header = new BitmapHeader();
                header.FileSize = (int)FileHeader.FileSize - 16;

                var headerInfo = new BitmapInfoHeader();
                headerInfo.BitmapHeight = (int)FileInfoHeader.BitmapHeight;
                headerInfo.BitmapWidth  = (int)FileInfoHeader.BitmapWidth;

                headerInfo.BitsPerPixel         = FileInfoHeader.BitsPerPixel;
                headerInfo.ColorPlanes          = FileInfoHeader.ColorPlanes;
                headerInfo.HorizantalResolution = FileInfoHeader.HorizantalResolution;
                headerInfo.VerticalResolution   = FileInfoHeader.VerticalResolution;

                var data = header.CreateBitmapHeader();
                ms.Write(data, 0, data.Length);

                data = headerInfo.CreateInfoHeaderData((int)FileInfoHeader.ColorDataSize);
                ms.Write(data, 0, data.Length);
                data = null;

                for (int i = 0; i < header.FileSize - 54; i++) // 54 = 70 - 16
                {
                    SeektoPage(i + 70);
                    ms.WriteByte(Reader.ReadByte(((i + 70) % MemoryPageSize)));
                }
                map = new Bitmap(ms);
            }

            return(map);
        }
    public static void Main(string[] args)
    {
        FileInfo file = new FileInfo(args[0]);

        using (MemoryMappedFile mapping = MemoryMappedFile.CreateFromFile(file.Name))
        {
            using (MemoryMappedViewAccessor view = mapping.CreateViewAccessor())
            {
                for (long i = 0, j = file.Length - 1; i < j; ++i, j--)
                {
                    byte ib = view.ReadByte(i);
                    byte jb = view.ReadByte(j);
                    view.Write(i, jb);
                    view.Write(j, ib);
                }
            }
        }
    }
Beispiel #18
0
            public int this[long index] {
                get {
                    using (new MmapLocker(this)) {
                        CheckIndex(index);

                        return(_view.ReadByte(index));
                    }
                }

                set {
                    using (new MmapLocker(this)) {
                        EnsureWritable();
                        CheckIndex(index);

                        _view.Write(index, (byte)value);
                    }
                }
            }
Beispiel #19
0
 byte[] ReadAllData()
 {
     byte[] buffer = new byte[DATASIZE];
     for (int i = 0; i < buffer.Length; i++)
     {
         buffer[i] = accessor.ReadByte(i);
     }
     return(buffer);
 }
Beispiel #20
0
        public byte ExchangeBit(int left, byte data)
        {
            if (!ipcConnectionExists)
            {
                EstablishIPCConnection();
            }

            accessor.Write(ipcOffsetSelf, data);
            return(accessor.ReadByte(ipcOffsetRemote));
        }
Beispiel #21
0
        public void ReadThread()
        {
            try
            {
                while (true)
                {
                    while (receiverAccessor != null && receiverAccessor.ReadByte(0) != 1)
                    {
                        if (readCts.Token.IsCancellationRequested)
                        {
                            return;
                        }
                        Thread.Sleep(1); // await Task.Delay(1);
                    }
                    if (receiverAccessor == null)
                    {
                        return;
                    }

                    long position = 1;
                    //CommandType
                    var length = receiverAccessor.ReadInt32(position);
                    position += sizeof(int);
                    var typeNameArray = new byte[length];
                    receiverAccessor.ReadArray(position, typeNameArray, 0, typeNameArray.Length);
                    position += typeNameArray.Length;
                    //RequestID
                    length    = receiverAccessor.ReadInt32(position);
                    position += sizeof(int);
                    var requestIdArray = new byte[length];
                    receiverAccessor.ReadArray(position, requestIdArray, 0, requestIdArray.Length);
                    position += requestIdArray.Length;
                    //Data
                    length    = receiverAccessor.ReadInt32(position);
                    position += sizeof(int);
                    var dataArray = new byte[length];
                    receiverAccessor.ReadArray(position, dataArray, 0, dataArray.Length);
                    //Write finish flag
                    receiverAccessor.Write(0, (byte)0);

                    var commandType = PipeCommands.GetCommandType(Encoding.UTF8.GetString(typeNameArray));
                    var requestId   = Encoding.UTF8.GetString(requestIdArray);
                    var data        = BinarySerializer.Deserialize(dataArray, commandType);
                    if (WaitReceivedDictionary.ContainsKey(requestId))
                    {
                        WaitReceivedDictionary[requestId] = data;
                    }
                    else
                    {
                        ReceivedEvent?.Invoke(this, new DataReceivedEventArgs(commandType, requestId, data));
                    }
                }
            }
            catch (NullReferenceException) { }
        }
Beispiel #22
0
        public string SendCommand(object command, string requestId = null, bool needWait = false)
        {
            System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase SendCommand Enter [{command.GetType().Name}]");
            if (IsConnected == false)
            {
                return(null);
            }
            if (string.IsNullOrEmpty(requestId))
            {
                requestId = Guid.NewGuid().ToString();
            }
            var typeNameArray  = Encoding.UTF8.GetBytes(command.GetType().Name);
            var requestIdArray = Encoding.UTF8.GetBytes(requestId);
            var dataArray      = BinarySerializer.Serialize(command);

            System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase SendCommand StartWait [{command.GetType().Name}]");
            while (senderAccessor.ReadByte(0) == 1) // Wait finish flag
            {
                if (readCts.Token.IsCancellationRequested)
                {
                    return(null);
                }
                Thread.Sleep(1);// await Task.Delay(1);
            }
            //Need to wait requestID before send (because sometime return data very fast)
            if (needWait)
            {
                WaitReceivedDictionary.TryAdd(requestId, null);
            }
            System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase SendCommand EndWait [{command.GetType().Name}]");
            long position = 1;

            //CommandType
            senderAccessor.Write(position, typeNameArray.Length);
            position += sizeof(int);
            senderAccessor.WriteArray(position, typeNameArray, 0, typeNameArray.Length);
            position += typeNameArray.Length;
            System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase SendCommand WriteCommandType [{command.GetType().Name}]");
            //RequestID
            senderAccessor.Write(position, requestIdArray.Length);
            position += sizeof(int);
            senderAccessor.WriteArray(position, requestIdArray, 0, requestIdArray.Length);
            position += requestIdArray.Length;
            System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase SendCommand WriteRequestID [{command.GetType().Name}]");
            //Data
            senderAccessor.Write(position, dataArray.Length);
            position += sizeof(int);
            senderAccessor.WriteArray(position, dataArray, 0, dataArray.Length);
            System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase SendCommand WriteData [{command.GetType().Name}]");
            //Write finish flag
            senderAccessor.Write(0, (byte)1);
            System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase SendCommand Write finish flag [{command.GetType().Name}]");

            return(requestId);
        }
Beispiel #23
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public byte ReadByte(long inPosition)
 {
     try
     {
         return(_sharedMemoryAccesor.ReadByte(inPosition));
     }
     catch
     {
         return(0);
     }
 }
Beispiel #24
0
    public static void CreateNew_DelayAllocatePages_ReadWrite()
    {
        int capacity = 4096 * 10000;

        using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(
                   null, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, HandleInheritability.None))
        {
            foreach (int viewCapacity in new[] { 0, 1, 4096, capacity })
            {
                using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(0, viewCapacity, MemoryMappedFileAccess.ReadWrite))
                {
                    accessor.Write(0, (byte)42);
                    Assert.Equal(42, accessor.ReadByte(0));

                    accessor.Write(accessor.Capacity - 1, (byte)84);
                    Assert.Equal(84, accessor.ReadByte(accessor.Capacity - 1));
                }
            }
        }
    }
 public override byte ReadByte()
 {
     try
     {
         return(_accessor.ReadByte(_position++));
     }
     catch (ArgumentException)
     {
         throw new IOException("read past EOF");
     }
 }
Beispiel #26
0
            static int GetCStringLength(MemoryMappedViewAccessor va, long stringOffset)
            {
                var currentOffset = stringOffset;
                var currentLength = 0;

                while (va.ReadByte(currentOffset) != 0x00)
                {
                    currentLength++;
                    currentOffset++;
                }
                return(currentLength);
            }
Beispiel #27
0
        /// <summary>
        /// Gets control chars
        /// </summary>
        /// <param name="MemViewAccessor"></param>
        /// <returns></returns>
        private string GetControlArray(MemoryMappedViewAccessor MemViewAccessor)
        {
            string ControlCharSet = string.Empty;

            byte[] byteArrayControl = new byte[4];
            for (int i = 0; i < 4; i++)
            {
                byteArrayControl[i] = MemViewAccessor.ReadByte(i);
            }
            ControlCharSet = Encoding.ASCII.GetString(byteArrayControl);
            return(ControlCharSet);
        }
        public byte ReadByte(int line, int sample)
        {
            const int height = 30400;
            const int width  = 30400;
            const int stride = width;

            Debug.Assert(line >= 0 && line < height && sample >= 0 && sample < width);

            int index = line * stride + sample;

            return(_accessor.ReadByte(index));
        }
                public override int ReadByte()
                {
                    if (position >= length)
                    {
                        return(-1);
                    }

                    var result = accessor.ReadByte(position);

                    position++;

                    return(result);
                }
Beispiel #30
0
        /// <summary>
        /// Uncompresses a valid LZ77 file.
        /// </summary>
        /// <param name="header">The compression header of the original file.</param>
        /// <param name="original">The original file accessor.</param>
        /// <param name="uncompressed">The uncompressed file accessor to write to.</param>
        public static void Expand(CompressionHeader header, MemoryMappedViewAccessor original, MemoryMappedViewAccessor uncompressed)
        {
            var  extended  = header.Compression == CompressionType.ExtendedLZ77;
            var  uncompLen = uncompressed.Capacity;
            long origPos   = header.HeaderSize;
            long uncompPos = 0;

            while (uncompPos < uncompLen)
            {
                byte bit     = 8;
                var  control = original.ReadByte(origPos++);
                while (bit-- != 0 && uncompPos < uncompLen)
                {
                    if ((control & (1 << bit)) == 0)
                    {
                        uncompressed.Write(uncompPos++, original.ReadByte(origPos++));
                    }
                    else
                    {
                        var temp = original.ReadByte(origPos) >> 4;
                        var num  = !extended
                            ? temp + 3
                            : temp == 1
                                ? (((original.ReadByte(origPos++) & 0x0F) << 12) | (original.ReadByte(origPos++) << 4) |
                                   (original.ReadByte(origPos) >> 4)) + 0xFF + 0xF + 3
                                : temp == 0
                                    ? (((original.ReadByte(origPos++) & 0x0F) << 4) |
                                       (original.ReadByte(origPos) >> 4)) + 0xF + 2
                                    : temp + 1;
                        var offset = (((original.ReadByte(origPos++) & 0xF) << 8) | original.ReadByte(origPos++)) + 2;
                        while (uncompPos != uncompLen && num-- > 0)
                        {
                            uncompressed.Write(uncompPos++, uncompressed.ReadByte(uncompPos - offset));
                        }
                    }
                }
            }
        }
        /// <summary>Performs validation on a view accessor.</summary>
        /// <param name="accessor">The accessor to validate.</param>
        /// <param name="capacity">The capacity specified when creating the accessor.</param>
        /// <param name="access">The access specified when creating the accessor.</param>
        protected static void ValidateMemoryMappedViewAccessor(MemoryMappedViewAccessor accessor, long capacity, MemoryMappedFileAccess access)
        {
            // Validate the accessor and its handle
            Assert.NotNull(accessor);
            Assert.NotNull(accessor.SafeMemoryMappedViewHandle);
            Assert.Same(accessor.SafeMemoryMappedViewHandle, accessor.SafeMemoryMappedViewHandle);

            // Ensure its properties match the criteria specified when it was created
            Assert.InRange(capacity, 0, accessor.Capacity); // the capacity may be rounded up to page size, so all we guarantee is that the accessor's capacity >= capacity
            Assert.Equal(0, accessor.PointerOffset);

            // If it's supposed to be readable, try to read from it.
            // Otherwise, verify we can't.
            if (IsReadable(access))
            {
                Assert.True(accessor.CanRead);
                Assert.Equal(0, accessor.ReadByte(0));
                Assert.Equal(0, accessor.ReadByte(capacity - 1));
            }
            else
            {
                Assert.False(accessor.CanRead);
                Assert.Throws<NotSupportedException>(() => accessor.ReadByte(0));
            }

            // If it's supposed to be writable, try to write to it
            if (IsWritable(access) || access == MemoryMappedFileAccess.CopyOnWrite)
            {
                Assert.True(accessor.CanWrite);

                // Write some data
                accessor.Write(0, (byte)42);
                accessor.Write(capacity - 1, (byte)42);

                // If possible, ensure we can read it back
                if (IsReadable(access))
                {
                    Assert.Equal(42, accessor.ReadByte(0));
                    Assert.Equal(42, accessor.ReadByte(capacity - 1));
                }

                // Write 0 back where we wrote data
                accessor.Write(0, (byte)0);
                accessor.Write(capacity - 1, (byte)0);
            }
            else
            {
                Assert.False(accessor.CanWrite);
                Assert.Throws<NotSupportedException>(() => accessor.Write(0, (byte)0));
            }
        }