blob: c5dbff1817191f522d8ff2d304a904b06277bed5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
package net.brokenfox.vulpirc;
import android.util.Log;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
/**
* Created by ninji on 2/3/14.
*/
public class Util {
private static CharsetDecoder mUTF8Decoder = null;
private static CharsetEncoder mUTF8Encoder = null;
public static synchronized String readStringFromBuffer(ByteBuffer p) {
if (mUTF8Decoder == null)
mUTF8Decoder = Charset.forName("UTF-8").newDecoder();
int size = p.getInt();
if (size <= 0)
return "";
int beginPos = p.position();
int endPos = beginPos + size;
int saveLimit = p.limit();
p.limit(endPos);
String result = "";
try {
result = mUTF8Decoder.decode(p).toString();
} catch (CharacterCodingException e) {
Log.e("VulpIRC", "Utils.readStringFromBuffer caught decode exception:");
Log.e("VulpIRC", e.toString());
}
p.limit(saveLimit);
p.position(endPos);
return result;
}
public static synchronized byte[] encodeString(CharSequence s) {
if (mUTF8Encoder == null)
mUTF8Encoder = Charset.forName("UTF-8").newEncoder();
try {
return mUTF8Encoder.encode(CharBuffer.wrap(s)).array();
} catch (CharacterCodingException e) {
Log.e("VulpIRC", "Utils.encodeString caught encode exception:");
Log.e("VulpIRC", e.toString());
return new byte[0];
}
}
}
|