1 /* 2 * Copyright (C) 2019 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.server.display.utils; 18 19 import java.time.Clock; 20 21 /** 22 * A fixed-size buffer that keeps the most recent values and their times. 23 * 24 * This class is used for logging and debugging purposes only, so there's no way to retrieve the 25 * history other than toString(), and a non-monotonic clock is good enough. 26 */ 27 public class History { 28 29 private int mSize; 30 private int mCount; 31 private int mStart; 32 private int mEnd; 33 34 private long[] mTimes; 35 private float[] mValues; 36 37 private Clock mClock; 38 39 /** 40 * @param size 41 * The maximum number of values kept. 42 */ History(int size)43 public History(int size) { 44 this(size, Clock.systemUTC()); 45 } 46 47 /** 48 * @param size 49 * The maximum number of values kept. 50 * @param clock 51 * The clock used. 52 */ History(int size, Clock clock)53 public History(int size, Clock clock) { 54 mSize = size; 55 mCount = 0; 56 mStart = 0; 57 mEnd = 0; 58 mTimes = new long[size]; 59 mValues = new float[size]; 60 mClock = clock; 61 } 62 63 /** 64 * Add a value. 65 * 66 * @param value 67 * The value. 68 */ add(float value)69 public void add(float value) { 70 mTimes[mEnd] = mClock.millis(); 71 mValues[mEnd] = value; 72 if (mCount < mSize) { 73 mCount++; 74 } else { 75 mStart = (mStart + 1) % mSize; 76 } 77 mEnd = (mEnd + 1) % mSize; 78 } 79 80 /** 81 * Convert the buffer to string. 82 * 83 * @return The buffer as string. 84 */ toString()85 public String toString() { 86 StringBuffer sb = new StringBuffer(); 87 sb.append("["); 88 for (int i = 0; i < mCount; i++) { 89 final int index = (mStart + i) % mSize; 90 final long time = mTimes[index]; 91 final float value = mValues[index]; 92 sb.append(value + " @ " + time); 93 if (i + 1 != mCount) { 94 sb.append(", "); 95 } 96 } 97 sb.append("]"); 98 return sb.toString(); 99 } 100 101 } 102