• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2011 Google, Inc.
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 package com.google.common.truth;
17 
18 import static com.google.common.base.Preconditions.checkArgument;
19 import static com.google.common.base.Strings.lenientFormat;
20 
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.collect.ImmutableList;
23 
24 final class LazyMessage {
25   private static final String PLACEHOLDER_ERR =
26       "Incorrect number of args (%s) for the given placeholders (%s) in string template:\"%s\"";
27 
28   private final String format;
29   private final Object[] args;
30 
LazyMessage(String format, Object... args)31   LazyMessage(String format, /*@Nullable*/ Object... args) {
32     this.format = format;
33     this.args = args;
34     int placeholders = countPlaceholders(format);
35     checkArgument(placeholders == args.length, PLACEHOLDER_ERR, args.length, placeholders, format);
36   }
37 
38   @Override
toString()39   public String toString() {
40     return lenientFormat(format, args);
41   }
42 
43   @VisibleForTesting
countPlaceholders(String template)44   static int countPlaceholders(String template) {
45     int index = 0;
46     int count = 0;
47     while (true) {
48       index = template.indexOf("%s", index);
49       if (index == -1) {
50         break;
51       }
52       index++;
53       count++;
54     }
55     return count;
56   }
57 
evaluateAll(ImmutableList<LazyMessage> messages)58   static ImmutableList<String> evaluateAll(ImmutableList<LazyMessage> messages) {
59     ImmutableList.Builder<String> result = ImmutableList.builder();
60     for (LazyMessage message : messages) {
61       result.add(message.toString());
62     }
63     return result.build();
64   }
65 }
66