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 **/ 019/** 020 * Implements the CFML Function arraymin 021 */ 022package lucee.runtime.functions.arrays; 023 024import lucee.runtime.PageContext; 025import lucee.runtime.exp.FunctionException; 026import lucee.runtime.exp.PageException; 027import lucee.runtime.functions.BIF; 028import lucee.runtime.op.Caster; 029import lucee.runtime.type.Array; 030import lucee.runtime.type.ArrayImpl; 031 032public final class ArraySlice extends BIF { 033 034 private static final long serialVersionUID = 7309769117464009924L; 035 036 public static Array call(PageContext pc , Array arr,double offset) throws PageException { 037 return call(pc , arr, offset,0); 038 } 039 public static Array call(PageContext pc , Array arr,double offset,double length) throws PageException { 040 041 int len=arr.size(); 042 if(offset>0) { 043 if(len<offset)throw new FunctionException(pc,"arraySlice",2,"offset","Offset cannot be greater than size of the array"); 044 045 int to=0; 046 if(length>0)to=(int)(offset+length-1); 047 else if(length<0)to=(int)(len+length); 048 if(len<to) 049 throw new FunctionException(pc,"arraySlice",3,"length","Offset+length cannot be greater than size of the array"); 050 051 return get(arr,(int)offset,to); 052 } 053 return call(pc ,arr,len+offset,length); 054 } 055 056 @Override 057 public Object invoke(PageContext pc, Object[] args) throws PageException { 058 if(args.length==2)return call(pc,Caster.toArray(args[0]),Caster.toDoubleValue(args[1])); 059 return call(pc,Caster.toArray(args[0]),Caster.toDoubleValue(args[1]),Caster.toDoubleValue(args[2])); 060 } 061 062 private static Array get(Array arr, int from, int to) throws PageException { 063 Array rtn=new ArrayImpl(arr.getDimension()); 064 int[] keys=arr.intKeys(); 065 for(int i=0;i<keys.length;i++) { 066 int key=keys[i]; 067 if(key<from)continue; 068 if(to>0 && key>to)break; 069 rtn.append(arr.getE(key)); 070 } 071 return rtn; 072 } 073 074}