1/*
2 * Copyright (c) 2007 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockito.internal.invocation;
6
7import org.mockito.ArgumentMatcher;
8import org.mockito.internal.matchers.ArrayEquals;
9import org.mockito.internal.matchers.Equals;
10
11import java.util.ArrayList;
12import java.util.List;
13
14/**
15 * by Szczepan Faber, created at: 3/31/12
16 */
17public class ArgumentsProcessor {
18    // expands array varArgs that are given by runtime (1, [a, b]) into true
19    // varArgs (1, a, b);
20    public static Object[] expandVarArgs(final boolean isVarArgs, final Object[] args) {
21        if (!isVarArgs || isNullOrEmpty(args) || args[args.length - 1] != null && !args[args.length - 1].getClass().isArray()) {
22            return args == null ? new Object[0] : args;
23        }
24
25        final int nonVarArgsCount = args.length - 1;
26        Object[] varArgs;
27        if (args[nonVarArgsCount] == null) {
28            // in case someone deliberately passed null varArg array
29            varArgs = new Object[] { null };
30        } else {
31            varArgs = ArrayEquals.createObjectArray(args[nonVarArgsCount]);
32        }
33        final int varArgsCount = varArgs.length;
34        Object[] newArgs = new Object[nonVarArgsCount + varArgsCount];
35        System.arraycopy(args, 0, newArgs, 0, nonVarArgsCount);
36        System.arraycopy(varArgs, 0, newArgs, nonVarArgsCount, varArgsCount);
37        return newArgs;
38    }
39
40    private static <T> boolean isNullOrEmpty(T[] array) {
41        return array == null || array.length == 0;
42    }
43
44    public static List<ArgumentMatcher> argumentsToMatchers(Object[] arguments) {
45        List<ArgumentMatcher> matchers = new ArrayList<ArgumentMatcher>(arguments.length);
46        for (Object arg : arguments) {
47            if (arg != null && arg.getClass().isArray()) {
48                matchers.add(new ArrayEquals(arg));
49            } else {
50                matchers.add(new Equals(arg));
51            }
52        }
53        return matchers;
54    }
55
56
57}
58