ByteArrayRingBuffer.java revision cc84bc6179db408b1e45168d43e10ba0ab089fca
1/* 2 * Copyright (C) 2016 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 17package com.android.server.wifi.util; 18 19import java.util.ArrayList; 20 21/** 22 * A ring buffer where each element of the ring is itself a byte array. 23 */ 24public class ByteArrayRingBuffer { 25 private ArrayList<byte[]> mArrayList; 26 private final int mMaxBytes; 27 private int mBytesUsed; 28 29 /** 30 * Creates a ring buffer that holds at most |maxBytes| of data. The overhead for each element 31 * is not included in this limit. 32 * @param maxBytes upper bound on the amount of data held 33 */ 34 public ByteArrayRingBuffer(int maxBytes) { 35 mArrayList = new ArrayList<byte[]>(); 36 mMaxBytes = maxBytes; 37 mBytesUsed = 0; 38 } 39 40 /** 41 * Adds |newData| to the ring buffer. Removes existing entries to make room, if necessary. 42 * Existing entries are removed in FIFO order. 43 * <p><b>Note:</b> will fail if |newData| itself exceeds the size limit for this buffer. 44 * Will first remove all existing entries in this case. (This guarantees that the ring buffer 45 * always represents a contiguous sequence of data.) 46 * @param newData data to be added to the ring 47 * @return true if the data was added 48 */ 49 public boolean appendBuffer(byte[] newData) { 50 // Loop is O(n^2), but |n| is expected to be small. 51 while (mBytesUsed + newData.length > mMaxBytes 52 && !mArrayList.isEmpty()) { 53 mBytesUsed -= mArrayList.get(0).length; 54 mArrayList.remove(0); 55 } 56 57 if (mBytesUsed + newData.length > mMaxBytes) { 58 return false; 59 } 60 61 mArrayList.add(newData); 62 mBytesUsed += newData.length; 63 return true; 64 } 65 66 /** 67 * Returns the |i|-th element of the ring. The element retains its position in the ring. 68 * @param i 69 * @return the requested element 70 */ 71 public byte[] getBuffer(int i) { 72 return mArrayList.get(i); 73 } 74 75 /** 76 * Returns the number of elements present in the ring. 77 * @return the number of elements present 78 */ 79 public int getNumBuffers() { 80 return mArrayList.size(); 81 } 82} 83