1 28 29 package org.jruby.util; 30 31 import java.nio.charset.Charset ; 32 import java.nio.charset.CharsetDecoder ; 33 import java.nio.charset.CharsetEncoder ; 34 import java.util.regex.Pattern ; 35 import org.jruby.Ruby; 36 import org.jruby.charset.PlainCharset; 37 import org.jruby.runtime.builtin.IRubyObject; 38 39 public class KCode { 40 public static final KCode NIL = new KCode(null); 41 public static final KCode NONE = new KCode("NONE"); 42 public static final KCode UTF8 = new KCode("UTF8"); 43 public static final KCode SJIS = new KCode("SJIS"); 44 public static final KCode EUC = new KCode("EUC"); 45 46 private String kcode; 47 48 private KCode(String kcode) { 49 this.kcode = kcode; 50 } 51 52 public static KCode create(Ruby runtime, String lang) { 53 if(lang == null) { 54 return NIL; 55 } 56 57 switch(lang.charAt(0)) { 58 case 'E': 59 case 'e': 60 runtime.getWarnings().warn("JRuby supports only Unicode regexp."); 61 return EUC; 62 case 'S': 63 case 's': 64 runtime.getWarnings().warn("JRuby supports only Unicode regexp."); 65 return SJIS; 66 case 'U': 67 case 'u': 68 return UTF8; 69 case 'N': 70 case 'n': 71 case 'A': 72 case 'a': 73 return NONE; 74 } 75 return NIL; 76 } 77 78 public IRubyObject kcode(Ruby runtime) { 79 if (kcode == null) { 80 return runtime.getNil(); 81 } 82 return runtime.newString(kcode); 83 } 84 85 public CharsetDecoder decoder() { 86 if (this == UTF8) { 87 return Charset.forName("UTF-8").newDecoder(); 88 } 89 90 return new PlainCharset().newDecoder(); 91 } 92 93 public CharsetEncoder encoder() { 94 if (this == UTF8) { 95 return Charset.forName("UTF-8").newEncoder(); 96 } 97 98 return new PlainCharset().newEncoder(); 99 } 100 101 public int flags() { 102 int flags = 0; 103 if (this == UTF8) { 104 flags |= Pattern.UNICODE_CASE; 105 } 106 flags |= Pattern.UNIX_LINES; 107 108 return flags; 109 } 110 } 111 112 | Popular Tags |