1 /* 2 * Copyright (C) 2014 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 package com.android.tradefed.util; 17 18 /** 19 * Data structure for holding a fixed size array that operates as a circular buffer, 20 * and tracks the total sum of all values in the array. 21 */ 22 public class CircularByteArray { 23 24 private byte[] mArray; 25 private int mCurPos = 0; 26 private boolean mIsWrapped = false; 27 private long mSum = 0; 28 29 public CircularByteArray(int size) { 30 mArray = new byte[size]; 31 } 32 33 /** 34 * Adds a new value to array, replacing oldest value if necessary 35 * @param value 36 */ 37 public void add(byte value) { 38 if (mIsWrapped) { 39 // pop value and adjust total 40 mSum -= mArray[mCurPos]; 41 } 42 mArray[mCurPos] = value; 43 mCurPos++; 44 mSum += value; 45 if (mCurPos >= mArray.length) { 46 mIsWrapped = true; 47 mCurPos = 0; 48 } 49 } 50 51 /** 52 * Get the number of elements stored 53 */ 54 public int size() { 55 if (mIsWrapped) { 56 return mArray.length; 57 } else { 58 return mCurPos; 59 } 60 } 61 62 /** 63 * Gets the total value of all elements currently stored in array 64 */ 65 public long getSum() { 66 return mSum; 67 } 68 } 69