1 /*******************************************************************************
2 * Copyright (c) 2010 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.databoard.util.binary;
14 import java.io.IOException;
15 import java.nio.ByteBuffer;
18 * IWriteable implementation with ByteBuffer as backend
20 * @author Toni Kalajainen (toni.kalajainen@vtt.fi)
22 public class ByteBufferWriteable implements BinaryWriteable {
26 public ByteBufferWriteable(ByteBuffer buf)
29 throw new IllegalArgumentException("null");
34 public void write(int b) {
39 public void writeByte(int b) throws IOException {
44 public void writeBoolean(boolean v) throws IOException {
45 buf.put( (byte) (v ? 1 : 0) );
49 public void writeFully(ByteBuffer src) {
54 public void writeFully(ByteBuffer src, int length) {
56 byte[] array = src.array();
57 buf.put(array, src.arrayOffset() + src.position(), length);
59 for (int i=0; i<length; i++)
65 public void write(byte[] src, int offset, int length) {
66 buf.put(src, offset, length);
70 public void write(byte[] src) {
75 public void writeDouble(double value) {
80 public void writeFloat(float value) {
85 public void writeInt(int value) {
90 public void writeLong(long value) {
95 public void writeShort(int value) {
96 buf.putShort((short)value);
100 public void writeChar(int value) {
101 buf.putChar((char) value);
105 public void writeBytes(String s) throws IOException {
106 int len = s.length();
107 for (int i = 0 ; i < len ; i++) {
108 buf.put((byte)s.charAt(i));
113 public void writeChars(String s) throws IOException {
114 int len = s.length();
115 for (int i = 0 ; i < len ; i++) {
116 char v = s.charAt(i);
122 public void writeUTF(String s) throws IOException {
123 int len = UTF8.getModifiedUTF8EncodingByteLength(s);
125 UTF8.writeModifiedUTF(this, s);
129 public void flush() {
132 public long position() throws IOException {
133 return buf.position();
136 public void position(long newPosition) throws IOException {
137 if (newPosition>=Integer.MAX_VALUE || newPosition<0) throw new IllegalArgumentException("index out of range");
138 buf.position((int) newPosition);