1/* 2 * Copyright (C) 2010 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 17package com.google.clearsilver.jsilver.functions.string; 18 19import com.google.clearsilver.jsilver.functions.NonEscapingFunction; 20import com.google.clearsilver.jsilver.values.Value; 21import static com.google.clearsilver.jsilver.values.Value.literalConstant; 22import static com.google.clearsilver.jsilver.values.Value.literalValue; 23 24import static java.lang.Math.max; 25import static java.lang.Math.min; 26 27/** 28 * Returns the string slice starting at start and ending at end, similar to the Python slice 29 * operator. 30 */ 31public class SliceFunction extends NonEscapingFunction { 32 33 /** 34 * @param args 1 string values then 2 numeric values (start and end). 35 * @return Sliced string 36 */ 37 public Value execute(Value... args) { 38 Value stringValue = args[0]; 39 Value startValue = args[1]; 40 Value endValue = args[2]; 41 String string = stringValue.asString(); 42 int start = startValue.asNumber(); 43 int end = endValue.asNumber(); 44 int length = string.length(); 45 46 if (start < 0) { 47 start += max(-start, length); 48 if (end == 0) { 49 end = length; 50 } 51 } 52 53 if (end < 0) { 54 end += length; 55 } 56 57 end = min(end, length); 58 59 if (end < start) { 60 return literalConstant("", args[0]); 61 } 62 63 return literalValue(string.substring(start, end), stringValue.getEscapeMode(), stringValue 64 .isPartiallyEscaped() 65 || startValue.isPartiallyEscaped() || endValue.isPartiallyEscaped()); 66 } 67} 68