| 1 | package Encode; | ||
| 2 | use strict; | ||
| 3 | |||
| 4 | use Exporter qw(import); | ||
| 5 | our @EXPORT = qw(encode_utf8 decode_utf8); | ||
| 6 | our @EXPORT_OK = qw(encode_utf8 decode_utf8 encode decode); | ||
| 7 | |||
| 8 | sub encode_utf8 ($) { | ||
| 9 | return encode('UTF-8', $_[0]); | ||
| 10 | } | ||
| 11 | |||
| 12 | sub encode ($$;$) { | ||
| 13 | return encode('UTF-8', $_[1], $_[2]) if $_[0] eq 'utf8'; | ||
| 14 | eval { | ||
| 15 | if (@_) { | ||
| 16 | Java::inline ' | ||
| 17 | String charset = List__.shift().toString(); | ||
| 18 | String s = List__.shift().toString(); | ||
| 19 | byte[] bytes = s.getBytes(charset); | ||
| 20 | StringBuilder sb = new StringBuilder(); | ||
| 21 | for (byte b : bytes) { | ||
| 22 | int i = b < 0 ? 256 + b : b; | ||
| 23 | sb.append((char)i); | ||
| 24 | } | ||
| 25 | return new PlString(sb.toString()) | ||
| 26 | '; | ||
| 27 | } | ||
| 28 | return undef; | ||
| 29 | } | ||
| 30 | or die $@; | ||
| 31 | } | ||
| 32 | |||
| 33 | sub decode_utf8 ($;$) { | ||
| 34 | return decode('UTF-8', $_[0], $_[1]); | ||
| 35 | } | ||
| 36 | |||
| 37 | sub decode ($$;$) { | ||
| 38 | return decode('UTF-8', $_[1], $_[2]) if $_[0] eq 'utf8'; | ||
| 39 | eval { | ||
| 40 | if (@_) { | ||
| 41 | Java::inline ' | ||
| 42 | String charset = List__.shift().toString(); | ||
| 43 | String s = List__.shift().toString(); | ||
| 44 | char[] chars = s.toCharArray(); | ||
| 45 | byte[] bytes = new byte[chars.length]; | ||
| 46 | for (int i = 0; i < bytes.length; i++){ | ||
| 47 | bytes[i] = (byte)(chars[i]); | ||
| 48 | } | ||
| 49 | return new PlString(new String(bytes, charset)) | ||
| 50 | '; | ||
| 51 | } | ||
| 52 | return undef; | ||
| 53 | } | ||
| 54 | or die $@; | ||
| 55 | } | ||
| 56 | |||
| 57 | 1; | ||
| 58 | |||
| 59 | __END__ |