1 32 package org.jruby.util; 33 34 import org.jruby.Ruby; 35 36 40 public class IOModes implements Cloneable { 41 public static final int RDONLY = 0; 42 public static final int WRONLY = 1; 43 public static final int RDWR = 2; 44 public static final int CREAT = 64; 45 public static final int EXCL = 128; 46 public static final int NOCTTY = 256; 47 public static final int TRUNC = 512; 48 public static final int APPEND = 1024; 49 public static final int NONBLOCK = 2048; 50 public static final int BINARY = 4096; 51 52 private Ruby runtime; 53 private int modes; 54 55 public IOModes(Ruby runtime) { 56 modes = 0; 57 this.runtime = runtime; 58 } 59 60 public Object clone() { 61 try { 62 return super.clone(); 63 } catch (CloneNotSupportedException cnse) { 64 return null; 66 } 67 } 68 69 public IOModes(Ruby runtime, String modesString) { 70 this(runtime, convertModesStringToModesInt(runtime, modesString)); 71 } 72 73 public IOModes(Ruby runtime, long modes) { 74 this.modes = (int)modes; 77 this.runtime = runtime; 78 } 79 80 public boolean isReadable() { 81 return (modes & RDWR) != 0 || modes == RDONLY || modes == BINARY; 82 } 83 84 public boolean isWriteable() { 85 return isWritable(); 86 } 87 88 public boolean isBinary() { 89 return (modes & BINARY) == BINARY; 90 } 91 92 public boolean isWritable() { 93 return (modes & RDWR) != 0 || (modes & WRONLY) != 0 || (modes & CREAT) != 0; 94 } 95 96 public boolean isAppendable() { 97 return (modes & APPEND) != 0; 98 } 99 100 public boolean shouldTruncate() { 101 return (modes & TRUNC) != 0; 102 } 103 104 public void checkSubsetOf(IOModes superset) { 106 if ((!superset.isReadable() && isReadable()) || 107 (!superset.isWriteable() && isWriteable()) || 108 !superset.isAppendable() && isAppendable()) { 109 throw runtime.newErrnoEINVALError("bad permissions"); 110 } 111 } 112 113 public String toString() { 115 return ""+modes; 116 } 117 118 public static int convertModesStringToModesInt(Ruby runtime, 119 String modesString) { 120 int modes = 0; 121 122 if (modesString.length() == 0) { 123 throw runtime.newArgumentError("illegal access mode"); 124 } 125 126 switch (modesString.charAt(0)) { 127 case 'r' : 128 modes |= RDONLY; 129 break; 130 case 'a' : 131 modes |= APPEND; 132 modes |= WRONLY; 133 break; 134 case 'w' : 135 modes |= WRONLY; 136 modes |= TRUNC; 137 break; 138 default : 139 throw runtime.newArgumentError("illegal access mode " + modes); 140 } 141 142 if (modesString.length() > 1) { 143 int i = modesString.charAt(1) == 'b' ? 2 : 1; 144 145 if (modesString.length() > i) { 146 if (modesString.charAt(i) == '+') { 147 if ((modes & APPEND) != 0) { 148 modes = RDWR | APPEND; 149 } else if ((modes & WRONLY) != 0){ 150 modes = RDWR | TRUNC; 151 } else { 152 modes = RDWR; 153 } 154 } else { 155 throw runtime.newArgumentError("illegal access mode " + modes); 156 } 157 } 158 if (i == 2) { 159 modes |= BINARY; 160 } 161 162 } 163 return modes; 164 } 165 } 166 | Popular Tags |