View Javadoc
1   /*
2    * Copyright (c) 2006 JMockit developers
3    * This file is subject to the terms of the MIT license (see LICENSE.txt).
4    */
5   package mockit.coverage;
6   
7   import edu.umd.cs.findbugs.annotations.NonNull;
8   
9   import org.checkerframework.checker.index.qual.NonNegative;
10  
11  public final class CoveragePercentage {
12      private CoveragePercentage() {
13      }
14  
15      public static int calculate(@NonNegative int coveredCount, @NonNegative int totalCount) {
16          if (totalCount == 0) {
17              return -1;
18          }
19  
20          // noinspection NumericCastThatLosesPrecision
21          return (int) (100.0 * coveredCount / totalCount + 0.5);
22      }
23  
24      @NonNull
25      public static String percentageColor(@NonNegative int coveredCount, @NonNegative int totalCount) {
26          if (coveredCount == 0) {
27              return "ff0000";
28          }
29          if (coveredCount == totalCount) {
30              return "00ff00";
31          }
32  
33          double percentage = 100.0 * coveredCount / totalCount;
34          // noinspection NumericCastThatLosesPrecision
35          int green = (int) (0xFF * percentage / 100.0 + 0.5);
36          int red = 0xFF - green;
37  
38          StringBuilder color = new StringBuilder(6);
39          appendColorInHexadecimal(color, red);
40          appendColorInHexadecimal(color, green);
41          color.append("00");
42  
43          return color.toString();
44      }
45  
46      private static void appendColorInHexadecimal(@NonNull StringBuilder colorInHexa, @NonNegative int rgb) {
47          String hex = Integer.toHexString(rgb);
48  
49          if (hex.length() == 1) {
50              colorInHexa.append('0');
51          }
52  
53          colorInHexa.append(hex);
54      }
55  }