1 package net.sf.saxon.functions; 2 import net.sf.saxon.expr.XPathContext; 3 import net.sf.saxon.om.Item; 4 import net.sf.saxon.om.FastStringBuffer; 5 import net.sf.saxon.trans.XPathException; 6 import net.sf.saxon.value.AtomicValue; 7 import net.sf.saxon.value.StringValue; 8 9 10 11 public class Translate extends SystemFunction { 12 13 16 17 public Item evaluateItem(XPathContext context) throws XPathException { 18 19 AtomicValue sv = (AtomicValue)argument[0].evaluateItem(context); 20 if (sv==null) { 21 return StringValue.EMPTY_STRING; 22 }; 23 CharSequence s1 = sv.getStringValueCS(); 24 25 sv = (AtomicValue)argument[1].evaluateItem(context); 26 CharSequence s2 = sv.getStringValueCS(); 27 28 sv = (AtomicValue)argument[2].evaluateItem(context); 29 CharSequence s3 = sv.getStringValueCS(); 30 31 return StringValue.makeStringValue(translate(s1, s2, s3)); 32 } 33 34 37 38 private static CharSequence translate(CharSequence s0, CharSequence s1, CharSequence s2) { 39 40 int len0 = StringValue.getStringLength(s0); 42 int len1 = StringValue.getStringLength(s1); 43 int len2 = StringValue.getStringLength(s2); 44 if (s0.length()!=len0 || 45 s1.length()!=len1 || 46 s2.length()!=len2 ) { 47 return slowTranslate(s0, s1, s2); 48 } 49 String st1 = s1.toString(); 50 FastStringBuffer sb = new FastStringBuffer(s0.length()); 51 int s2len = s2.length(); 52 for (int i=0; i<s0.length(); i++) { 53 char c = s0.charAt(i); 54 int j = st1.indexOf(c); 55 if (j<s2len) { 56 sb.append(( j<0 ? c : s2.charAt(j) )); 57 } 58 } 59 return sb; 60 } 61 62 65 66 private static CharSequence slowTranslate(CharSequence s0, CharSequence s1, CharSequence s2) { 67 int[] a0 = StringValue.expand(s0); 68 int[] a1 = StringValue.expand(s1); 69 int[] a2 = StringValue.expand(s2); 70 StringBuffer sb = new StringBuffer (s0.length()); 71 for (int i=0; i<a0.length; i++) { 72 int c = a0[i]; 73 int j = -1; 74 for (int test=0; test<a1.length; test++) { 75 if (a1[test]==c) { 76 j = test; 77 break; 78 } 79 } 80 int newchar = -1; 81 if (j<0) { 82 newchar = a0[i]; 83 } else if (j<a2.length) { 84 newchar = a2[j]; 85 } else { 86 } 88 89 if (newchar>=0) { 90 if (newchar<65536) { 91 sb.append((char)newchar); 92 } 93 else { newchar -= 65536; 98 sb.append((char)((newchar / 1024) + 55296)); 99 sb.append((char)((newchar % 1024) + 56320)); 100 } 101 } 102 } 103 return sb; 104 } 105 106 107 } 108 109 110 111 | Popular Tags |