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