1 /* 2 * Copyright (C) 2017 The Android Open Source Project 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 17 package com.android.apksig.internal.util; 18 19 import com.android.apksig.util.DataSinkTestBase; 20 import java.io.IOException; 21 import java.nio.ByteBuffer; 22 23 public abstract class ByteBufferSinkTestBase extends DataSinkTestBase<ByteBufferSink> { 24 25 private static final int START_POS = 100; 26 27 protected abstract ByteBuffer createBuffer(int size); 28 29 @Override 30 protected CloseableWithDataSink<ByteBufferSink> createDataSink() { 31 ByteBuffer buf = createBuffer(1024); 32 // Use non-zero position and limit which isn't set to capacity to catch the implementation 33 // under test ignoring the initial position. 34 buf.position(START_POS); 35 buf.limit(buf.capacity() - 300); 36 return CloseableWithDataSink.of(new ByteBufferSink(buf)); 37 } 38 39 @Override 40 protected ByteBuffer getContents(ByteBufferSink dataSink) throws IOException { 41 ByteBuffer buf = dataSink.getBuffer(); 42 int oldPos = buf.position(); 43 int oldLimit = buf.limit(); 44 try { 45 buf.position(START_POS); 46 buf.limit(oldPos); 47 return buf.slice(); 48 } finally { 49 buf.limit(oldLimit); 50 buf.position(oldPos); 51 } 52 } 53 } 54