1 /* ====================================================================
2 Licensed to the Apache Software Foundation (ASF) under one or more
3 contributor license agreements. See the NOTICE file distributed with
4 this work for additional information regarding copyright ownership.
5 The ASF licenses this file to You under the Apache License, Version 2.0
6 (the "License"); you may not use this file except in compliance with
7 the License. You may obtain a copy of the License at
9 http://www.apache.org/licenses/LICENSE-2.0
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16 ==================================================================== */
18 package org.apache.poi.ss.formula.eval;
20 import org.apache.poi.ss.formula.functions.Fixed2ArgFunction;
21 import org.apache.poi.ss.formula.functions.Function;
26 public final class IntersectionEval extends Fixed2ArgFunction {
28 public static final Function instance = new IntersectionEval();
30 private IntersectionEval() {
34 public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
37 AreaEval reA = evaluateRef(arg0);
38 AreaEval reB = evaluateRef(arg1);
39 AreaEval result = resolveRange(reA, reB);
41 return ErrorEval.NULL_INTERSECTION;
44 } catch (EvaluationException e) {
45 return e.getErrorEval();
50 * @return simple rectangular {@link AreaEval} which represents the intersection of areas
51 * <tt>aeA</tt> and <tt>aeB</tt>. If the two areas do not intersect, the result is <code>null</code>.
53 private static AreaEval resolveRange(AreaEval aeA, AreaEval aeB) {
55 int aeAfr = aeA.getFirstRow();
56 int aeAfc = aeA.getFirstColumn();
57 int aeBlc = aeB.getLastColumn();
61 int aeBfc = aeB.getFirstColumn();
62 if (aeBfc > aeA.getLastColumn()) {
65 int aeBlr = aeB.getLastRow();
69 int aeBfr = aeB.getFirstRow();
70 int aeAlr = aeA.getLastRow();
76 int top = Math.max(aeAfr, aeBfr);
77 int bottom = Math.min(aeAlr, aeBlr);
78 int left = Math.max(aeAfc, aeBfc);
79 int right = Math.min(aeA.getLastColumn(), aeBlc);
81 return aeA.offset(top-aeAfr, bottom-aeAfr, left-aeAfc, right-aeAfc);
84 private static AreaEval evaluateRef(ValueEval arg) throws EvaluationException {
85 if (arg instanceof AreaEval) {
86 return (AreaEval) arg;
88 if (arg instanceof RefEval) {
89 return ((RefEval) arg).offset(0, 0, 0, 0);
91 if (arg instanceof ErrorEval) {
92 throw new EvaluationException((ErrorEval)arg);
94 throw new IllegalArgumentException("Unexpected ref arg class (" + arg.getClass().getName() + ")");