aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/makamys/neodymium/util/BufferWriter.java
blob: 617bd7ac0451f4ee05b62ce788ffac9fd08ef3e9 (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
package makamys.neodymium.util;

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

public class BufferWriter {
    
    private ByteBuffer buf;
    
    private FloatBuffer floatBuffer;
    private ShortBuffer shortBuffer;
    private IntBuffer intBuffer;
    
    public BufferWriter(ByteBuffer buf) {
        this.buf = buf;
        this.floatBuffer = buf.asFloatBuffer();
        this.shortBuffer = buf.asShortBuffer();
        this.intBuffer = buf.asIntBuffer();
    }
    
    private void incrementPosition(int add) {
        buf.position(buf.position() + add);
        floatBuffer.position(buf.position() / 4);
        shortBuffer.position(buf.position() / 2);
        intBuffer.position(buf.position() / 4);
    }
    
    public void writeFloat(float x) {
        try {
        floatBuffer.put(x);
        
        incrementPosition(4);
        } catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void writeInt(int x) {
        intBuffer.put(x);
        
        incrementPosition(4);
    }
    
    public void writeByte(byte x) {
        buf.put(x); // this increments the buffer position by 1
        
        incrementPosition(0);
    }
    
    public int position() {
        return buf.position();
    }
    
}