Fix StyleCop warning SA1206 (modifer ordering)
[mono-project.git] / netcore / System.Private.CoreLib / shared / System / Security / SafeBSTRHandle.cs
blobceaf903aa9f1140f1961abde7d931e93dbaaaa76
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
5 using System.Runtime;
6 using System.Diagnostics;
7 using System.Runtime.InteropServices;
9 namespace System.Security
11 internal sealed class SafeBSTRHandle : SafeBuffer
13 internal SafeBSTRHandle() : base(true) { }
15 internal static SafeBSTRHandle Allocate(uint lenInChars)
17 ulong lenInBytes = (ulong)lenInChars * sizeof(char);
18 SafeBSTRHandle bstr = Interop.OleAut32.SysAllocStringLen(IntPtr.Zero, lenInChars);
19 if (bstr.IsInvalid) // SysAllocStringLen returns a NULL ptr when there's insufficient memory
21 throw new OutOfMemoryException();
23 bstr.Initialize(lenInBytes);
24 return bstr;
27 protected override bool ReleaseHandle()
29 RuntimeImports.RhZeroMemory(handle, (UIntPtr)Marshal.SysStringByteLen(handle));
30 Interop.OleAut32.SysFreeString(handle);
31 return true;
34 internal unsafe void ClearBuffer()
36 byte* bufferPtr = null;
37 try
39 AcquirePointer(ref bufferPtr);
40 RuntimeImports.RhZeroMemory((IntPtr)bufferPtr, (UIntPtr)Marshal.SysStringByteLen((IntPtr)bufferPtr));
42 finally
44 if (bufferPtr != null)
46 ReleasePointer();
51 internal unsafe uint Length => Interop.OleAut32.SysStringLen(this);
53 internal static unsafe void Copy(SafeBSTRHandle source, SafeBSTRHandle target, uint bytesToCopy)
55 if (bytesToCopy == 0)
57 return;
60 byte* sourcePtr = null, targetPtr = null;
61 try
63 source.AcquirePointer(ref sourcePtr);
64 target.AcquirePointer(ref targetPtr);
66 Debug.Assert(source.ByteLength >= bytesToCopy, "Source buffer is too small.");
67 Buffer.MemoryCopy(sourcePtr, targetPtr, target.ByteLength, bytesToCopy);
69 finally
71 if (targetPtr != null)
73 target.ReleasePointer();
75 if (sourcePtr != null)
77 source.ReleasePointer();