1 /* 2 * Copyright (C) 2021 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.tare; 18 19 import static android.app.tare.EconomyManager.CAKE_IN_ARC; 20 21 import android.annotation.NonNull; 22 import android.annotation.SuppressLint; 23 import android.util.IndentingPrintWriter; 24 25 import com.android.internal.annotations.VisibleForTesting; 26 27 import java.text.SimpleDateFormat; 28 import java.time.Clock; 29 30 class TareUtils { 31 @SuppressLint("SimpleDateFormat") 32 private static final SimpleDateFormat sDumpDateFormat = 33 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 34 35 @VisibleForTesting 36 static Clock sSystemClock = Clock.systemUTC(); 37 dumpTime(IndentingPrintWriter pw, long time)38 static void dumpTime(IndentingPrintWriter pw, long time) { 39 pw.print(sDumpDateFormat.format(time)); 40 } 41 getCurrentTimeMillis()42 static long getCurrentTimeMillis() { 43 return sSystemClock.millis(); 44 } 45 cakeToArc(long cakes)46 static int cakeToArc(long cakes) { 47 return (int) (cakes / CAKE_IN_ARC); 48 } 49 50 @NonNull cakeToString(long cakes)51 static String cakeToString(long cakes) { 52 if (cakes == 0) { 53 return "0 ARCs"; 54 } 55 final long sub = cakes % CAKE_IN_ARC; 56 final long arcs = cakeToArc(cakes); 57 if (arcs == 0) { 58 return sub == 1 59 ? sub + " cake" 60 : sub + " cakes"; 61 } 62 StringBuilder sb = new StringBuilder(); 63 sb.append(arcs); 64 if (sub != 0) { 65 sb.append(".").append(String.format("%03d", Math.abs(sub) / (CAKE_IN_ARC / 1000))); 66 } 67 sb.append(" ARC"); 68 if (arcs != 1 || sub != 0) { 69 sb.append("s"); 70 } 71 return sb.toString(); 72 } 73 74 /** Returns a standardized format for printing userId+pkgName combinations. */ 75 @NonNull appToString(int userId, String pkgName)76 static String appToString(int userId, String pkgName) { 77 return "<" + userId + ">" + pkgName; 78 } 79 } 80