Beispiel #1
0
        public void DisposedTest()
        {
            var ms = new NativeMemoryStream(20);

            ms.Dispose();
            Assert.That(ms.CanRead, Is.False);
            Assert.That(ms.CanSeek, Is.False);
            Assert.That(ms.CanWrite, Is.False);
            Assert.That(() => ms.Capacity > 0, Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Read <int>(), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Read(typeof(int)), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Read(new byte[3], 0, 3), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.ReadByte(), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.ReadArray(typeof(byte), 1, false), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.ReadReference <int>(), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.ReadReference <string>(), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Seek(0, SeekOrigin.Begin), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.SetLength(20), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Write("X"), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Write("X", CharSet.Ansi), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Write(new[] { "X", "Y" }), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Write(new byte[3], 0, 3), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Write(new[] { 1, 2 }), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.Write(256), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.WriteByte(1), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.WriteObject(Guid.NewGuid()), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.WriteReference("X"), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.WriteReference(256), Throws.InstanceOf <ObjectDisposedException>());
            Assert.That(() => ms.WriteReferenceObject(Guid.NewGuid()), Throws.InstanceOf <ObjectDisposedException>());
        }
Beispiel #2
0
        public void RefStringTest()
        {
            using (var ms = new NativeMemoryStream(20, 20))
            {
                Assert.That(() => ms.WriteReference(""), Throws.Nothing);
                Assert.That(ms.Length, Is.EqualTo(2 + IntPtr.Size));
                Assert.That(ms.Position, Is.EqualTo(IntPtr.Size));
                Assert.That(ms.Capacity, Is.EqualTo(20));
                Assert.That(() => ms.WriteReference(testStr), Throws.Nothing);
                Assert.That(ms.Length, Is.EqualTo(24 + IntPtr.Size * 2));
                Assert.That(ms.Position, Is.EqualTo(IntPtr.Size * 2));
                Assert.That(() => ms.WriteReference((string)null), Throws.Nothing);
                Assert.That(ms.Length, Is.EqualTo(24 + IntPtr.Size * 3));
                Assert.That(ms.Position, Is.EqualTo(IntPtr.Size * 3));
                var ptrs = ms.Pointer.ToArray <IntPtr>(3);
                Assert.That(ptrs, Is.EquivalentTo(new[] { IntPtr.Zero, IntPtr.Zero, IntPtr.Zero }));
                ms.Flush();
                Assert.That(ms.Capacity, Is.EqualTo(40));
                ptrs = ms.Pointer.ToArray <IntPtr>(3);
                Assert.That(ptrs, Is.Not.EquivalentTo(new[] { IntPtr.Zero, IntPtr.Zero, IntPtr.Zero }));
                Assert.That(StringHelper.GetString(ptrs[0], ms.CharSet), Is.EqualTo(""));
                Assert.That(StringHelper.GetString(ptrs[1], ms.CharSet), Is.EqualTo(testStr));
                Assert.That(StringHelper.GetString(ptrs[2], ms.CharSet), Is.Null);

                TestContext.WriteLine(ms.Pointer.ToHexDumpString((int)ms.Length, 32));
                ms.Position = 0;

                Assert.That(ms.ReadReference <string>(), Is.EqualTo(string.Empty));
                Assert.That(ms.Position, Is.EqualTo(IntPtr.Size));
                Assert.That(ms.ReadReference <string>(), Is.EqualTo(testStr));
                Assert.That(ms.ReadReference <string>(), Is.Null);
                Assert.That(ms.Read <string>(), Is.EqualTo(string.Empty));
                Assert.That(ms.Read <string>(), Is.EqualTo(testStr));
            }
        }
Beispiel #3
0
 private ShaderMixinObjectId()
 {
     objectIdBuilder = new ObjectIdBuilder();
     buffer          = Marshal.AllocHGlobal(65536);
     memStream       = new NativeMemoryStream(buffer, 65536);
     writer          = new HashSerializationWriter(memStream);
     writer.Context.SerializerSelector = new SerializerSelector("Default", "Hash");
 }
Beispiel #4
0
        public void StringEnumTest()
        {
            var abc = new[] { "A", "B", "C" };
            var a_c = new[] { "A", null, "C" };

            using (var ms = new NativeMemoryStream(128, 128))
            {
                Assert.That(() => ms.Write(null, StringListPackMethod.Concatenated), Throws.Nothing);

                Assert.That(() => ms.Write(abc, StringListPackMethod.Concatenated), Throws.Nothing);
                var len = 14;
                var pos = len;
                Assert.That(len, Is.EqualTo(ms.Length).And.EqualTo(ms.Position));
                Assert.That(() => ms.Write(abc, StringListPackMethod.Packed), Throws.Nothing);
                Assert.That(len += 12 + IntPtr.Size * 3, Is.EqualTo(ms.Length));
                Assert.That(pos += IntPtr.Size * 3, Is.EqualTo(ms.Position));
                Assert.That(ms.Capacity, Is.EqualTo(128));
                Assert.That(() => ms.Write(a_c, StringListPackMethod.Concatenated), Throws.Exception);
                Assert.That(() => ms.Write(a_c, StringListPackMethod.Packed), Throws.Nothing);
                Assert.That(len += 8 + IntPtr.Size * 3, Is.EqualTo(ms.Length));
                Assert.That(pos += IntPtr.Size * 3, Is.EqualTo(ms.Position));
                Assert.That(ms.Capacity, Is.EqualTo(128));

                var testSz = 10;
                var strSz  = 50;
                var l      = new List <string>(testSz);
                for (var i = 0; i < testSz; i++)
                {
                    l.Add(new string('X', strSz));
                }
                Assert.That(() => ms.Write(l, StringListPackMethod.Concatenated), Throws.Nothing);
                var strLen = ((strSz + 1) * testSz + 1) * StringHelper.GetCharSize();
                Assert.That(len += strLen, Is.EqualTo(ms.Length));
                Assert.That(pos += strLen, Is.EqualTo(ms.Position));
                Assert.That(ms.Capacity, Is.GreaterThan(128));

                Assert.That(() => ms.Write(l, StringListPackMethod.Packed), Throws.Nothing);
                strLen           = (strSz + 1) * testSz * StringHelper.GetCharSize();
                Assert.That(len += strLen + IntPtr.Size * testSz, Is.EqualTo(ms.Length));
                Assert.That(pos += IntPtr.Size * testSz, Is.EqualTo(ms.Position));

                Assert.That(ms.Position, Is.LessThan(ms.Length));
                ms.Flush();
                Assert.That(ms.Position, Is.EqualTo(ms.Length));
                Assert.That(ms.Position, Is.LessThanOrEqualTo(ms.Capacity));

                ms.Position = 0;

                Assert.That(ms.ReadArray(typeof(string), abc.Length, false), Is.EquivalentTo(abc));
                Assert.That(ms.ReadArray(typeof(string), abc.Length, true), Is.EquivalentTo(abc));
                Assert.That(ms.ReadArray(typeof(string), a_c.Length, true), Is.EquivalentTo(a_c));
                Assert.That(ms.ReadArray <string>(l.Count, false), Is.EquivalentTo(l));
                Assert.That(ms.ReadArray <string>(l.Count, true), Is.EquivalentTo(l));

                l.Clear();
            }
        }
Beispiel #5
0
 public void SetLengthTest()
 {
     using (var m = new SafeHGlobalHandle(1000))
         using (var ms = new NativeMemoryStream((IntPtr)m, m.Size))
         {
             Assert.That(() => ms.SetLength(-1), Throws.TypeOf <ArgumentOutOfRangeException>());
             Assert.That(() => ms.SetLength(1001), Throws.Exception);
             Assert.That(() => ms.SetLength(100), Throws.Nothing);
         }
 }
Beispiel #6
0
        /// <summary>
        /// Create and Load a sound effect from an input wav stream.
        /// </summary>
        /// <param name="engine">Name of the audio engine in which to create the sound effect</param>
        /// <param name="stream">A stream corresponding to a wav file.</param>
        /// <returns>A new instance soundEffect ready to be played</returns>
        /// <exception cref="ArgumentNullException"><paramref name="engine"/> or <paramref name="stream"/> is null.</exception>
        /// <exception cref="NotSupportedException">The wave file or has more than 2 channels or is not encoded in 16bits.</exception>
        /// <exception cref="InvalidOperationException">The content of the stream does not correspond to a valid wave file.</exception>
        /// <exception cref="OutOfMemoryException">There is not enough memory anymore to load the specified file in memory. </exception>
        /// <exception cref="ObjectDisposedException">The audio engine has already been disposed</exception>
        /// <remarks>Supported WAV files' audio format is the 16bits PCM format.</remarks>
        public static SoundEffect Load(AudioEngine engine, Stream stream)
        {
            if (engine == null)
            {
                throw new ArgumentNullException("engine");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (engine.IsDisposed)
            {
                throw new ObjectDisposedException("Audio Engine");
            }

            // create a native memory stream to extract the lz4 audio stream.
            var newSdEff = new SoundEffect(engine)
            {
                nativeDataBuffer = Utilities.AllocateMemory((int)stream.Length)
            };

            var nativeStream = new NativeMemoryStream(newSdEff.nativeDataBuffer, stream.Length);

            stream.CopyTo(nativeStream);
            nativeStream.Position = 0;

            var waveStreamReader = new SoundStream(nativeStream);
            var waveFormat       = waveStreamReader.Format;

            if (waveFormat.Channels > 2)
            {
                throw new NotSupportedException("The wave file contains more than 2 data channels. Only mono and stereo formats are currently supported.");
            }

            if (waveFormat.Encoding != WaveFormatEncoding.Pcm || waveFormat.BitsPerSample != 16)
            {
                throw new NotSupportedException("The wave file audio format is not supported. Only 16bits PCM encoded formats are currently supported.");
            }

            newSdEff.WaveFormat   = waveFormat;
            newSdEff.WaveDataPtr  = newSdEff.nativeDataBuffer + (int)nativeStream.Position;
            newSdEff.WaveDataSize = (int)waveStreamReader.Length;
            newSdEff.Name         = "Sound Effect " + soundEffectCreationCount;

            newSdEff.AdaptAudioDataImpl();

            // register the sound to the AudioEngine so that it will be properly freed if AudioEngine is disposed before this.
            engine.RegisterSound(newSdEff);

            Interlocked.Increment(ref soundEffectCreationCount);

            return(newSdEff);
        }
Beispiel #7
0
 public void SeekTest()
 {
     using (var m = new SafeHGlobalHandle(1000))
         using (var ms = new NativeMemoryStream((IntPtr)m, m.Size))
         {
             Assert.That(ms.Seek(20, SeekOrigin.Begin), Is.EqualTo(20));
             Assert.That(ms.Seek(20, SeekOrigin.Current), Is.EqualTo(40));
             Assert.That(ms.Seek(-100, SeekOrigin.End), Is.EqualTo(900));
             Assert.That(() => ms.Seek(-1, SeekOrigin.Begin), Throws.ArgumentException);
             Assert.That(() => ms.Seek(1, SeekOrigin.End), Throws.ArgumentException);
         }
 }
Beispiel #8
0
        internal void Load(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (AudioEngine.IsDisposed)
            {
                throw new ObjectDisposedException("Audio Engine");
            }

            // create a native memory stream to extract the lz4 audio stream.
            nativeDataBuffer = Utilities.AllocateMemory((int)stream.Length);

            var nativeStream = new NativeMemoryStream(nativeDataBuffer, stream.Length);

            stream.CopyTo(nativeStream);
            nativeStream.Position = 0;

            var waveStreamReader = new SoundStream(nativeStream);
            var waveFormat       = waveStreamReader.Format;

            if (waveFormat.Channels > 2)
            {
                throw new NotSupportedException("The wave file contains more than 2 data channels. Only mono and stereo formats are currently supported.");
            }

            if (waveFormat.Encoding != WaveFormatEncoding.Pcm || waveFormat.BitsPerSample != 16)
            {
                throw new NotSupportedException("The wave file audio format is not supported. Only 16bits PCM encoded formats are currently supported.");
            }

            WaveFormat   = waveFormat;
            WaveDataPtr  = nativeDataBuffer + (int)nativeStream.Position;
            WaveDataSize = (int)waveStreamReader.Length;
            Name         = "Sound Effect " + soundEffectCreationCount;

            AdaptAudioDataImpl();

            // register the sound to the AudioEngine so that it will be properly freed if AudioEngine is disposed before this.
            AudioEngine.RegisterSound(this);

            //create a default instance only when actually we load, previously we were creating this on demand which would result sometimes in useless creations and bugs within the editor
            DefaultInstance = CreateInstance();
            //copy back values we might have set before default instance creation
            DefaultInstance.Pan      = defaultPan;
            DefaultInstance.Volume   = defaultVolume;
            DefaultInstance.IsLooped = defaultIsLooped;

            Interlocked.Increment(ref soundEffectCreationCount);
        }
Beispiel #9
0
        public void CapacityTest()
        {
            using (var ms = new NativeMemoryStream(10, 10, 20))
            {
                Assert.That(ms.Capacity, Is.EqualTo(10));
                ms.Write(Guid.NewGuid());
                Assert.That(ms.Capacity, Is.EqualTo(20));
                Assert.That(ms.Length, Is.EqualTo(16));

                Assert.That(() => ms.EnsureCapacity(-100), Throws.TypeOf <ArgumentOutOfRangeException>());
                Assert.That(() => ms.EnsureCapacity(40), Throws.TypeOf <ArgumentOutOfRangeException>());
            }
        }
Beispiel #10
0
        public void AmsiNotifyOperationTest()
        {
            using var hsess = new SafeHAMSISESSION(Guid.NewGuid().ToString());
            var fn = TestCaseSources.BmpFile;

            using var fs  = File.OpenRead(fn);
            using var mem = new NativeMemoryStream();
            fs.CopyTo(mem);
            Assert.That(AmsiNotifyOperation(hsess.Context, mem.Pointer, (uint)mem.Length, fn, out var ret), ResultIs.Successful);
            Assert.IsFalse(AmsiResultIsMalware(ret));
            Assert.That(AmsiScanBuffer(hsess.Context, mem.Pointer, (uint)mem.Length, fn, hsess, out ret), ResultIs.Successful);
            Assert.IsFalse(AmsiResultIsMalware(ret));
        }
Beispiel #11
0
 public void NativeMemoryStreamTest(int sz)
 {
     using (var ms = new NativeMemoryStream(sz))
     {
         if (sz <= 0)
         {
             Assert.That(() => ms.Capacity, Throws.Exception);
         }
         else
         {
             Assert.That(ms.Capacity, Is.EqualTo(sz));
         }
     }
 }
Beispiel #12
0
        public void PropTest()
        {
            using (var m = new SafeHGlobalHandle(1000))
                using (var ms = new NativeMemoryStream((IntPtr)m, m.Size))
                {
                    Assert.That(ms.Capacity, Is.EqualTo(1000));
                    Assert.That(ms.CanWrite, Is.False);
                    Assert.That(ms.CanSeek, Is.True);
                    Assert.That(ms.CanRead, Is.True);
                    Assert.That(ms.Length, Is.EqualTo(0));

                    Assert.That(() => ms.EnsureCapacity(2000), Throws.InvalidOperationException);
                }
        }
Beispiel #13
0
        public void StructEnumTest()
        {
            using (var ms = new NativeMemoryStream(48, 16))
            {
                var arr = new[] { 1L, 2L, 3L, 4L, 5L, 6L };
                Assert.That(() => ms.Write(arr), Throws.Nothing);
                var sz = sizeof(long) * arr.Length;
                Assert.That(ms.Length, Is.EqualTo(sz));
                Assert.That(ms.Position, Is.EqualTo(sz));
                Assert.That(ms.Capacity, Is.EqualTo(48));

                var list = new List <int> {
                    1, 2, 3
                };
                Assert.That(() => ms.Write(list), Throws.Nothing);
                sz += sizeof(int) * list.Count;
                Assert.That(ms.Length, Is.EqualTo(sz));
                Assert.That(ms.Position, Is.EqualTo(sz));
                Assert.That(ms.Capacity, Is.EqualTo(64));

                var pos = ms.Position;
                Assert.That(() => ms.Write(arr, true), Throws.Nothing);
                sz  += (sizeof(long) + IntPtr.Size) * arr.Length;
                pos += IntPtr.Size * arr.Length;
                Assert.That(ms.Length, Is.EqualTo(sz));
                Assert.That(ms.Position, Is.EqualTo(pos));
                Assert.That(ms.Capacity, Is.EqualTo(144));

                Assert.That(() => ms.Write(list, true), Throws.Nothing);
                sz  += (sizeof(int) + IntPtr.Size) * list.Count;
                pos += IntPtr.Size * list.Count;
                Assert.That(ms.Length, Is.EqualTo(sz));
                Assert.That(ms.Position, Is.EqualTo(pos));
                Assert.That(ms.Capacity, Is.EqualTo(160));

                ms.Flush();
                ms.Position = 0;

                Assert.That(() => ms.ReadArray(null, 0, false), Throws.ArgumentNullException);
                Assert.That(() => ms.ReadArray(typeof(int), -1, false), Throws.InstanceOf <ArgumentOutOfRangeException>());
                Assert.That(() => ms.ReadArray(typeof(int), 0, false), Throws.Nothing);
                Assert.That(ms.ReadArray(typeof(int), 0, false).Length, Is.Zero);
                Assert.That(() => ms.ReadArray(typeof(Guid), 100, false), Throws.InstanceOf <ArgumentOutOfRangeException>());

                Assert.That(ms.ReadArray(typeof(long), arr.Length, false), Is.EquivalentTo(arr));
                Assert.That(ms.ReadArray <int>(list.Count, false), Is.EquivalentTo(list));
                Assert.That(ms.ReadArray <long>(arr.Length, true), Is.EquivalentTo(arr));
                Assert.That(ms.ReadArray(typeof(int), list.Count, true), Is.EquivalentTo(list));
            }
        }
        private ShaderMixinObjectId()
        {
            objectIdBuilder = new ObjectIdBuilder();
            buffer          = Marshal.AllocHGlobal(65536);
            memStream       = new NativeMemoryStream(buffer, 65536);
            writer          = new HashSerializationWriter(memStream);
            writer.Context.SerializerSelector = new SerializerSelector();
            writer.Context.SerializerSelector.RegisterProfile("Default");
            writer.Context.SerializerSelector.RegisterSerializer(new ParameterKeyHashSerializer());
            writer.Context.SerializerSelector.RegisterSerializer(new ParameterCollectionHashSerializer());

            if (parameters == null)
            {
                parameters = new ParameterCollection();
            }
        }
Beispiel #15
0
 public void NativeMemoryStreamTest2()
 {
     using (var m = new SafeHGlobalHandle(10))
     {
         Assert.That(() => new NativeMemoryStream(null, 10, 20), Throws.ArgumentNullException);
         using (var ms = new NativeMemoryStream(m, 10, 20))
         {
             Assert.That(ms.Capacity, Is.EqualTo(10));
             Assert.That(ms.MaxCapacity, Is.EqualTo(20));
             Assert.That(ms.Pointer, Is.EqualTo((IntPtr)m));
             Assert.That(() => ms.Write(Guid.NewGuid()), Throws.Nothing);
             Assert.That(ms.Capacity, Is.EqualTo(20));
             Assert.That(() => ms.Write(Guid.NewGuid()), Throws.Exception);
         }
     }
 }
Beispiel #16
0
        /// <summary>
        /// Marshals data from a managed list of strings to an unmanaged block of memory allocated by the <paramref name="memAlloc"/> method.
        /// </summary>
        /// <param name="values">The enumerated list of strings to marshal.</param>
        /// <param name="packing">The packing type for the strings.</param>
        /// <param name="memAlloc">
        /// The function that allocates the memory for the block of strings (typically <see cref="Marshal.AllocCoTaskMem(int)"/> or <see cref="Marshal.AllocHGlobal(int)"/>.
        /// </param>
        /// <param name="bytesAllocated">The bytes allocated by the <paramref name="memAlloc"/> method.</param>
        /// <param name="charSet">The character set to use for the strings.</param>
        /// <param name="prefixBytes">Number of bytes preceding the trailing strings.</param>
        /// <returns>
        /// Pointer to the allocated native (unmanaged) array of strings stored using the <paramref name="packing"/> model and the character
        /// set defined by <paramref name="charSet"/>.
        /// </returns>
        public static IntPtr MarshalToPtr(this IEnumerable <string> values, StringListPackMethod packing, Func <int, IntPtr> memAlloc, out int bytesAllocated, CharSet charSet = CharSet.Auto, int prefixBytes = 0)
        {
            // Bail early if empty
            if (values is null || !values.Any())
            {
                bytesAllocated = prefixBytes + (packing == StringListPackMethod.Concatenated ? StringHelper.GetCharSize(charSet) : IntPtr.Size);
                var ret = memAlloc(bytesAllocated);
                ret.FillMemory(0, bytesAllocated);
                return(ret);
            }

            // Write to memory stream
            using (var ms = new NativeMemoryStream(1024, 1024)
            {
                CharSet = charSet
            })
            {
                ms.SetLength(ms.Position = prefixBytes);
                if (packing == StringListPackMethod.Packed)
                {
                    foreach (var s in values)
                    {
                        ms.WriteReference(s);
                    }
                    ms.WriteReference(null);
                }
                else
                {
                    foreach (var s in values)
                    {
                        if (string.IsNullOrEmpty(s))
                        {
                            throw new ArgumentException("Concatenated string arrays cannot contain empty or null strings.");
                        }
                        ms.Write(s);
                    }
                    ms.Write("");
                }
                ms.Flush();

                // Copy to newly allocated memory using memAlloc
                bytesAllocated = (int)ms.Length;
                var ret = memAlloc(bytesAllocated);
                ms.Pointer.CopyTo(ret, bytesAllocated);
                return(ret);
            }
        }
Beispiel #17
0
        public void BytesTest()
        {
            using (var ms = new NativeMemoryStream(20, 10))
            {
                Assert.That(ms.Length, Is.EqualTo(0));
                Assert.That(() => ms.Write(null, 0, 0), Throws.ArgumentNullException);
                var bytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 3 };
                Assert.That(() => ms.Write(bytes, 1, 8), Throws.ArgumentException);
                Assert.That(() => ms.Write(bytes, -1, 8), Throws.TypeOf <ArgumentOutOfRangeException>());
                Assert.That(() => ms.Write(bytes, 1, -8), Throws.TypeOf <ArgumentOutOfRangeException>());
                Assert.That(() => ms.Write(bytes, 0, 8), Throws.Nothing);
                Assert.That(ms.Length, Is.EqualTo(8));
                Assert.That(ms.Position, Is.EqualTo(8));
                Assert.That(ms.Capacity, Is.EqualTo(20));
                var ones = new byte[22];
                for (var i = 0; i < ones.Length; i++)
                {
                    ones[i] = 1;
                }
                Array.ForEach(ones, b => b = 1);
                Assert.That(() => ms.Write(ones, 0, ones.Length), Throws.Nothing);
                Assert.That(ms.Length, Is.EqualTo(30));
                Assert.That(ms.Position, Is.EqualTo(30));
                Assert.That(ms.Capacity, Is.EqualTo(30));

                ms.Flush();
                ms.Position = 0;

                Assert.That(() => ms.Read(null, 0, 0), Throws.ArgumentNullException);
                var rbytes = new byte[bytes.Length];
                Assert.That(() => ms.Read(rbytes, 5, bytes.Length), Throws.ArgumentException);
                Assert.That(() => ms.Read(rbytes, -1, 1), Throws.InstanceOf <ArgumentOutOfRangeException>());
                Assert.That(() => ms.Read(rbytes, 0, -1), Throws.InstanceOf <ArgumentOutOfRangeException>());
                Assert.That(ms.Read(rbytes, 0, bytes.Length), Is.EqualTo(bytes.Length));
                Assert.That(rbytes, Is.EquivalentTo(bytes));
                Assert.That(ms.Position, Is.EqualTo(bytes.Length));
                rbytes = new byte[ms.Length];
                Assert.That(() => ms.Read(rbytes, (int)ms.Position, 40), Throws.ArgumentException);
                Assert.That(ms.Read(rbytes, (int)ms.Position, ones.Length), Is.EqualTo(ones.Length));
                for (var i = bytes.Length; i < ms.Position; i++)
                {
                    Assert.That(rbytes[i], Is.EqualTo(1));
                }
                Assert.That(() => ms.Read(rbytes, 0, 2), Throws.InstanceOf <ArgumentOutOfRangeException>());
            }
        }
Beispiel #18
0
        public void StructTest()
        {
            using (var ms = new NativeMemoryStream(8, 16, 48))
            {
                Assert.That(() => ms.Write(256), Throws.Nothing);
                var isz = sizeof(int);
                Assert.That(ms.Length, Is.EqualTo(Len()));
                Assert.That(ms.Position, Is.EqualTo(Pos()));
                Assert.That(ms.Capacity, Is.EqualTo(8));
                Assert.That(() => ms.Write((ushort)256), Throws.Nothing);
                isz += sizeof(ushort);
                Assert.That(ms.Length, Is.EqualTo(Len()));
                Assert.That(ms.Position, Is.EqualTo(Pos()));
                Assert.That(ms.Capacity, Is.EqualTo(8));
                Assert.That(() => ms.Write((long)1), Throws.Nothing);
                isz += sizeof(long);
                Assert.That(ms.Length, Is.EqualTo(Len()));
                Assert.That(ms.Position, Is.EqualTo(Pos()));
                Assert.That(ms.Capacity, Is.EqualTo(24));
                var newGuid = Guid.NewGuid();
                Assert.That(() => ms.Write(newGuid), Throws.Nothing);
                isz += Marshal.SizeOf(typeof(Guid));
                Assert.That(ms.Length, Is.EqualTo(Len()));
                Assert.That(ms.Position, Is.EqualTo(Pos()));
                Assert.That(ms.Capacity, Is.EqualTo(40));

                Assert.That(ms.Length, Is.EqualTo(ms.Position));
                Assert.That(ms.Capacity, Is.GreaterThanOrEqualTo(ms.Length));

                Assert.That(() => ms.Write(new Unblittable()), Throws.Exception);

                TestContext.WriteLine(ms.Pointer.ToHexDumpString((int)ms.Length, 32));
                ms.Position = 0;

                Assert.That(() => ms.Read(null), Throws.ArgumentNullException);

                Assert.That(ms.Read <int>(), Is.EqualTo(256));
                Assert.That(ms.Read <ushort>(), Is.EqualTo(256));
                Assert.That(ms.Read <long>(), Is.EqualTo(1));
                Assert.That(ms.Read <Guid>(), Is.EqualTo(newGuid));

                int Len() => isz;
                int Pos() => isz;
            }
        }
Beispiel #19
0
        public void RefStructTest()
        {
            using (var ms = new NativeMemoryStream(8, 16, 100))
            {
                Assert.That(() => ms.WriteReference(256), Throws.Nothing);
                var isz  = sizeof(int);
                var pcnt = 1;
                Assert.That(ms.Length, Is.EqualTo(Len()));
                Assert.That(ms.Position, Is.EqualTo(Pos()));
                Assert.That(ms.Capacity, Is.EqualTo(8));
                Assert.That(() => ms.WriteReference((ushort)256), Throws.Nothing);
                isz += sizeof(ushort); pcnt++;
                Assert.That(ms.Length, Is.EqualTo(Len()));
                Assert.That(ms.Position, Is.EqualTo(Pos()));
                Assert.That(ms.Capacity, Is.EqualTo(24));
                Assert.That(() => ms.WriteReference((long)1), Throws.Nothing);
                isz += sizeof(long); pcnt++;
                Assert.That(ms.Length, Is.EqualTo(Len()));
                Assert.That(ms.Position, Is.EqualTo(Pos()));
                Assert.That(ms.Capacity, Is.EqualTo(40));
                Assert.That(ms.Pointer.ToArray(IntPtr.Size == 4 ? typeof(uint) : typeof(ulong), pcnt), Is.EquivalentTo(new[] { 0, 0, 0 }));
                var newGuid = Guid.NewGuid();
                Assert.That(() => ms.WriteReference(newGuid), Throws.Nothing);
                isz += Marshal.SizeOf(typeof(Guid)); pcnt++;
                Assert.That(ms.Length, Is.EqualTo(Len()));
                Assert.That(ms.Position, Is.EqualTo(Pos()));
                Assert.That(ms.Capacity, Is.EqualTo(56));
                ms.Flush();
                Assert.That(ms.Length, Is.EqualTo(ms.Position));
                Assert.That(ms.Capacity, Is.GreaterThanOrEqualTo(ms.Length));
                var arr = ms.Pointer.ToArray(IntPtr.Size == 4 ? typeof(uint) : typeof(ulong), pcnt);
                Assert.That(arr, Is.Not.EquivalentTo(new[] { 0, 0, 0, 0 }));

                ms.Position = 0;

                Assert.That(ms.ReadReference <int>(), Is.EqualTo(256));
                Assert.That(ms.ReadReference <ushort>(), Is.EqualTo(256));
                Assert.That(ms.ReadReference <long>(), Is.EqualTo(1));
                Assert.That(ms.ReadReference <Guid>(), Is.EqualTo(newGuid));

                int Len() => Pos() + isz;
                int Pos() => pcnt *IntPtr.Size;
            }
        }
Beispiel #20
0
        /// <summary>
        /// Marshals data from a managed list of objects to an unmanaged block of memory allocated by the <paramref name="memAlloc"/> method.
        /// </summary>
        /// <param name="values">The enumerated list of objects to marshal.</param>
        /// <param name="memAlloc">
        /// The function that allocates the memory for the block of objects (typically <see cref="Marshal.AllocCoTaskMem(int)"/> or <see cref="Marshal.AllocHGlobal(int)"/>.
        /// </param>
        /// <param name="bytesAllocated">The bytes allocated by the <paramref name="memAlloc"/> method.</param>
        /// <param name="referencePointers">
        /// if set to <see langword="true"/> the pointer will be processed by storing a reference to the value; if <see langword="false"/>,
        /// the pointer value will be directly inserted into the array of pointers.
        /// </param>
        /// <param name="charSet">The character set to use for strings.</param>
        /// <param name="prefixBytes">Number of bytes preceding the allocated objects.</param>
        /// <returns>Pointer to the allocated native (unmanaged) array of objects stored using the character set defined by <paramref name="charSet"/>.</returns>
        public static IntPtr MarshalObjectsToPtr(this IEnumerable <object> values, Func <int, IntPtr> memAlloc, out int bytesAllocated, bool referencePointers = false, CharSet charSet = CharSet.Auto, int prefixBytes = 0)
        {
            // Bail early if empty
            if (values is null || !values.Any())
            {
                bytesAllocated = prefixBytes + IntPtr.Size;
                var ret = memAlloc(bytesAllocated);
                ret.FillMemory(0, bytesAllocated);
                return(ret);
            }

            // Write to memory stream
            using (var ms = new NativeMemoryStream(1024, 1024)
            {
                CharSet = charSet
            })
            {
                ms.SetLength(ms.Position = prefixBytes);
                foreach (var o in values)
                {
                    if (referencePointers)
                    {
                        ms.WriteReferenceObject(o);
                    }
                    else
                    {
                        ms.WriteObject(o);
                    }
                }
                if (referencePointers)
                {
                    ms.WriteReference(null);
                }
                ms.Flush();

                // Copy to newly allocated memory using memAlloc
                bytesAllocated = (int)ms.Length;
                var ret = memAlloc(bytesAllocated);
                ms.Pointer.CopyTo(ret, bytesAllocated);
                return(ret);
            }
        }
Beispiel #21
0
        public void StringTest()
        {
            using (var ms = new NativeMemoryStream(20))
            {
                Assert.That(() => ms.Write(""), Throws.Nothing);
                Assert.That(ms.Length, Is.EqualTo(2));
                Assert.That(ms.Position, Is.EqualTo(2));
                Assert.That(ms.Capacity, Is.EqualTo(20));
                Assert.That(() => ms.Write(testStr), Throws.Nothing);
                Assert.That(ms.Length, Is.EqualTo(24));
                Assert.That(ms.Position, Is.EqualTo(24));
                Assert.That(ms.Capacity, Is.GreaterThan(20));

                ms.Flush();
                ms.Position = 0;

                Assert.That(ms.Read <string>(), Is.EqualTo(string.Empty));
                Assert.That(ms.Position, Is.EqualTo(StringHelper.GetCharSize(ms.CharSet)));
                Assert.That(ms.Read <string>(), Is.EqualTo(testStr));
            }
        }
Beispiel #22
0
        public void MixedReadWriteTest()
        {
            using (var m = new SafeHGlobalHandle(512))
            {
                var  str  = "Test1";
                var  guid = Guid.NewGuid();
                var  lVal = 1208L;
                byte b    = 18;
                using (var ms = new NativeMemoryStream(m)
                {
                    CharSet = CharSet.Unicode
                })
                {
                    Assert.That(() => ms.WriteReference(str), Throws.Nothing);
                    Assert.That(() => ms.Write(str), Throws.Nothing);
                    Assert.That(() => ms.WriteReference(guid), Throws.Nothing);
                    Assert.That(() => ms.Write(guid), Throws.Nothing);
                    Assert.That(() => ms.WriteReference(lVal), Throws.Nothing);
                    Assert.That(() => ms.Write(lVal), Throws.Nothing);
                    Assert.That(() => ms.WriteReference(b), Throws.Nothing);
                    Assert.That(() => ms.Write(b), Throws.Nothing);
                    Assert.That(() => ms.WriteReference(str), Throws.Nothing);

                    ms.Flush();
                    ms.Position = 0;

                    Assert.That(ms.ReadReference <string>(CharSet.Unicode), Is.EqualTo(str));
                    Assert.That(ms.Read <string>(CharSet.Unicode), Is.EqualTo(str));
                    Assert.That(ms.ReadReference <Guid>(), Is.EqualTo(guid));
                    Assert.That(ms.Read <Guid>(), Is.EqualTo(guid));
                    Assert.That(ms.ReadReference <long>(), Is.EqualTo(lVal));
                    Assert.That(ms.Read <long>(), Is.EqualTo(lVal));
                    Assert.That(ms.ReadReference <byte>(), Is.EqualTo(b));
                    Assert.That(ms.Read <byte>(), Is.EqualTo(b));
                    Assert.That(ms.ReadReference <string>(CharSet.Unicode), Is.EqualTo(str));
                }
            }
        }
Beispiel #23
0
 private static Bitmap GetTransparentBitmap(HBITMAP hbitmap)
 {
     try
     {
         var dibsection = GetObject <BITMAP>(hbitmap);
         var bitmap     = new Bitmap(dibsection.bmWidth, dibsection.bmHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
         using var mstr = new NativeMemoryStream(dibsection.bmBits, dibsection.bmBitsPixel * dibsection.bmHeight * dibsection.bmWidth);
         for (var x = 0; x < dibsection.bmWidth; x++)
         {
             for (var y = 0; y < dibsection.bmHeight; y++)
             {
                 var rgbquad = mstr.Read <RGBQUAD>();
                 if (rgbquad.rgbReserved != 0)
                 {
                     bitmap.SetPixel(x, y, rgbquad.Color);
                 }
             }
         }
         return(bitmap);
     }
     catch { }
     return(Image.FromHbitmap((IntPtr)hbitmap));
 }
Beispiel #24
0
        public void ReadWriteOnlyTest()
        {
            using (var m = new SafeHGlobalHandle(10))
                using (var ms = new NativeMemoryStream((IntPtr)m, m.Size))
                {
                    Assert.That(ms.CanWrite, Is.False);
                    Assert.That(ms.CanSeek, Is.True);
                    Assert.That(ms.CanRead, Is.True);

                    Assert.That(() => ms.Write("X"), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.Write("X", CharSet.Ansi), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.Write(new[] { "X", "Y" }), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.Write(new byte[3], 0, 3), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.Write(new[] { 1, 2 }), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.Write(256), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.WriteByte(1), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.WriteObject(Guid.NewGuid()), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.WriteReference("X"), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.WriteReference(256), Throws.InstanceOf <NotSupportedException>());
                    Assert.That(() => ms.WriteReferenceObject(Guid.NewGuid()), Throws.InstanceOf <NotSupportedException>());
                }

            using (var ms = new NativeMemoryStream(10, 10, 20, FileAccess.Write))
            {
                Assert.That(ms.CanWrite, Is.True);
                Assert.That(ms.CanSeek, Is.True);
                Assert.That(ms.CanRead, Is.False);

                Assert.That(() => ms.Read <int>(), Throws.InstanceOf <NotSupportedException>());
                Assert.That(() => ms.Read(typeof(int)), Throws.InstanceOf <NotSupportedException>());
                Assert.That(() => ms.Read(new byte[3], 0, 3), Throws.InstanceOf <NotSupportedException>());
                Assert.That(() => ms.ReadByte(), Throws.InstanceOf <NotSupportedException>());
                Assert.That(() => ms.ReadArray(typeof(byte), 1, false), Throws.InstanceOf <NotSupportedException>());
                Assert.That(() => ms.ReadReference <int>(), Throws.InstanceOf <NotSupportedException>());
                Assert.That(() => ms.ReadReference <string>(), Throws.InstanceOf <NotSupportedException>());
            }
        }
Beispiel #25
0
        /// <summary>
        /// Creates a in-memory binary blob as a <see cref="Blob"/> that will also be stored using the active <see cref="IOdbBackend"/>.
        /// Even if <see cref="Blob"/> is new (not in the ODB), memory will be copied.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="size">The size.</param>
        /// <returns>The <see cref="Blob"/> containing given data, with its reference count incremented.</returns>
        public Blob CreateBlob(IntPtr data, int size)
        {
            // Generate hash
            ObjectId objectId;
            var      nativeMemoryStream = new NativeMemoryStream(data, size);

            using (var digestStream = new DigestStream(Stream.Null))
            {
                nativeMemoryStream.CopyTo(digestStream);
                objectId = digestStream.CurrentHash;
            }

            lock (LoadedBlobs)
            {
                var blob = Lookup(objectId);

                // Blob doesn't exist yet, so let's create it and save it to ODB.
                if (blob == null)
                {
                    // Let's go back to beginning of stream after previous hash
                    nativeMemoryStream.Position = 0;

                    // Create blob
                    blob = new Blob(this, objectId, data, size);
                    blob.AddReference();

                    // Write to disk
                    backendWrite.Write(objectId, nativeMemoryStream, size, false);

                    // Add blob to cache
                    LoadedBlobs.Add(objectId, blob);
                }

                return(blob);
            }
        }