• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2012 Sebastian Annies, Hamburg
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.googlecode.mp4parser.util;
17 
18 import java.io.EOFException;
19 import java.io.IOException;
20 import java.nio.ByteBuffer;
21 import java.nio.channels.ByteChannel;
22 
23 /**
24  * Creates a <code>ReadableByteChannel</code> that is backed by a <code>ByteBuffer</code>.
25  */
26 public class ByteBufferByteChannel implements ByteChannel {
27     ByteBuffer byteBuffer;
28 
ByteBufferByteChannel(ByteBuffer byteBuffer)29     public ByteBufferByteChannel(ByteBuffer byteBuffer) {
30         this.byteBuffer = byteBuffer;
31     }
32 
read(ByteBuffer dst)33     public int read(ByteBuffer dst) throws IOException {
34         byte[] b = dst.array();
35         int r = dst.remaining();
36         if (byteBuffer.remaining() >= r) {
37             byteBuffer.get(b, dst.position(), r);
38             return r;
39         } else {
40             throw new EOFException("Reading beyond end of stream");
41         }
42     }
43 
isOpen()44     public boolean isOpen() {
45         return true;
46     }
47 
close()48     public void close() throws IOException {
49     }
50 
write(ByteBuffer src)51     public int write(ByteBuffer src) throws IOException {
52         int r = src.remaining();
53         byteBuffer.put(src);
54         return r;
55     }
56 }
57