using System.Runtime.InteropServices;
using System.Text;
namespace Bit.RustSDK;
///
/// Service implementation that provides a C# friendly interface to the Rust SDK
///
public class RustSdkService
{
///
/// Adds two integers using the native implementation
///
/// First integer
/// Second integer
/// The sum of x and y
public int Add(int x, int y)
{
try
{
return NativeMethods.my_add(x, y);
}
catch (Exception ex)
{
throw new RustSdkException($"Failed to perform addition operation: {ex.Message}", ex);
}
}
///
/// Hashes a password using the native implementation
///
/// User email
/// User password
/// The hashed password as a string
/// Thrown when email or password is null
/// Thrown when email or password is empty
/// Thrown when the native operation fails
public unsafe string HashPassword(string email, string password)
{
// Convert strings to null-terminated byte arrays
var emailBytes = Encoding.UTF8.GetBytes(email + '\0');
var passwordBytes = Encoding.UTF8.GetBytes(password + '\0');
try
{
fixed (byte* emailPtr = emailBytes)
fixed (byte* passwordPtr = passwordBytes)
{
var resultPtr = NativeMethods.hash_password(emailPtr, passwordPtr);
var result = TakeAndDestroyRustString(resultPtr);
return result;
}
}
catch (RustSdkException)
{
throw; // Re-throw our custom exceptions
}
catch (Exception ex)
{
throw new RustSdkException($"Failed to hash password: {ex.Message}", ex);
}
}
private static unsafe string TakeAndDestroyRustString(byte* ptr)
{
if (ptr == null)
{
throw new RustSdkException("Pointer is null");
}
var result = Marshal.PtrToStringUTF8((IntPtr)ptr);
NativeMethods.free_c_string(ptr);
if (result == null)
{
throw new RustSdkException("Failed to convert native result to string");
}
return result;
}
}