1 package org.hedgewars.hedgeroid.netplay; |
|
2 |
|
3 import java.io.UnsupportedEncodingException; |
|
4 |
|
5 import com.sun.jna.DefaultTypeMapper; |
|
6 import com.sun.jna.FromNativeContext; |
|
7 import com.sun.jna.FromNativeConverter; |
|
8 import com.sun.jna.Native; |
|
9 import com.sun.jna.Pointer; |
|
10 import com.sun.jna.ToNativeContext; |
|
11 import com.sun.jna.ToNativeConverter; |
|
12 import com.sun.jna.TypeConverter; |
|
13 import com.sun.jna.TypeMapper; |
|
14 |
|
15 public class FrontlibTypeMapper extends DefaultTypeMapper { |
|
16 public static final TypeMapper INSTANCE = new FrontlibTypeMapper(); |
|
17 |
|
18 protected FrontlibTypeMapper() { |
|
19 addTypeConverter(Boolean.class, new BooleanConverter()); |
|
20 addToNativeConverter(String.class, new StringToNativeConverter()); |
|
21 addFromNativeConverter(String.class, new StringFromNativeConverter()); |
|
22 } |
|
23 } |
|
24 |
|
25 class BooleanConverter implements TypeConverter { |
|
26 public Class<Byte> nativeType() { |
|
27 return Byte.class; |
|
28 } |
|
29 public Object fromNative(Object value, FromNativeContext context) { |
|
30 return ((Byte)value).intValue() != 0 ? Boolean.TRUE : Boolean.FALSE; |
|
31 } |
|
32 public Object toNative(Object value, ToNativeContext context) { |
|
33 return Byte.valueOf((byte)(Boolean.TRUE.equals(value) ? 1 : 0)); |
|
34 } |
|
35 } |
|
36 |
|
37 class StringToNativeConverter implements ToNativeConverter { |
|
38 public byte[] toNative(Object value, ToNativeContext context) { |
|
39 try { |
|
40 return value==null ? null : Native.toByteArray((String)value, "UTF-8"); |
|
41 } catch (UnsupportedEncodingException e) { |
|
42 throw new AssertionError(e); // Never happens |
|
43 } |
|
44 } |
|
45 |
|
46 public Class<byte[]> nativeType() { |
|
47 return byte[].class; |
|
48 } |
|
49 } |
|
50 |
|
51 class StringFromNativeConverter implements FromNativeConverter { |
|
52 public String fromNative(Object value, FromNativeContext context) { |
|
53 Pointer p = (Pointer)value; |
|
54 if(p==null) { |
|
55 return null; |
|
56 } |
|
57 int i=0; |
|
58 while(p.getByte(i) != 0) { |
|
59 i++; |
|
60 } |
|
61 try { |
|
62 return new String(p.getByteArray(0, i), "UTF-8"); |
|
63 } catch (UnsupportedEncodingException e) { |
|
64 throw new AssertionError(e); // Never happens |
|
65 } |
|
66 } |
|
67 |
|
68 public Class<Pointer> nativeType() { |
|
69 return Pointer.class; |
|
70 } |
|
71 } |
|