1 package net.sf.saxon.functions; 2 import net.sf.saxon.expr.XPathContext; 3 import net.sf.saxon.om.*; 4 import net.sf.saxon.trans.DynamicError; 5 import net.sf.saxon.trans.XPathException; 6 import net.sf.saxon.value.NumericValue; 7 import net.sf.saxon.value.StringValue; 8 9 12 13 public class Unicode extends SystemFunction { 14 15 public static final int TO_CODEPOINTS = 0; 16 public static final int FROM_CODEPOINTS = 1; 17 18 21 22 public Item evaluateItem(XPathContext c) throws XPathException { 23 switch (operation) { 24 case TO_CODEPOINTS: 25 throw new UnsupportedOperationException ("Cannot call evaluateItem on a sequence"); 26 case FROM_CODEPOINTS: 27 return StringValue.makeStringValue(unicodeToString(argument[0].iterate(c), c)); 28 default: 29 throw new UnsupportedOperationException ("Unknown Unicode operation"); 30 } 31 } 32 33 public SequenceIterator iterate(XPathContext c) throws XPathException { 34 switch (operation) { 35 case TO_CODEPOINTS: 36 Item item = argument[0].evaluateItem(c); 37 if (item==null) { 38 return EmptyIterator.getInstance(); 39 } 40 return stringToUnicode(item.getStringValueCS()); 41 case FROM_CODEPOINTS: 42 return SingletonIterator.makeIterator(evaluateItem(c)); 43 default: 44 throw new UnsupportedOperationException ("Unknown Unicode operation"); 45 } 46 } 47 48 52 53 private static SequenceIterator stringToUnicode(CharSequence s) { 54 return StringValue.makeStringValue(s).iterateCharacters(); 55 } 56 57 60 61 private static CharSequence unicodeToString(SequenceIterator chars, XPathContext context) throws XPathException { 62 FastStringBuffer sb = new FastStringBuffer(256); 63 while (true) { 64 NumericValue nextInt = (NumericValue)chars.next(); 65 if (nextInt == null) { 66 return sb.condense(); 67 } 68 long next = nextInt.longValue(); 69 if (next > Integer.MAX_VALUE || !XMLChar.isValid((int)next)) { 70 DynamicError e = new DynamicError("Invalid XML character [decimal " + next + ']'); 71 e.setErrorCode("FOCH0001"); 72 e.setXPathContext(context); 73 throw e; 74 } 75 if (next<65536) { 76 sb.append((char)next); 77 } else { sb.append(XMLChar.highSurrogate((int)next)); 79 sb.append(XMLChar.lowSurrogate((int)next)); 80 } 81 } 82 } 83 84 85 } 86 87 88 89 | Popular Tags |