001package org.cache2k.storage; 002 003/* 004 * #%L 005 * cache2k core package 006 * %% 007 * Copyright (C) 2000 - 2015 headissue GmbH, Munich 008 * %% 009 * This program is free software: you can redistribute it and/or modify 010 * it under the terms of the GNU General Public License as 011 * published by the Free Software Foundation, either version 3 of the 012 * License, or (at your option) any later version. 013 * 014 * This program is distributed in the hope that it will be useful, 015 * but WITHOUT ANY WARRANTY; without even the implied warranty of 016 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 017 * GNU General Public License for more details. 018 * 019 * You should have received a copy of the GNU General Public 020 * License along with this program. If not, see 021 * <http://www.gnu.org/licenses/gpl-3.0.html>. 022 * #L% 023 */ 024 025import java.io.IOException; 026import java.io.InputStream; 027import java.nio.ByteBuffer; 028 029/** 030 * InputStream wrapper that reads directly from a bytebuffer. 031 * 032 * Credits: inspired by the stackoverflow question and adapted to my coding style. 033 * 034 * @author Jens Wilke; created: 2014-03-28 035 */ 036public class ByteBufferInputStream extends InputStream { 037 038 ByteBuffer byteBuffer; 039 040 public ByteBufferInputStream(ByteBuffer buf) { 041 byteBuffer = buf; 042} 043 044 public int read() throws IOException { 045 if (!byteBuffer.hasRemaining()) { 046 return -1; 047 } 048 return byteBuffer.get() & 0x0ff; 049 } 050 051 public int read(byte[] bytes, int off, int len) throws IOException { 052 if (!byteBuffer.hasRemaining()) { 053 return -1; 054 } 055 len = Math.min(len, byteBuffer.remaining()); 056 byteBuffer.get(bytes, off, len); 057 return len; 058 } 059 060}