generated from CareBoo/UPMTemplate-2020
-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
11762f6
commit fdd3ccb
Showing
2 changed files
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
using System; | ||
using System.Diagnostics; | ||
using Unity.Collections; | ||
using Unity.Jobs; | ||
|
||
namespace Algorand.Unity.Crypto | ||
{ | ||
public struct SodiumString : INativeDisposable | ||
{ | ||
private readonly SecureMemoryHandle handle; | ||
|
||
private readonly int totalCapacity; | ||
|
||
private int length; | ||
|
||
public bool IsCreated => handle.IsCreated; | ||
|
||
public int Length => length; | ||
|
||
public int Capacity => totalCapacity - 1; | ||
|
||
public unsafe byte* GetUnsafePtr() | ||
{ | ||
return (byte*)handle.GetUnsafePtr(); | ||
} | ||
|
||
public SodiumString(ReadOnlySpan<char> source) | ||
{ | ||
totalCapacity = source.Length * sizeof(char); | ||
var totalCapacityNUint = (UIntPtr)totalCapacity; | ||
handle = SecureMemoryHandle.Create(totalCapacityNUint); | ||
unsafe | ||
{ | ||
fixed (char* sourceptr = source) | ||
{ | ||
sodium.sodium_mlock((IntPtr)sourceptr, totalCapacityNUint); | ||
var error = UTF8ArrayUnsafeUtility.Copy( | ||
handle.GetUnsafePtr(), | ||
out length, | ||
totalCapacity - 1, | ||
sourceptr, | ||
source.Length | ||
); | ||
sodium.sodium_munlock((IntPtr)sourceptr, totalCapacityNUint); | ||
if (error != CopyError.None) | ||
{ | ||
if (handle.IsCreated) handle.Dispose(); | ||
length = 0; | ||
ThrowCopyError(error, source); | ||
} | ||
} | ||
} | ||
} | ||
|
||
public JobHandle Dispose(JobHandle inputDeps) | ||
{ | ||
return handle.Dispose(inputDeps); | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
handle.Dispose(); | ||
} | ||
|
||
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] | ||
void ThrowCopyError(CopyError error, ReadOnlySpan<char> source) | ||
{ | ||
throw new ArgumentException($"NativeText: {error} while copying \"{source.ToString()}\""); | ||
} | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.