summaryrefslogtreecommitdiff
path: root/NET/worlds/network/ServerOutputStream.java
blob: a95a0f1cf45b5003b2f6302ca844d79d66e9f7e0 (plain) (blame)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package NET.worlds.network;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ServerOutputStream extends FilterOutputStream {
   private int _version;

   public ServerOutputStream(OutputStream o) {
      super(o);
      this.setVersion(24);
   }

   public ServerOutputStream(OutputStream o, int vers) {
      super(o);
      this.setVersion(vers);
   }

   public void setVersion(int vers) {
      this._version = vers;
   }

   public int getVersion() {
      return this._version;
   }

   @Override
   public final void write(int b) throws IOException {
      this.out.write(b);
   }

   @Override
   public final void write(byte[] b, int off, int len) throws IOException {
      this.out.write(b, off, len);
   }

   public final void writeByte(int v) throws IOException {
      this.out.write(v);
   }

   public final void writeShort(int v) throws IOException {
      OutputStream out = this.out;
      out.write(v >>> 8 & 0xFF);
      out.write(v >>> 0 & 0xFF);
   }

   public final void writeInt(int v) throws IOException {
      OutputStream out = this.out;
      out.write(v >>> 24 & 0xFF);
      out.write(v >>> 16 & 0xFF);
      out.write(v >>> 8 & 0xFF);
      out.write(v >>> 0 & 0xFF);
   }

   public static int utfLength(String str) {
      int strlen = str.length();
      int utflen = 0;

      for (int i = 0; i < strlen; i++) {
         int c = str.charAt(i);
         if (c >= 1 && c <= 127) {
            utflen++;
         } else if (c > 2047) {
            utflen += 3;
         } else {
            utflen += 2;
         }
      }

      return utflen;
   }

   public void writeUTF(String str) throws IOException {
      OutputStream out = this.out;
      int strlen = str.length();
      int utflen = utfLength(str);

      assert utflen < 256;

      out.write(utflen >>> 0 & 0xFF);

      for (int i = 0; i < strlen; i++) {
         int c = str.charAt(i);
         if (c >= 1 && c <= 127) {
            out.write(c);
         } else if (c > 2047) {
            out.write(224 | c >> 12 & 15);
            out.write(128 | c >> 6 & 63);
            out.write(128 | c >> 0 & 63);
         } else {
            out.write(192 | c >> 6 & 31);
            out.write(128 | c >> 0 & 63);
         }
      }
   }
}