[TCSACR-93] Add USB Host C# API
[platform/core/csapi/tizenfx.git] / src / Tizen.System.Usb / Interop / Interop.SafeUsbHandle.cs
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 using System;
18 using System.Runtime.CompilerServices;
19 using System.Runtime.InteropServices;
20 using System.Text;
21
22 internal static partial class Interop
23 {
24     public delegate ErrorCode GetterMethod<T>(out T value);
25     public delegate ErrorCode GetterPtrMethod(out IntPtr value);
26     public delegate ErrorCode GetDescriptorString(ref int length, byte[] data);
27     public delegate ErrorCode SetterMethod<T>(T value);
28
29     internal static T NativeGet<T>(GetterMethod<T> getter, [CallerMemberName] string propertyName = "")
30     {
31         T value;
32         var err = getter(out value);
33         if (err.IsSuccess())
34         {
35             return value;
36         }
37
38         err.ThrowIfFailed($"Native getter for {propertyName} failed");
39         return default(T);
40     }
41
42     internal static string DescriptorString(GetDescriptorString getter, string language = "us-ascii", [CallerMemberName] string propertyName = "")
43     {
44         int len = MaxStringDescriptorSize;
45         byte[] data = new byte[len];
46         getter(ref len, data).ThrowIfFailed($"Native setter for {propertyName} failed");
47         return Encoding.GetEncoding(language).GetString(data, 0, len);
48     }
49
50     internal static void NativeSet<T>(SetterMethod<T> setter, T value, [CallerMemberName] string propertyName = "")
51     {
52         setter(value).ThrowIfFailed($"Native setter for {propertyName} failed");
53     }
54
55     internal abstract class SafeUsbHandle : SafeHandle
56     {
57         public abstract void Destroy();
58         public SafeUsbHandle() : base(IntPtr.Zero, true) { }
59         public SafeUsbHandle(IntPtr handle) : base(handle, true) { }
60         public override bool IsInvalid { get { return handle == IntPtr.Zero; } }
61         protected override bool ReleaseHandle()
62         {
63             Destroy();
64             SetHandle(IntPtr.Zero);
65             return true;
66         }
67     }
68 }