/******************************************************************************* * Copyright (c) 2010 Association for Decentralized Information Management in * Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.databoard.util.binary; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; public class OutputStreamWriteable implements BinaryWriteable { OutputStream out; public OutputStreamWriteable(OutputStream out) { if (out==null) throw new IllegalArgumentException("null arg"); this.out = out; } public OutputStream getStream() { return out; } void _put(int value) throws IOException { out.write(value); } @Override public void write(int b) throws IOException { _put(b); } @Override public void writeByte(int b) throws IOException { _put(b); } @Override public void writeBoolean(boolean v) throws IOException { _put( v ? 1 : 0); } @Override public void writeFully(ByteBuffer src) throws IOException { if (src.hasArray()) { byte array[] = src.array(); write(array, src.position(), src.remaining()); src.position(src.limit()); } else for (;src.hasRemaining();) _put(src.get()); } @Override public void writeFully(ByteBuffer src, int length) throws IOException { if (src.hasArray()) { byte array[] = src.array(); write(array, src.position(), length); src.position(length); } else { for (int i=0; i> 24); _put(value >> 16); _put(value >> 8); _put(value); } @Override public void writeLong(long value) throws IOException { _put((int) (value >> 56)); _put((int) (value >> 48)); _put((int) (value >> 40)); _put((int) (value >> 32)); _put((int) (value >> 24)); _put((int) (value >> 16)); _put((int) (value >> 8)); _put((int) (value)); } @Override public void writeShort(int value) throws IOException { _put(value >> 8); _put(value); } @Override public void writeChar(int value) throws IOException { _put(value >> 8); _put(value); } @Override public void writeBytes(String s) throws IOException { int len = s.length(); for (int i = 0 ; i < len ; i++) { _put((byte)s.charAt(i)); } } @Override public void writeChars(String s) throws IOException { int len = s.length(); for (int i = 0 ; i < len ; i++) { int v = s.charAt(i); _put((v >>> 8) & 0xFF); _put((v >>> 0) & 0xFF); } } @Override public void writeUTF(String s) throws IOException { int len = UTF8.getModifiedUTF8EncodingByteLength(s); writeShort(len); UTF8.writeModifiedUTF(this, s); } @Override public void flush() throws IOException { out.flush(); } }