001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.functions.arrays;
020
021import lucee.runtime.PageContext;
022import lucee.runtime.exp.ExpressionException;
023import lucee.runtime.exp.FunctionException;
024import lucee.runtime.exp.PageException;
025import lucee.runtime.functions.BIF;
026import lucee.runtime.op.Caster;
027import lucee.runtime.type.Array;
028import lucee.runtime.type.ArrayImpl;
029
030public final class ArrayMid extends BIF {
031
032        private static final long serialVersionUID = 4996354700884413289L;
033
034        public static Array call(PageContext pc , Array arr, double start) throws ExpressionException {
035                return call(pc,arr,start,-1);
036        }
037        
038        public static Array call(PageContext pc , Array arr, double start, double count) throws ExpressionException {
039                int s=(int) start;
040                int c=(int) count;
041                
042                if(s<1) throw new FunctionException(pc, "ArrayMid", 2, "start", "Parameter which is now ["+s+"] must be a positive integer");
043                if(c==-1) c=arr.size();
044                else if(c<-1) throw new FunctionException(pc, "ArrayMid", 3, "count", "Parameter which is now ["+c+"] must be a non-negative integer or -1 (for string length)");
045                c+=s-1;
046                if(s>arr.size()) return new ArrayImpl();
047                
048                ArrayImpl rtn = new ArrayImpl();
049                int len = arr.size();
050                Object value;
051                for(int i=s;i<=c && i<=len ;i++){
052                        value=arr.get(i, null);
053                        rtn.appendEL(value);
054                }
055                return rtn;
056        }
057        
058        @Override
059        public Object invoke(PageContext pc, Object[] args) throws PageException {
060                if(args.length==2)return call(pc,Caster.toArray(args[0]),Caster.toDoubleValue(args[1]));
061                return call(pc,Caster.toArray(args[0]),Caster.toDoubleValue(args[1]),Caster.toDoubleValue(args[2]));
062        }
063}