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 17 package com.google.clearsilver.jsilver.functions.string; 18 19 import com.google.clearsilver.jsilver.functions.NonEscapingFunction; 20 import com.google.clearsilver.jsilver.values.Value; 21 import static com.google.clearsilver.jsilver.values.Value.literalConstant; 22 23 import java.io.UnsupportedEncodingException; 24 import java.util.zip.CRC32; 25 import java.util.zip.Checksum; 26 27 /** 28 * Returns the CRC-32 of a string. 29 */ 30 public class CrcFunction extends NonEscapingFunction { 31 32 /** 33 * @param args 1 string expression 34 * @return CRC-32 of string as number value 35 */ execute(Value... args)36 public Value execute(Value... args) { 37 String string = args[0].asString(); 38 // This function produces a 'standard' CRC-32 (IV -1, reflected polynomial, 39 // and final complement step). The CRC-32 of "123456789" is 0xCBF43926. 40 Checksum crc = new CRC32(); 41 byte[] b; 42 try { 43 b = string.getBytes("UTF-8"); 44 } catch (UnsupportedEncodingException e) { 45 throw new AssertionError("UTF-8 must be supported"); 46 } 47 crc.update(b, 0, b.length); 48 // Note that we need to cast to signed int, but that's okay because the 49 // CRC fits into 32 bits by definition. 50 return literalConstant((int) crc.getValue(), args[0]); 51 } 52 } 53