Home | History | Annotate | Download | only in util
      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 
     17 package com.android.internal.util;
     18 
     19 /**
     20  * Helper class for implementing a ring buffer.  This supplies the indices, you supply
     21  * the array(s).
     22  */
     23 public class RingBufferIndices {
     24     private final int mCapacity;
     25 
     26     // The first valid element and the next open slot.
     27     private int mStart;
     28     private int mSize;
     29 
     30     /**
     31      * Create ring buffer of the given capacity.
     32      */
     33     public RingBufferIndices(int capacity) {
     34         mCapacity = capacity;
     35     }
     36 
     37     /**
     38      * Add a new item to the ring buffer.  If the ring buffer is full, this
     39      * replaces the oldest item.
     40      * @return Returns the index at which the new item appears, for placing in your array.
     41      */
     42     public int add() {
     43         if (mSize < mCapacity) {
     44             final int pos = mSize;
     45             mSize++;
     46             return pos;
     47         }
     48         int pos = mStart;
     49         mStart++;
     50         if (mStart == mCapacity) {
     51             mStart = 0;
     52         }
     53         return pos;
     54     }
     55 
     56     /**
     57      * Clear the ring buffer.
     58      */
     59     public void clear() {
     60         mStart = 0;
     61         mSize = 0;
     62     }
     63 
     64     /**
     65      * Return the current size of the ring buffer.
     66      */
     67     public int size() {
     68         return mSize;
     69     }
     70 
     71     /**
     72      * Convert a position in the ring buffer that is [0..size()] to an offset
     73      * in the array(s) containing the ring buffer items.
     74      */
     75     public int indexOf(int pos) {
     76         int index = mStart + pos;
     77         if (index >= mCapacity) {
     78             index -= mCapacity;
     79         }
     80         return index;
     81     }
     82 }
     83