http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs deleted file mode 100644 index 265fd0d..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs +++ /dev/null @@ -1,438 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Reflection; - using System.Runtime.InteropServices; - using System.Text; - using Apache.Ignite.Core.Cluster; - using Apache.Ignite.Core.Common; - using Apache.Ignite.Core.Impl.Cluster; - using Apache.Ignite.Core.Impl.Common; - using Apache.Ignite.Core.Impl.Portable; - using Apache.Ignite.Core.Impl.Unmanaged; - using Apache.Ignite.Core.Portable; - - /// <summary> - /// Native utility methods. - /// </summary> - internal static class IgniteUtils - { - /** Environment variable: JAVA_HOME. */ - private const string EnvJavaHome = "JAVA_HOME"; - - /** Directory: jre. */ - private const string DirJre = "jre"; - - /** Directory: bin. */ - private const string DirBin = "bin"; - - /** Directory: server. */ - private const string DirServer = "server"; - - /** File: jvm.dll. */ - private const string FileJvmDll = "jvm.dll"; - - /** File: Ignite.Common.dll. */ - internal const string FileIgniteJniDll = "ignite.common.dll"; - - /** Prefix for temp directory names. */ - private const string DirIgniteTmp = "Ignite_"; - - /** Loaded. */ - private static bool _loaded; - - /** Thread-local random. */ - [ThreadStatic] - private static Random _rnd; - - /// <summary> - /// Initializes the <see cref="IgniteUtils"/> class. - /// </summary> - static IgniteUtils() - { - TryCleanTempDirectories(); - } - - /// <summary> - /// Gets thread local random. - /// </summary> - /// <returns>Thread local random.</returns> - public static Random ThreadLocalRandom() - { - if (_rnd == null) - _rnd = new Random(); - - return _rnd; - } - - /// <summary> - /// Returns shuffled list copy. - /// </summary> - /// <returns>Shuffled list copy.</returns> - public static IList<T> Shuffle<T>(IList<T> list) - { - int cnt = list.Count; - - if (cnt > 1) { - List<T> res = new List<T>(list); - - Random rnd = ThreadLocalRandom(); - - while (cnt > 1) - { - cnt--; - - int idx = rnd.Next(cnt + 1); - - T val = res[idx]; - res[idx] = res[cnt]; - res[cnt] = val; - } - - return res; - } - return list; - } - - /// <summary> - /// Load JVM DLL if needed. - /// </summary> - /// <param name="configJvmDllPath">JVM DLL path from config.</param> - public static void LoadDlls(string configJvmDllPath) - { - if (_loaded) return; - - // 1. Load JNI dll. - LoadJvmDll(configJvmDllPath); - - // 2. Load GG JNI dll. - UnmanagedUtils.Initialize(); - - _loaded = true; - } - - /// <summary> - /// Create new instance of specified class. - /// </summary> - /// <param name="assemblyName">Assembly name.</param> - /// <param name="clsName">Class name</param> - /// <returns>New Instance.</returns> - public static object CreateInstance(string assemblyName, string clsName) - { - IgniteArgumentCheck.NotNullOrEmpty(clsName, "clsName"); - - var type = new TypeResolver().ResolveType(clsName, assemblyName); - - if (type == null) - throw new IgniteException("Failed to create class instance [assemblyName=" + assemblyName + - ", className=" + clsName + ']'); - - return Activator.CreateInstance(type); - } - - /// <summary> - /// Set properties on the object. - /// </summary> - /// <param name="target">Target object.</param> - /// <param name="props">Properties.</param> - public static void SetProperties(object target, IEnumerable<KeyValuePair<string, object>> props) - { - if (props == null) - return; - - IgniteArgumentCheck.NotNull(target, "target"); - - Type typ = target.GetType(); - - foreach (KeyValuePair<string, object> prop in props) - { - PropertyInfo prop0 = typ.GetProperty(prop.Key, - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - - if (prop0 == null) - throw new IgniteException("Property is not found [type=" + typ.Name + - ", property=" + prop.Key + ']'); - - prop0.SetValue(target, prop.Value, null); - } - } - - /// <summary> - /// Loads the JVM DLL. - /// </summary> - private static void LoadJvmDll(string configJvmDllPath) - { - var messages = new List<string>(); - foreach (var dllPath in GetJvmDllPaths(configJvmDllPath)) - { - var errCode = LoadDll(dllPath.Value, FileJvmDll); - if (errCode == 0) - return; - - messages.Add(string.Format("[option={0}, path={1}, errorCode={2}]", - dllPath.Key, dllPath.Value, errCode)); - - if (dllPath.Value == configJvmDllPath) - break; // if configJvmDllPath is specified and is invalid - do not try other options - } - - if (!messages.Any()) // not loaded and no messages - everything was null - messages.Add(string.Format("Please specify IgniteConfiguration.JvmDllPath or {0}.", EnvJavaHome)); - - if (messages.Count == 1) - throw new IgniteException(string.Format("Failed to load {0} ({1})", FileJvmDll, messages[0])); - - var combinedMessage = messages.Aggregate((x, y) => string.Format("{0}\n{1}", x, y)); - throw new IgniteException(string.Format("Failed to load {0}:\n{1}", FileJvmDll, combinedMessage)); - } - - /// <summary> - /// Try loading DLLs first using file path, then using it's simple name. - /// </summary> - /// <param name="filePath"></param> - /// <param name="simpleName"></param> - /// <returns>Zero in case of success, error code in case of failure.</returns> - private static int LoadDll(string filePath, string simpleName) - { - int res = 0; - - IntPtr ptr; - - if (filePath != null) - { - ptr = NativeMethods.LoadLibrary(filePath); - - if (ptr == IntPtr.Zero) - res = Marshal.GetLastWin32Error(); - else - return res; - } - - // Failed to load using file path, fallback to simple name. - ptr = NativeMethods.LoadLibrary(simpleName); - - if (ptr == IntPtr.Zero) - { - // Preserve the first error code, if any. - if (res == 0) - res = Marshal.GetLastWin32Error(); - } - else - res = 0; - - return res; - } - - /// <summary> - /// Gets the JVM DLL paths in order of lookup priority. - /// </summary> - private static IEnumerable<KeyValuePair<string, string>> GetJvmDllPaths(string configJvmDllPath) - { - if (!string.IsNullOrEmpty(configJvmDllPath)) - yield return new KeyValuePair<string, string>("IgniteConfiguration.JvmDllPath", configJvmDllPath); - - var javaHomeDir = Environment.GetEnvironmentVariable(EnvJavaHome); - - if (!string.IsNullOrEmpty(javaHomeDir)) - yield return - new KeyValuePair<string, string>(EnvJavaHome, GetJvmDllPath(Path.Combine(javaHomeDir, DirJre))); - } - - /// <summary> - /// Gets the JVM DLL path from JRE dir. - /// </summary> - private static string GetJvmDllPath(string jreDir) - { - return Path.Combine(jreDir, DirBin, DirServer, FileJvmDll); - } - - /// <summary> - /// Unpacks an embedded resource into a temporary folder and returns the full path of resulting file. - /// </summary> - /// <param name="resourceName">Resource name.</param> - /// <returns>Path to a temp file with an unpacked resource.</returns> - public static string UnpackEmbeddedResource(string resourceName) - { - var dllRes = Assembly.GetExecutingAssembly().GetManifestResourceNames() - .Single(x => x.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase)); - - return WriteResourceToTempFile(dllRes, resourceName); - } - - /// <summary> - /// Writes the resource to temporary file. - /// </summary> - /// <param name="resource">The resource.</param> - /// <param name="name">File name prefix</param> - /// <returns>Path to the resulting temp file.</returns> - private static string WriteResourceToTempFile(string resource, string name) - { - // Dll file name should not be changed, so we create a temp folder with random name instead. - var file = Path.Combine(GetTempDirectoryName(), name); - - using (var src = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)) - using (var dest = File.OpenWrite(file)) - { - // ReSharper disable once PossibleNullReferenceException - src.CopyTo(dest); - - return file; - } - } - - /// <summary> - /// Tries to clean temporary directories created with <see cref="GetTempDirectoryName"/>. - /// </summary> - private static void TryCleanTempDirectories() - { - foreach (var dir in Directory.GetDirectories(Path.GetTempPath(), DirIgniteTmp + "*")) - { - try - { - Directory.Delete(dir, true); - } - catch (IOException) - { - // Expected - } - catch (UnauthorizedAccessException) - { - // Expected - } - } - } - - /// <summary> - /// Creates a uniquely named, empty temporary directory on disk and returns the full path of that directory. - /// </summary> - /// <returns>The full path of the temporary directory.</returns> - private static string GetTempDirectoryName() - { - while (true) - { - var dir = Path.Combine(Path.GetTempPath(), DirIgniteTmp + Path.GetRandomFileName()); - - try - { - return Directory.CreateDirectory(dir).FullName; - } - catch (IOException) - { - // Expected - } - catch (UnauthorizedAccessException) - { - // Expected - } - } - } - - /// <summary> - /// Convert unmanaged char array to string. - /// </summary> - /// <param name="chars">Char array.</param> - /// <param name="charsLen">Char array length.</param> - /// <returns></returns> - public static unsafe string Utf8UnmanagedToString(sbyte* chars, int charsLen) - { - IntPtr ptr = new IntPtr(chars); - - if (ptr == IntPtr.Zero) - return null; - - byte[] arr = new byte[charsLen]; - - Marshal.Copy(ptr, arr, 0, arr.Length); - - return Encoding.UTF8.GetString(arr); - } - - /// <summary> - /// Convert string to unmanaged byte array. - /// </summary> - /// <param name="str">String.</param> - /// <returns>Unmanaged byte array.</returns> - public static unsafe sbyte* StringToUtf8Unmanaged(string str) - { - var ptr = IntPtr.Zero; - - if (str != null) - { - byte[] strBytes = Encoding.UTF8.GetBytes(str); - - ptr = Marshal.AllocHGlobal(strBytes.Length + 1); - - Marshal.Copy(strBytes, 0, ptr, strBytes.Length); - - *((byte*)ptr.ToPointer() + strBytes.Length) = 0; // NULL-terminator. - } - - return (sbyte*)ptr.ToPointer(); - } - - /// <summary> - /// Reads node collection from stream. - /// </summary> - /// <param name="reader">Reader.</param> - /// <param name="pred">The predicate.</param> - /// <returns> Nodes list or null. </returns> - public static List<IClusterNode> ReadNodes(IPortableRawReader reader, Func<ClusterNodeImpl, bool> pred = null) - { - var cnt = reader.ReadInt(); - - if (cnt < 0) - return null; - - var res = new List<IClusterNode>(cnt); - - var ignite = ((PortableReaderImpl)reader).Marshaller.Ignite; - - if (pred == null) - { - for (var i = 0; i < cnt; i++) - res.Add(ignite.GetNode(reader.ReadGuid())); - } - else - { - for (var i = 0; i < cnt; i++) - { - var node = ignite.GetNode(reader.ReadGuid()); - - if (pred(node)) - res.Add(node); - } - } - - return res; - } - - /// <summary> - /// Gets the asynchronous mode disabled exception. - /// </summary> - /// <returns>Asynchronous mode disabled exception.</returns> - public static InvalidOperationException GetAsyncModeDisabledException() - { - return new InvalidOperationException("Asynchronous mode is disabled"); - } - } -}
http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/InteropExceptionHolder.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/InteropExceptionHolder.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/InteropExceptionHolder.cs deleted file mode 100644 index 98d57da..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/InteropExceptionHolder.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl -{ - using System; - using System.Runtime.Serialization.Formatters.Binary; - using Apache.Ignite.Core.Impl.Portable; - using Apache.Ignite.Core.Impl.Portable.IO; - using Apache.Ignite.Core.Portable; - - /// <summary> - /// Holder of exception which must be serialized to Java and then backwards to the native platform. - /// </summary> - internal class InteropExceptionHolder : IPortableMarshalAware - { - /** Initial exception. */ - private Exception _err; - - /// <summary> - /// Constructor. - /// </summary> - public InteropExceptionHolder() - { - // No-op. - } - - /// <summary> - /// Constructor. - /// </summary> - /// <param name="err">Error.</param> - public InteropExceptionHolder(Exception err) - { - _err = err; - } - - /// <summary> - /// Underlying exception. - /// </summary> - public Exception Error - { - get { return _err; } - } - - /** <inheritDoc /> */ - public void WritePortable(IPortableWriter writer) - { - var writer0 = (PortableWriterImpl) writer.RawWriter(); - - if (writer0.IsPortable(_err)) - { - writer0.WriteBoolean(true); - writer0.WriteObject(_err); - } - else - { - writer0.WriteBoolean(false); - - BinaryFormatter bf = new BinaryFormatter(); - - bf.Serialize(new PortableStreamAdapter(writer0.Stream), _err); - } - } - - /** <inheritDoc /> */ - public void ReadPortable(IPortableReader reader) - { - throw new NotImplementedException(); - } - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/LifecycleBeanHolder.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/LifecycleBeanHolder.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/LifecycleBeanHolder.cs deleted file mode 100644 index cce4ec5..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/LifecycleBeanHolder.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl -{ - using Apache.Ignite.Core.Impl.Resource; - using Apache.Ignite.Core.Lifecycle; - - /// <summary> - /// Lifecycle bean holder. - /// </summary> - internal class LifecycleBeanHolder : ILifecycleBean - { - /** Target bean. */ - private readonly ILifecycleBean _target; - - /** Whether start event was invoked. */ - private volatile bool _startEvt; - - /// <summary> - /// Constructor. - /// </summary> - /// <param name="target">Target bean.</param> - public LifecycleBeanHolder(ILifecycleBean target) - { - _target = target; - } - - /** <inheritDoc /> */ - public void OnLifecycleEvent(LifecycleEventType evt) - { - if (evt == LifecycleEventType.AfterNodeStart) - // This event cannot be propagated right away because at this point we - // do not have Ignite instance yet. So just schedule it. - _startEvt = true; - else - _target.OnLifecycleEvent(evt); - } - - /// <summary> - /// Grid start callback. - /// </summary> - /// <param name="grid">Ignite instance.</param> - internal void OnStart(Ignite grid) - { - ResourceProcessor.Inject(_target, grid); - - if (_startEvt) - _target.OnLifecycleEvent(LifecycleEventType.AfterNodeStart); - } - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/IPlatformMemory.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/IPlatformMemory.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/IPlatformMemory.cs deleted file mode 100644 index 93fd164..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/IPlatformMemory.cs +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - using System; - - /// <summary> - /// Platform memory chunk. - /// </summary> - [CLSCompliant(false)] - public interface IPlatformMemory - { - /// <summary> - /// Gets stream for read/write operations on the given memory chunk. - /// </summary> - /// <returns></returns> - PlatformMemoryStream Stream(); - - /// <summary> - /// Cross-platform pointer. - /// </summary> - long Pointer { get; } - - /// <summary> - /// Data pointer. - /// </summary> - long Data { get; } - - /// <summary> - /// CalculateCapacity. - /// </summary> - int Capacity { get; } - - /// <summary> - /// Length. - /// </summary> - int Length { get; set; } - - /// <summary> - /// Reallocates memory chunk. - /// </summary> - /// <param name="cap">Minimum capacity.</param> - void Reallocate(int cap); - - /// <summary> - /// Release memory. - /// </summary> - void Release(); - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/InteropExternalMemory.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/InteropExternalMemory.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/InteropExternalMemory.cs deleted file mode 100644 index d356b5e..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/InteropExternalMemory.cs +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - /// <summary> - /// Interop external memory chunk. - /// </summary> - internal class InteropExternalMemory : PlatformMemory - { - /// <summary> - /// Constructor. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - public InteropExternalMemory(long memPtr) : base(memPtr) - { - // No-op. - } - - /** <inheritdoc /> */ - public override void Reallocate(int cap) - { - InteropMemoryUtils.ReallocateExternal(Pointer, cap); - } - - /** <inheritdoc /> */ - public override void Release() - { - // Memory can only be released by native platform. - } - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/InteropMemoryUtils.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/InteropMemoryUtils.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/InteropMemoryUtils.cs deleted file mode 100644 index 485d3db..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/InteropMemoryUtils.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - using Apache.Ignite.Core.Impl.Unmanaged; - - /// <summary> - /// Utility methods for interop memory management. - /// </summary> - internal static class InteropMemoryUtils - { - /// <summary> - /// Re-allocate external memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <param name="cap">CalculateCapacity.</param> - /// <returns>New memory pointer.</returns> - public static void ReallocateExternal(long memPtr, int cap) - { - UnmanagedUtils.Reallocate(memPtr, cap); - } - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformBigEndianMemoryStream.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformBigEndianMemoryStream.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformBigEndianMemoryStream.cs deleted file mode 100644 index 33a0487..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformBigEndianMemoryStream.cs +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - /// <summary> - /// Platform memory stream for big endian platforms. - /// </summary> - internal class PlatformBigEndianMemoryStream : PlatformMemoryStream - { - /// <summary> - /// Constructor. - /// </summary> - /// <param name="mem"></param> - public PlatformBigEndianMemoryStream(IPlatformMemory mem) : base(mem) - { - // No-op. - } - - #region WRITE - - /** <inheritDoc /> */ - public override unsafe void WriteShort(short val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(Len2); - - byte* valPtr = (byte*)&val; - - curPos[0] = valPtr[1]; - curPos[1] = valPtr[0]; - } - - /** <inheritDoc /> */ - public override unsafe void WriteShortArray(short[] val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift2); - - for (int i = 0; i < val.Length; i++) - { - short val0 = val[i]; - - byte* valPtr = (byte*)&(val0); - - *curPos++ = valPtr[1]; - *curPos++ = valPtr[0]; - } - } - - /** <inheritDoc /> */ - public override unsafe void WriteChar(char val) - { - WriteShort(*(short*)(&val)); - } - - /** <inheritDoc /> */ - public override unsafe void WriteCharArray(char[] val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift2); - - for (int i = 0; i < val.Length; i++) - { - char val0 = val[i]; - - byte* valPtr = (byte*)&(val0); - - *curPos++ = valPtr[1]; - *curPos++ = valPtr[0]; - } - } - - /** <inheritDoc /> */ - public override unsafe void WriteInt(int val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(Len4); - - byte* valPtr = (byte*)&val; - - curPos[0] = valPtr[3]; - curPos[1] = valPtr[2]; - curPos[2] = valPtr[1]; - curPos[3] = valPtr[0]; - } - - /** <inheritDoc /> */ - public override unsafe void WriteInt(int writePos, int val) - { - EnsureWriteCapacity(writePos + 4); - - byte* curPos = Data + writePos; - - byte* valPtr = (byte*)&val; - - curPos[0] = valPtr[3]; - curPos[1] = valPtr[2]; - curPos[2] = valPtr[1]; - curPos[3] = valPtr[0]; - } - - /** <inheritDoc /> */ - public override unsafe void WriteIntArray(int[] val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift4); - - for (int i = 0; i < val.Length; i++) - { - int val0 = val[i]; - - byte* valPtr = (byte*)&(val0); - - *curPos++ = valPtr[3]; - *curPos++ = valPtr[2]; - *curPos++ = valPtr[1]; - *curPos++ = valPtr[0]; - } - } - - /** <inheritDoc /> */ - public override unsafe void WriteLong(long val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(Len8); - - byte* valPtr = (byte*)&val; - - curPos[0] = valPtr[7]; - curPos[1] = valPtr[6]; - curPos[2] = valPtr[5]; - curPos[3] = valPtr[4]; - curPos[4] = valPtr[3]; - curPos[5] = valPtr[2]; - curPos[6] = valPtr[1]; - curPos[7] = valPtr[0]; - } - - /** <inheritDoc /> */ - public override unsafe void WriteLongArray(long[] val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift8); - - for (int i = 0; i < val.Length; i++) - { - long val0 = val[i]; - - byte* valPtr = (byte*)&(val0); - - *curPos++ = valPtr[7]; - *curPos++ = valPtr[6]; - *curPos++ = valPtr[5]; - *curPos++ = valPtr[4]; - *curPos++ = valPtr[3]; - *curPos++ = valPtr[2]; - *curPos++ = valPtr[1]; - *curPos++ = valPtr[0]; - } - } - - /** <inheritDoc /> */ - public override unsafe void WriteFloat(float val) - { - WriteInt(*(int*)(&val)); - } - - /** <inheritDoc /> */ - public override unsafe void WriteFloatArray(float[] val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift4); - - for (int i = 0; i < val.Length; i++) - { - float val0 = val[i]; - - byte* valPtr = (byte*)&(val0); - - *curPos++ = valPtr[3]; - *curPos++ = valPtr[2]; - *curPos++ = valPtr[1]; - *curPos++ = valPtr[0]; - } - } - - /** <inheritDoc /> */ - public override unsafe void WriteDouble(double val) - { - WriteLong(*(long*)(&val)); - } - - /** <inheritDoc /> */ - public override unsafe void WriteDoubleArray(double[] val) - { - byte* curPos = Data + EnsureWriteCapacityAndShift(val.Length << Shift8); - - for (int i = 0; i < val.Length; i++) - { - double val0 = val[i]; - - byte* valPtr = (byte*)&(val0); - - *curPos++ = valPtr[7]; - *curPos++ = valPtr[6]; - *curPos++ = valPtr[5]; - *curPos++ = valPtr[4]; - *curPos++ = valPtr[3]; - *curPos++ = valPtr[2]; - *curPos++ = valPtr[1]; - *curPos++ = valPtr[0]; - } - } - - #endregion - - #region READ - - /** <inheritDoc /> */ - public override unsafe short ReadShort() - { - int curPos = EnsureReadCapacityAndShift(Len2); - - short val; - - byte* valPtr = (byte*)&val; - - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos); - - return val; - } - - /** <inheritDoc /> */ - public override unsafe short[] ReadShortArray(int len) - { - int curPos = EnsureReadCapacityAndShift(len << Shift2); - - short[] res = new short[len]; - - for (int i = 0; i < len; i++) - { - short val; - - byte* valPtr = (byte*)&val; - - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos++); - - res[i] = val; - } - - return res; - } - - /** <inheritDoc /> */ - public override unsafe char ReadChar() - { - int curPos = EnsureReadCapacityAndShift(Len2); - - char val; - - byte* valPtr = (byte*)&val; - - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos); - - return val; - } - - /** <inheritDoc /> */ - public override unsafe char[] ReadCharArray(int len) - { - int curPos = EnsureReadCapacityAndShift(len << Shift2); - - char[] res = new char[len]; - - for (int i = 0; i < len; i++) - { - char val; - - byte* valPtr = (byte*)&val; - - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos++); - - res[i] = val; - } - - return res; - } - - /** <inheritDoc /> */ - public override unsafe int ReadInt() - { - int curPos = EnsureReadCapacityAndShift(Len4); - - int val; - - byte* valPtr = (byte*)&val; - - valPtr[3] = *(Data + curPos++); - valPtr[2] = *(Data + curPos++); - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos); - - return val; - } - - /** <inheritDoc /> */ - public override unsafe int[] ReadIntArray(int len) - { - int curPos = EnsureReadCapacityAndShift(len << Shift4); - - int[] res = new int[len]; - - for (int i = 0; i < len; i++) - { - int val; - - byte* valPtr = (byte*)&val; - - valPtr[3] = *(Data + curPos++); - valPtr[2] = *(Data + curPos++); - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos++); - - res[i] = val; - } - - return res; - } - - /** <inheritDoc /> */ - public override unsafe long ReadLong() - { - int curPos = EnsureReadCapacityAndShift(Len8); - - long val; - - byte* valPtr = (byte*)&val; - - valPtr[7] = *(Data + curPos++); - valPtr[6] = *(Data + curPos++); - valPtr[5] = *(Data + curPos++); - valPtr[4] = *(Data + curPos++); - valPtr[3] = *(Data + curPos++); - valPtr[2] = *(Data + curPos++); - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos); - - return val; - } - - /** <inheritDoc /> */ - - public override unsafe long[] ReadLongArray(int len) - { - int curPos = EnsureReadCapacityAndShift(len << Shift8); - - long[] res = new long[len]; - - for (int i = 0; i < len; i++) - { - long val; - - byte* valPtr = (byte*) &val; - - valPtr[7] = *(Data + curPos++); - valPtr[6] = *(Data + curPos++); - valPtr[5] = *(Data + curPos++); - valPtr[4] = *(Data + curPos++); - valPtr[3] = *(Data + curPos++); - valPtr[2] = *(Data + curPos++); - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos++); - - res[i] = val; - } - - return res; - } - - /** <inheritDoc /> */ - public override unsafe float ReadFloat() - { - int curPos = EnsureReadCapacityAndShift(Len4); - - float val; - - byte* valPtr = (byte*)&val; - - valPtr[3] = *(Data + curPos++); - valPtr[2] = *(Data + curPos++); - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos); - - return val; - } - - /** <inheritDoc /> */ - public override unsafe float[] ReadFloatArray(int len) - { - int curPos = EnsureReadCapacityAndShift(len << Shift4); - - float[] res = new float[len]; - - for (int i = 0; i < len; i++) - { - float val; - - byte* valPtr = (byte*)&val; - - valPtr[3] = *(Data + curPos++); - valPtr[2] = *(Data + curPos++); - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos++); - - res[i] = val; - } - - return res; - } - - /** <inheritDoc /> */ - public override unsafe double ReadDouble() - { - int curPos = EnsureReadCapacityAndShift(Len8); - - double val; - - byte* valPtr = (byte*)&val; - - valPtr[7] = *(Data + curPos++); - valPtr[6] = *(Data + curPos++); - valPtr[5] = *(Data + curPos++); - valPtr[4] = *(Data + curPos++); - valPtr[3] = *(Data + curPos++); - valPtr[2] = *(Data + curPos++); - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos); - - return val; - } - - /** <inheritDoc /> */ - public override unsafe double[] ReadDoubleArray(int len) - { - int curPos = EnsureReadCapacityAndShift(len << Shift8); - - double[] res = new double[len]; - - for (int i = 0; i < len; i++) - { - double val; - - byte* valPtr = (byte*)&val; - - valPtr[7] = *(Data + curPos++); - valPtr[6] = *(Data + curPos++); - valPtr[5] = *(Data + curPos++); - valPtr[4] = *(Data + curPos++); - valPtr[3] = *(Data + curPos++); - valPtr[2] = *(Data + curPos++); - valPtr[1] = *(Data + curPos++); - valPtr[0] = *(Data + curPos++); - - res[i] = val; - } - - return res; - } - - #endregion - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemory.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemory.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemory.cs deleted file mode 100644 index 3a9ed26..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemory.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - using System; - - /// <summary> - /// Abstract memory chunk. - /// </summary> - [CLSCompliant(false)] - public abstract class PlatformMemory : IPlatformMemory - { - /** Memory pointer. */ - protected readonly long MemPtr; - - /// <summary> - /// Constructor. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - protected PlatformMemory(long memPtr) - { - MemPtr = memPtr; - } - - /** <inheritdoc /> */ - public virtual PlatformMemoryStream Stream() - { - return BitConverter.IsLittleEndian ? new PlatformMemoryStream(this) : - new PlatformBigEndianMemoryStream(this); - } - - /** <inheritdoc /> */ - public long Pointer - { - get { return MemPtr; } - } - - /** <inheritdoc /> */ - public long Data - { - get { return PlatformMemoryUtils.Data(MemPtr); } - } - - /** <inheritdoc /> */ - public int Capacity - { - get { return PlatformMemoryUtils.Capacity(MemPtr); } - } - - /** <inheritdoc /> */ - public int Length - { - get { return PlatformMemoryUtils.Length(MemPtr); } - set { PlatformMemoryUtils.Length(MemPtr, value); } - } - - /** <inheritdoc /> */ - public abstract void Reallocate(int cap); - - /** <inheritdoc /> */ - public abstract void Release(); - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryManager.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryManager.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryManager.cs deleted file mode 100644 index b280140..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryManager.cs +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Threading; - - /// <summary> - /// Memory manager implementation. - /// </summary> - [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", - Justification = "This class instance usually lives as long as the app runs.")] - [CLSCompliant(false)] - public class PlatformMemoryManager - { - /** Default capacity. */ - private readonly int _dfltCap; - - /** Thread-local pool. */ - private readonly ThreadLocal<PlatformMemoryPool> _threadLocPool = new ThreadLocal<PlatformMemoryPool>(); - - /// <summary> - /// Constructor. - /// </summary> - /// <param name="dfltCap">Default capacity.</param> - public PlatformMemoryManager(int dfltCap) - { - _dfltCap = dfltCap; - } - - /// <summary> - /// Allocate memory. - /// </summary> - /// <returns>Memory.</returns> - public IPlatformMemory Allocate() - { - return Allocate(_dfltCap); - } - - /// <summary> - /// Allocate memory having at least the given capacity. - /// </summary> - /// <param name="cap">Minimum capacity.</param> - /// <returns>Memory.</returns> - public IPlatformMemory Allocate(int cap) - { - return Pool().Allocate(cap); - } - - /// <summary> - /// Gets memory from existing pointer. - /// </summary> - /// <param name="memPtr">Cross-platform memory pointer.</param> - /// <returns>Memory.</returns> - public IPlatformMemory Get(long memPtr) - { - int flags = PlatformMemoryUtils.Flags(memPtr); - - return PlatformMemoryUtils.IsExternal(flags) ? GetExternalMemory(memPtr) - : PlatformMemoryUtils.IsPooled(flags) ? Pool().Get(memPtr) : new PlatformUnpooledMemory(memPtr); - } - - /// <summary> - /// Gets or creates thread-local memory pool. - /// </summary> - /// <returns>Memory pool.</returns> - public PlatformMemoryPool Pool() - { - PlatformMemoryPool pool = _threadLocPool.Value; - - if (pool == null) - { - pool = new PlatformMemoryPool(); - - _threadLocPool.Value = pool; - } - - return pool; - } - - /// <summary> - /// Gets the external memory. - /// </summary> - /// <param name="memPtr">Cross-platform memory pointer.</param> - /// <returns>Memory.</returns> - protected virtual IPlatformMemory GetExternalMemory(long memPtr) - { - return new InteropExternalMemory(memPtr); - } - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryPool.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryPool.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryPool.cs deleted file mode 100644 index 75e8965..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryPool.cs +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - using System; - using Microsoft.Win32.SafeHandles; - - /// <summary> - /// Platform memory pool. - /// </summary> - [CLSCompliant(false)] - public class PlatformMemoryPool : SafeHandleMinusOneIsInvalid - { - /** First pooled memory chunk. */ - private PlatformPooledMemory _mem1; - - /** Second pooled memory chunk. */ - private PlatformPooledMemory _mem2; - - /** Third pooled memory chunk. */ - private PlatformPooledMemory _mem3; - - /// <summary> - /// Constructor. - /// </summary> - public PlatformMemoryPool() : base(true) - { - handle = (IntPtr)PlatformMemoryUtils.AllocatePool(); - } - - /// <summary> - /// Allocate memory chunk, optionally pooling it. - /// </summary> - /// <param name="cap">Minimum capacity.</param> - /// <returns>Memory chunk</returns> - public PlatformMemory Allocate(int cap) - { - var memPtr = PlatformMemoryUtils.AllocatePooled(handle.ToInt64(), cap); - - // memPtr == 0 means that we failed to acquire thread-local memory chunk, so fallback to unpooled memory. - return memPtr != 0 ? Get(memPtr) : new PlatformUnpooledMemory(PlatformMemoryUtils.AllocateUnpooled(cap)); - } - - /// <summary> - /// Re-allocate existing pool memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <param name="cap">Minimum capacity.</param> - public void Reallocate(long memPtr, int cap) - { - PlatformMemoryUtils.ReallocatePooled(memPtr, cap); - } - - /// <summary> - /// Release pooled memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - public void Release(long memPtr) - { - PlatformMemoryUtils.ReleasePooled(memPtr); - } - - /// <summary> - /// Get pooled memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <returns>Memory chunk.</returns> - public PlatformMemory Get(long memPtr) - { - long delta = memPtr - handle.ToInt64(); - - if (delta == PlatformMemoryUtils.PoolHdrOffMem1) - return _mem1 ?? (_mem1 = new PlatformPooledMemory(this, memPtr)); - - if (delta == PlatformMemoryUtils.PoolHdrOffMem2) - return _mem2 ?? (_mem2 = new PlatformPooledMemory(this, memPtr)); - - return _mem3 ?? (_mem3 = new PlatformPooledMemory(this, memPtr)); - } - - /** <inheritdoc /> */ - protected override bool ReleaseHandle() - { - PlatformMemoryUtils.ReleasePool(handle.ToInt64()); - - handle = new IntPtr(-1); - - return true; - } - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryStream.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryStream.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryStream.cs deleted file mode 100644 index 71da18f..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryStream.cs +++ /dev/null @@ -1,677 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - using System; - using System.IO; - using System.Text; - using Apache.Ignite.Core.Impl.Portable.IO; - - /// <summary> - /// Platform memory stream. - /// </summary> - [CLSCompliant(false)] - public unsafe class PlatformMemoryStream : IPortableStream - { - /** Length: 1 byte. */ - protected const int Len1 = 1; - - /** Length: 2 bytes. */ - protected const int Len2 = 2; - - /** Length: 4 bytes. */ - protected const int Len4 = 4; - - /** Length: 8 bytes. */ - protected const int Len8 = 8; - - /** Shift: 2 bytes. */ - protected const int Shift2 = 1; - - /** Shift: 4 bytes. */ - protected const int Shift4 = 2; - - /** Shift: 8 bytes. */ - protected const int Shift8 = 3; - - /** Underlying memory. */ - private readonly IPlatformMemory _mem; - - /** Actual data. */ - protected byte* Data; - - /** CalculateCapacity. */ - private int _cap; - - /** Position. */ - private int _pos; - - /** Length. */ - private int _len; - - /// <summary> - /// Constructor. - /// </summary> - /// <param name="mem">Memory.</param> - public PlatformMemoryStream(IPlatformMemory mem) - { - _mem = mem; - - Data = (byte*)mem.Data; - _cap = mem.Capacity; - _len = mem.Length; - } - - #region WRITE - - /** <inheritdoc /> */ - public void WriteByte(byte val) - { - int curPos = EnsureWriteCapacityAndShift(Len1); - - *(Data + curPos) = val; - } - - /** <inheritdoc /> */ - public void WriteByteArray(byte[] val) - { - fixed (byte* val0 = val) - { - CopyFromAndShift(val0, val.Length); - } - } - - /** <inheritdoc /> */ - public void WriteBool(bool val) - { - WriteByte(val ? (byte)1 : (byte)0); - } - - /** <inheritdoc /> */ - public void WriteBoolArray(bool[] val) - { - fixed (bool* val0 = val) - { - CopyFromAndShift((byte*)val0, val.Length); - } - } - - /** <inheritdoc /> */ - public virtual void WriteShort(short val) - { - int curPos = EnsureWriteCapacityAndShift(Len2); - - *((short*)(Data + curPos)) = val; - } - - /** <inheritdoc /> */ - public virtual void WriteShortArray(short[] val) - { - fixed (short* val0 = val) - { - CopyFromAndShift((byte*)val0, val.Length << Shift2); - } - } - - /** <inheritdoc /> */ - public virtual void WriteChar(char val) - { - int curPos = EnsureWriteCapacityAndShift(Len2); - - *((char*)(Data + curPos)) = val; - } - - /** <inheritdoc /> */ - public virtual void WriteCharArray(char[] val) - { - fixed (char* val0 = val) - { - CopyFromAndShift((byte*)val0, val.Length << Shift2); - } - } - - /** <inheritdoc /> */ - public virtual void WriteInt(int val) - { - int curPos = EnsureWriteCapacityAndShift(Len4); - - *((int*)(Data + curPos)) = val; - } - - /** <inheritdoc /> */ - public virtual void WriteInt(int writePos, int val) - { - EnsureWriteCapacity(writePos + 4); - - *((int*)(Data + writePos)) = val; - } - - /** <inheritdoc /> */ - public virtual void WriteIntArray(int[] val) - { - fixed (int* val0 = val) - { - CopyFromAndShift((byte*)val0, val.Length << Shift4); - } - } - - /** <inheritdoc /> */ - public virtual void WriteLong(long val) - { - int curPos = EnsureWriteCapacityAndShift(Len8); - - *((long*)(Data + curPos)) = val; - } - - /** <inheritdoc /> */ - public virtual void WriteLongArray(long[] val) - { - fixed (long* val0 = val) - { - CopyFromAndShift((byte*)val0, val.Length << Shift8); - } - } - - /** <inheritdoc /> */ - public virtual void WriteFloat(float val) - { - int curPos = EnsureWriteCapacityAndShift(Len4); - - *((float*)(Data + curPos)) = val; - } - - /** <inheritdoc /> */ - public virtual void WriteFloatArray(float[] val) - { - fixed (float* val0 = val) - { - CopyFromAndShift((byte*)val0, val.Length << Shift4); - } - } - - /** <inheritdoc /> */ - public virtual void WriteDouble(double val) - { - int curPos = EnsureWriteCapacityAndShift(Len8); - - *((double*)(Data + curPos)) = val; - } - - /** <inheritdoc /> */ - public virtual void WriteDoubleArray(double[] val) - { - fixed (double* val0 = val) - { - CopyFromAndShift((byte*)val0, val.Length << Shift8); - } - } - - /** <inheritdoc /> */ - public int WriteString(char* chars, int charCnt, int byteCnt, Encoding enc) - { - int curPos = EnsureWriteCapacityAndShift(byteCnt); - - return enc.GetBytes(chars, charCnt, Data + curPos, byteCnt); - } - - /** <inheritdoc /> */ - public void Write(byte[] src, int off, int cnt) - { - fixed (byte* src0 = src) - { - CopyFromAndShift(src0 + off, cnt); - } - } - - /** <inheritdoc /> */ - public void Write(byte* src, int cnt) - { - CopyFromAndShift(src, cnt); - } - - #endregion WRITE - - #region READ - - /** <inheritdoc /> */ - public byte ReadByte() - { - int curPos = EnsureReadCapacityAndShift(Len1); - - return *(Data + curPos); - } - - /** <inheritdoc /> */ - - public byte[] ReadByteArray(int cnt) - { - int curPos = EnsureReadCapacityAndShift(cnt); - - byte[] res = new byte[cnt]; - - fixed (byte* res0 = res) - { - PlatformMemoryUtils.CopyMemory(Data + curPos, res0, cnt); - } - - return res; - } - - /** <inheritdoc /> */ - public bool ReadBool() - { - return ReadByte() == 1; - } - - /** <inheritdoc /> */ - public bool[] ReadBoolArray(int cnt) - { - bool[] res = new bool[cnt]; - - fixed (bool* res0 = res) - { - CopyToAndShift((byte*)res0, cnt); - } - - return res; - } - - /** <inheritdoc /> */ - public virtual short ReadShort() - { - int curPos = EnsureReadCapacityAndShift(Len2); - - return *((short*)(Data + curPos)); - } - - /** <inheritdoc /> */ - public virtual short[] ReadShortArray(int cnt) - { - short[] res = new short[cnt]; - - fixed (short* res0 = res) - { - CopyToAndShift((byte*)res0, cnt << Shift2); - } - - return res; - } - - /** <inheritdoc /> */ - public virtual char ReadChar() - { - int curPos = EnsureReadCapacityAndShift(Len2); - - return *((char*)(Data + curPos)); - } - - /** <inheritdoc /> */ - public virtual char[] ReadCharArray(int cnt) - { - char[] res = new char[cnt]; - - fixed (char* res0 = res) - { - CopyToAndShift((byte*)res0, cnt << Shift2); - } - - return res; - } - - /** <inheritdoc /> */ - public virtual int ReadInt() - { - int curPos = EnsureReadCapacityAndShift(Len4); - - return *((int*)(Data + curPos)); - } - - /** <inheritdoc /> */ - public virtual int[] ReadIntArray(int cnt) - { - int[] res = new int[cnt]; - - fixed (int* res0 = res) - { - CopyToAndShift((byte*)res0, cnt << Shift4); - } - - return res; - } - - /** <inheritdoc /> */ - public virtual long ReadLong() - { - int curPos = EnsureReadCapacityAndShift(Len8); - - return *((long*)(Data + curPos)); - } - - /** <inheritdoc /> */ - public virtual long[] ReadLongArray(int cnt) - { - long[] res = new long[cnt]; - - fixed (long* res0 = res) - { - CopyToAndShift((byte*)res0, cnt << Shift8); - } - - return res; - } - - /** <inheritdoc /> */ - public virtual float ReadFloat() - { - int curPos = EnsureReadCapacityAndShift(Len4); - - return *((float*)(Data + curPos)); - } - - /** <inheritdoc /> */ - public virtual float[] ReadFloatArray(int cnt) - { - float[] res = new float[cnt]; - - fixed (float* res0 = res) - { - CopyToAndShift((byte*)res0, cnt << Shift4); - } - - return res; - } - - /** <inheritdoc /> */ - public virtual double ReadDouble() - { - int curPos = EnsureReadCapacityAndShift(Len8); - - return *((double*)(Data + curPos)); - } - - /** <inheritdoc /> */ - public virtual double[] ReadDoubleArray(int cnt) - { - double[] res = new double[cnt]; - - fixed (double* res0 = res) - { - CopyToAndShift((byte*)res0, cnt << Shift8); - } - - return res; - } - - /** <inheritdoc /> */ - public void Read(byte[] dest, int off, int cnt) - { - fixed (byte* dest0 = dest) - { - Read(dest0 + off, cnt); - } - } - - /** <inheritdoc /> */ - public void Read(byte* dest, int cnt) - { - CopyToAndShift(dest, cnt); - } - - #endregion - - #region MISC - - /// <summary> - /// Get cross-platform memory pointer for the stream. - /// </summary> - public long MemoryPointer - { - get { return _mem.Pointer; } - } - - /// <summary> - /// Synchronize stream write opeartions with underlying memory and return current memory pointer. - /// <returns>Memory pointer.</returns> - /// </summary> - public long SynchronizeOutput() - { - if (_pos > _len) - _len = _pos; - - _mem.Length = _len; - - return MemoryPointer; - } - - /// <summary> - /// Synchronized stream read operations from underlying memory. This is required when stream was passed - /// to Java and something might have been written there. - /// </summary> - public void SynchronizeInput() - { - Data = (byte*)_mem.Data; - _cap = _mem.Capacity; - _len = _mem.Length; - } - - /// <summary> - /// Reset stream state. Sets both position and length to 0. - /// </summary> - public void Reset() - { - _pos = 0; - } - - /// <summary> - /// Reset stream state as if it was just created. - /// </summary> - public void Reuse() - { - Data = (byte*)_mem.Data; - _cap = _mem.Capacity; - _len = _mem.Length; - _pos = 0; - } - - /** <inheritdoc /> */ - public int Seek(int offset, SeekOrigin origin) - { - int newPos; - - switch (origin) - { - case SeekOrigin.Begin: - { - newPos = offset; - - break; - } - - case SeekOrigin.Current: - { - newPos = _pos + offset; - - break; - } - - default: - throw new ArgumentException("Unsupported seek origin: " + origin); - } - - if (newPos < 0) - throw new ArgumentException("Seek before origin: " + newPos); - - EnsureWriteCapacity(newPos); - - _pos = newPos; - - return _pos; - } - - /// <summary> - /// Ensure capacity for write and shift position. - /// </summary> - /// <param name="cnt">Bytes count.</param> - /// <returns>Position before shift.</returns> - protected int EnsureWriteCapacityAndShift(int cnt) - { - int curPos = _pos; - - int newPos = _pos + cnt; - - EnsureWriteCapacity(newPos); - - _pos = newPos; - - return curPos; - } - - /// <summary> - /// Ensure write capacity. - /// </summary> - /// <param name="reqCap">Required capacity.</param> - protected void EnsureWriteCapacity(int reqCap) - { - if (reqCap > _cap) - { - reqCap = CalculateCapacity(_cap, reqCap); - - _mem.Reallocate(reqCap); - - Data = (byte*)_mem.Data; - _cap = _mem.Capacity; - } - } - - /// <summary> - /// Ensure capacity for read and shift position. - /// </summary> - /// <param name="cnt">Bytes count.</param> - /// <returns>Position before shift.</returns> - protected int EnsureReadCapacityAndShift(int cnt) - { - int curPos = _pos; - - if (_len - _pos < cnt) - throw new EndOfStreamException("Not enough data in stream [expected=" + cnt + - ", remaining=" + (_len - _pos) + ']'); - - _pos += cnt; - - return curPos; - } - - /// <summary> - /// Copy (read) some data into destination and shift the stream forward. - /// </summary> - /// <param name="dest">Destination.</param> - /// <param name="cnt">Bytes count.</param> - private void CopyToAndShift(byte* dest, int cnt) - { - int curPos = EnsureReadCapacityAndShift(cnt); - - PlatformMemoryUtils.CopyMemory(Data + curPos, dest, cnt); - } - - /// <summary> - /// Copy (write) some data from source and shift the stream forward. - /// </summary> - /// <param name="src">Source.</param> - /// <param name="cnt">Bytes count.</param> - private void CopyFromAndShift(byte* src, int cnt) - { - int curPos = EnsureWriteCapacityAndShift(cnt); - - PlatformMemoryUtils.CopyMemory(src, Data + curPos, cnt); - } - - /// <summary> - /// Calculate new capacity. - /// </summary> - /// <param name="curCap">Current capacity.</param> - /// <param name="reqCap">Required capacity.</param> - /// <returns>New capacity.</returns> - private static int CalculateCapacity(int curCap, int reqCap) - { - int newCap; - - if (reqCap < 256) - newCap = 256; - else - { - newCap = curCap << 1; - - if (newCap < reqCap) - newCap = reqCap; - } - - return newCap; - } - - /** <inheritdoc /> */ - public int Position - { - get { return _pos; } - } - - /** <inheritdoc /> */ - public int Remaining() - { - return _len - _pos; - } - - /** <inheritdoc /> */ - public void Dispose() - { - SynchronizeOutput(); - - _mem.Release(); - } - - #endregion - - #region ARRAYS - - /** <inheritdoc /> */ - public byte[] Array() - { - return ArrayCopy(); - } - - /** <inheritdoc /> */ - public byte[] ArrayCopy() - { - byte[] res = new byte[_mem.Length]; - - fixed (byte* res0 = res) - { - PlatformMemoryUtils.CopyMemory(Data, res0, res.Length); - } - - return res; - } - - /** <inheritdoc /> */ - public bool IsSameArray(byte[] arr) - { - return false; - } - - #endregion - } -} http://git-wip-us.apache.org/repos/asf/ignite/blob/f0bac562/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryUtils.cs ---------------------------------------------------------------------- diff --git a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryUtils.cs b/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryUtils.cs deleted file mode 100644 index dd53281..0000000 --- a/modules/platform/src/main/dotnet/Apache.Ignite.Core/Impl/Memory/PlatformMemoryUtils.cs +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -namespace Apache.Ignite.Core.Impl.Memory -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Reflection; - using System.Runtime.InteropServices; - - /// <summary> - /// Utility methods for platform memory management. - /// </summary> - [CLSCompliant(false)] - public static unsafe class PlatformMemoryUtils - { - #region CONSTANTS - - /** Header length. */ - private const int PoolHdrLen = 64; - - /** Pool header offset: first memory chunk. */ - internal const int PoolHdrOffMem1 = 0; - - /** Pool header offset: second memory chunk. */ - internal const int PoolHdrOffMem2 = 20; - - /** Pool header offset: third memory chunk. */ - internal const int PoolHdrOffMem3 = 40; - - /** Memory chunk header length. */ - private const int MemHdrLen = 20; - - /** Offset: capacity. */ - private const int MemHdrOffCap = 8; - - /** Offset: length. */ - private const int MemHdrOffLen = 12; - - /** Offset: flags. */ - private const int MemHdrOffFlags = 16; - - /** Flag: external. */ - private const int FlagExt = 0x1; - - /** Flag: pooled. */ - private const int FlagPooled = 0x2; - - /** Flag: whether this pooled memory chunk is acquired. */ - private const int FlagAcquired = 0x4; - - #endregion - - #region COMMON - - /// <summary> - /// Gets data pointer for the given memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <returns>Data pointer.</returns> - public static long Data(long memPtr) - { - return *((long*)memPtr); - } - - /// <summary> - /// Gets capacity for the given memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <returns>CalculateCapacity.</returns> - public static int Capacity(long memPtr) - { - return *((int*)(memPtr + MemHdrOffCap)); - } - - /// <summary> - /// Sets capacity for the given memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <param name="cap">CalculateCapacity.</param> - public static void Capacity(long memPtr, int cap) - { - *((int*)(memPtr + MemHdrOffCap)) = cap; - } - - /// <summary> - /// Gets length for the given memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <returns>Length.</returns> - public static int Length(long memPtr) - { - return *((int*)(memPtr + MemHdrOffLen)); - } - - /// <summary> - /// Sets length for the given memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <param name="len">Length.</param> - public static void Length(long memPtr, int len) - { - *((int*)(memPtr + MemHdrOffLen)) = len; - } - - /// <summary> - /// Gets flags for the given memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <returns>Flags.</returns> - public static int Flags(long memPtr) - { - return *((int*)(memPtr + MemHdrOffFlags)); - } - - /// <summary> - /// Sets flags for the given memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <param name="flags">Flags.</param> - public static void Flags(long memPtr, int flags) - { - *((int*)(memPtr + MemHdrOffFlags)) = flags; - } - - /// <summary> - /// Check whether this memory chunk is external. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <returns><c>True</c> if owned by Java.</returns> - public static bool IsExternal(long memPtr) - { - return IsExternal(Flags(memPtr)); - } - - /// <summary> - /// Check whether flags denote that this memory chunk is external. - /// </summary> - /// <param name="flags">Flags.</param> - /// <returns><c>True</c> if owned by Java.</returns> - public static bool IsExternal(int flags) - { - return (flags & FlagExt) != FlagExt; - } - - /// <summary> - /// Check whether this memory chunk is pooled. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <returns><c>True</c> if pooled.</returns> - public static bool IsPooled(long memPtr) - { - return IsPooled(Flags(memPtr)); - } - - /// <summary> - /// Check whether flags denote pooled memory chunk. - /// </summary> - /// <param name="flags">Flags.</param> - /// <returns><c>True</c> if pooled.</returns> - public static bool IsPooled(int flags) - { - return (flags & FlagPooled) != 0; - } - - /// <summary> - /// Check whether this memory chunk is pooled and acquired. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <returns><c>True</c> if acquired.</returns> - public static bool IsAcquired(long memPtr) - { - return IsAcquired(Flags(memPtr)); - } - - /// <summary> - /// Check whether flags denote pooled and acquired memory chunk. - /// </summary> - /// <param name="flags">Flags.</param> - /// <returns><c>True</c> if acquired.</returns> - public static bool IsAcquired(int flags) - { - return (flags & FlagAcquired) != 0; - } - - #endregion - - #region UNPOOLED MEMORY - - /// <summary> - /// Allocate unpooled memory chunk. - /// </summary> - /// <param name="cap">Minimum capacity.</param> - /// <returns>New memory pointer.</returns> - public static long AllocateUnpooled(int cap) - { - long memPtr = Marshal.AllocHGlobal(MemHdrLen).ToInt64(); - long dataPtr = Marshal.AllocHGlobal(cap).ToInt64(); - - *((long*)memPtr) = dataPtr; - *((int*)(memPtr + MemHdrOffCap)) = cap; - *((int*)(memPtr + MemHdrOffLen)) = 0; - *((int*)(memPtr + MemHdrOffFlags)) = FlagExt; - - return memPtr; - } - - - /// <summary> - /// Reallocate unpooled memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <param name="cap">Minimum capacity.</param> - /// <returns></returns> - public static void ReallocateUnpooled(long memPtr, int cap) - { - long dataPtr = Data(memPtr); - - long newDataPtr = Marshal.ReAllocHGlobal((IntPtr)dataPtr, (IntPtr)cap).ToInt64(); - - if (dataPtr != newDataPtr) - *((long*)memPtr) = newDataPtr; // Write new data address if needed. - - *((int*)(memPtr + MemHdrOffCap)) = cap; // Write new capacity. - } - - /// <summary> - /// Release unpooled memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - public static void ReleaseUnpooled(long memPtr) - { - Marshal.FreeHGlobal((IntPtr)Data(memPtr)); - Marshal.FreeHGlobal((IntPtr)memPtr); - } - - #endregion - - #region POOLED MEMORY - - /// <summary> - /// Allocate pool memory. - /// </summary> - /// <returns>Pool pointer.</returns> - public static long AllocatePool() - { - // 1. Allocate memory. - long poolPtr = Marshal.AllocHGlobal((IntPtr)PoolHdrLen).ToInt64(); - - // 2. Clear memory. - for (int i = 0; i < PoolHdrLen; i += 8) - *((long*)(poolPtr + i)) = 0; - - // 3. Set flags for memory chunks. - Flags(poolPtr + PoolHdrOffMem1, FlagExt | FlagPooled); - Flags(poolPtr + PoolHdrOffMem2, FlagExt | FlagPooled); - Flags(poolPtr + PoolHdrOffMem3, FlagExt | FlagPooled); - - return poolPtr; - } - - /// <summary> - /// Release pool memory. - /// </summary> - /// <param name="poolPtr">Pool pointer.</param> - public static void ReleasePool(long poolPtr) - { - // Clean predefined memory chunks. - long mem = *((long*)(poolPtr + PoolHdrOffMem1)); - - if (mem != 0) - Marshal.FreeHGlobal((IntPtr)mem); - - mem = *((long*)(poolPtr + PoolHdrOffMem2)); - - if (mem != 0) - Marshal.FreeHGlobal((IntPtr)mem); - - mem = *((long*)(poolPtr + PoolHdrOffMem3)); - - if (mem != 0) - Marshal.FreeHGlobal((IntPtr)mem); - - // Clean pool chunk. - Marshal.FreeHGlobal((IntPtr)poolPtr); - } - - /// <summary> - /// Allocate pooled memory chunk. - /// </summary> - /// <param name="poolPtr">Pool pointer.</param> - /// <param name="cap">CalculateCapacity.</param> - /// <returns>Memory pointer or <c>0</c> in case there are no free memory chunks in the pool.</returns> - public static long AllocatePooled(long poolPtr, int cap) - { - long memPtr = poolPtr + PoolHdrOffMem1; - - if (IsAcquired(memPtr)) - { - memPtr = poolPtr + PoolHdrOffMem2; - - if (IsAcquired(memPtr)) - { - memPtr = poolPtr + PoolHdrOffMem3; - - if (IsAcquired(memPtr)) - memPtr = 0; - else - AllocatePooled0(memPtr, cap); - } - else - AllocatePooled0(memPtr, cap); - } - else - AllocatePooled0(memPtr, cap); - - return memPtr; - } - - /// <summary> - /// Internal pooled memory chunk allocation routine. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <param name="cap">CalculateCapacity.</param> - private static void AllocatePooled0(long memPtr, int cap) - { - long data = *((long*)memPtr); - - if (data == 0) { - // First allocation of the chunk. - data = Marshal.AllocHGlobal(cap).ToInt64(); - - *((long*)memPtr) = data; - *((int*)(memPtr + MemHdrOffCap)) = cap; - } - else { - // Ensure that we have enough capacity. - int curCap = Capacity(memPtr); - - if (cap > curCap) { - data = Marshal.ReAllocHGlobal((IntPtr)data, (IntPtr)cap).ToInt64(); - - *((long*)memPtr) = data; - *((int*)(memPtr + MemHdrOffCap)) = cap; - } - } - - Flags(memPtr, FlagExt | FlagPooled | FlagAcquired); - } - - /// <summary> - /// Reallocate pooled memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - /// <param name="cap">Minimum capacity.</param> - public static void ReallocatePooled(long memPtr, int cap) - { - long data = *((long*)memPtr); - - int curCap = Capacity(memPtr); - - if (cap > curCap) { - data = Marshal.ReAllocHGlobal((IntPtr)data, (IntPtr)cap).ToInt64(); - - *((long*)memPtr) = data; - *((int*)(memPtr + MemHdrOffCap)) = cap; - } - } - - /// <summary> - /// Release pooled memory chunk. - /// </summary> - /// <param name="memPtr">Memory pointer.</param> - public static void ReleasePooled(long memPtr) - { - Flags(memPtr, Flags(memPtr) ^ FlagAcquired); - } - - #endregion - - #region MEMCPY - - /** Array copy delegate. */ - private delegate void MemCopy(byte* a1, byte* a2, int len); - - /** memcpy function handle. */ - private static readonly MemCopy Memcpy; - - /** Whether src and dest arguments are inverted. */ - private static readonly bool MemcpyInverted; - - /// <summary> - /// Static initializer. - /// </summary> - [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] - static PlatformMemoryUtils() - { - Type type = typeof(Buffer); - - const BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic; - Type[] paramTypes = { typeof(byte*), typeof(byte*), typeof(int) }; - - // Assume .Net 4.5. - MethodInfo mthd = type.GetMethod("Memcpy", flags, null, paramTypes, null); - - MemcpyInverted = true; - - if (mthd == null) - { - // Assume .Net 4.0. - mthd = type.GetMethod("memcpyimpl", flags, null, paramTypes, null); - - MemcpyInverted = false; - - if (mthd == null) - throw new InvalidOperationException("Unable to get memory copy function delegate."); - } - - Memcpy = (MemCopy)Delegate.CreateDelegate(typeof(MemCopy), mthd); - } - - /// <summary> - /// Unsafe memory copy routine. - /// </summary> - /// <param name="src">Source.</param> - /// <param name="dest">Destination.</param> - /// <param name="len">Length.</param> - public static void CopyMemory(void* src, void* dest, int len) - { - CopyMemory((byte*)src, (byte*)dest, len); - } - - /// <summary> - /// Unsafe memory copy routine. - /// </summary> - /// <param name="src">Source.</param> - /// <param name="dest">Destination.</param> - /// <param name="len">Length.</param> - public static void CopyMemory(byte* src, byte* dest, int len) - { - if (MemcpyInverted) - Memcpy.Invoke(dest, src, len); - else - Memcpy.Invoke(src, dest, len); - } - - #endregion - } -}
