Files
DotNetAlpm/Alpm/Detail.cs
2020-04-30 17:27:50 -04:00

71 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Foodsoft.Alpm
{
internal static class Detail
{
internal static unsafe IntPtr ListNext(IntPtr list) => ((alpm_list_t*) list)->next;
internal static unsafe IntPtr ListData(IntPtr list) => ((alpm_list_t*) list)->data;
internal static TResult UseHandle<TResult>(this SafeHandle handle, IntPtr ptr, Func<IntPtr, TResult> op)
{
var release = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
handle.DangerousAddRef(ref release);
if (!release) throw new ObjectDisposedException(handle.GetType().FullName);
return op(ptr);
}
finally
{
if (release)
handle.DangerousRelease();
}
}
internal static TResult UseHandle<TResult>(this SafeHandle handle, Func<IntPtr, TResult> op) =>
handle.UseHandle(handle.DangerousGetHandle(), op);
internal static void SetStringCollection(IEnumerable<string> value, SafeAlpmHandle safeAlpmHandle, Func<string, int> op)
{
// ReSharper disable once LoopCanBeConvertedToQuery
foreach (var s in value)
{
if (op(s) < 0)
throw new AlpmException(safeAlpmHandle);
}
}
internal static void WrapError(SafeAlpmHandle alpmHandle, Func<int> f)
{
var err = f();
if (err != 0)
throw new AlpmException(alpmHandle);
}
internal delegate int OutFunc<T, in THandle>(THandle handle, out T result);
internal static T WrapError<T, THandle>(SafeAlpmHandle alpmHandle, THandle handle, OutFunc<T, THandle> f)
{
var err = f(handle, out var result);
if (err != 0)
throw new AlpmException(alpmHandle);
return result;
}
internal static bool WrapErrorBool(SafeAlpmHandle h, Func<int> f)
{
var err = f();
if (err < 0)
{
throw new AlpmException(h);
}
return err == 0;
}
}
}