1 // UnixMarshalTests.cs - NUnit2 Test Cases for Mono.Unix.UnixMarshal class
4 // Jonathan Pryor (jonpryor@vt.edu)
6 // (c) 2005 Jonathan Pryor
11 using System.Collections.Generic;
13 using System.Runtime.InteropServices;
17 namespace MonoTests.Mono.Unix {
19 class RandomEncoding : UTF8Encoding {
20 public RandomEncoding ()
25 public override int GetMaxByteCount (int value)
31 [TestFixture, Category ("NotOnWindows")]
32 public class UnixMarshalTest {
34 public static void Main ()
36 string s = UnixMarshal.GetErrorDescription (Errno.ERANGE);
37 Console.WriteLine ("ERANGE={0}", s);
38 s = UnixMarshal.GetErrorDescription ((Errno) 999999);
39 Console.WriteLine ("Invalid={0}", s);
44 public void TestStringToHeap ()
47 "Hello, world!", true, true,
48 "MS Pゴシック", false, true,
51 for (int i = 0; i < data.Length; i += 3) {
52 string s = (string) data [i+0];
53 bool valid_ascii = (bool) data [i+1];
54 bool valid_unicode = (bool) data [i+2];
56 StringToHeap (s, valid_ascii, valid_unicode);
60 private static void StringToHeap (string s, bool validAscii, bool validUnicode)
62 StringToHeap (s, Encoding.ASCII, validAscii);
63 StringToHeap (s, Encoding.UTF7, validUnicode);
64 StringToHeap (s, Encoding.UTF8, validUnicode);
65 StringToHeap (s, Encoding.Unicode, validUnicode);
66 StringToHeap (s, Encoding.BigEndianUnicode, validUnicode);
67 StringToHeap (s, new RandomEncoding (), validUnicode);
70 private static void StringToHeap (string s, Encoding e, bool mustBeEqual)
72 IntPtr p = UnixMarshal.StringToHeap (s, e);
74 string _s = UnixMarshal.PtrToString (p, e);
76 Assert.AreEqual (s, _s, "#TSTA (" + e.GetType() + ")");
79 UnixMarshal.FreeHeap (p);
84 public void TestPtrToString ()
86 IntPtr p = UnixMarshal.AllocHeap (1);
87 Marshal.WriteByte (p, 0);
88 string s = UnixMarshal.PtrToString (p);
89 UnixMarshal.FreeHeap (p);
93 public void TestUtf32PtrToString ()
95 var utf32NativeEndianNoBom = new UTF32Encoding(
96 bigEndian: !BitConverter.IsLittleEndian,
98 throwOnInvalidCharacters: true
101 // assemble a buffer that contains:
102 // 1. eight garbage bytes
103 // 2. the native-endian UTF-32 string "Hello, World" without BOM
104 // 3. four 0 bytes (as a C wide string terminator)
105 // 4. the native-endian UTF-32 string "broken" without BOM
107 // 6. four garbage bytes
108 var buf = new List<byte>();
109 for (int i = 0; i < 2; ++i) {
116 buf.AddRange(utf32NativeEndianNoBom.GetBytes("Hello, World"));
118 for (int i = 0; i < 4; ++i) {
122 buf.AddRange(utf32NativeEndianNoBom.GetBytes("broken"));
124 for (int i = 0; i < 8; ++i) {
133 // get the array version of this
134 var bufArr = buf.ToArray();
136 // allocate a buffer that will contain this string
137 IntPtr bufPtr = UnixMarshal.AllocHeap(bufArr.Length);
142 Marshal.Copy(bufArr, 0, bufPtr, bufArr.Length);
144 // try getting it back
145 returned = UnixMarshal.PtrToString(bufPtr + 8, utf32NativeEndianNoBom);
149 UnixMarshal.FreeHeap(bufPtr);
152 Assert.AreEqual("Hello, World", returned);