1 /* 2 * Hunt - A refined core library for D programming language. 3 * 4 * Copyright (C) 2018-2019 HuntLabs 5 * 6 * Website: https://www.huntlabs.net/ 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 module hunt.util.Common; 12 13 14 15 /** 16 * Implementing this interface allows an object to be the target of 17 * the "for-each loop" statement. 18 * @param (T) the type of elements returned by the iterator 19 */ 20 interface Iterable(T) { 21 int opApply(scope int delegate(ref T) dg); 22 } 23 24 interface Iterable(K, V) { 25 int opApply(scope int delegate(ref K, ref V) dg); 26 } 27 28 29 /** 30 * A class implements the <code>Cloneable</code> interface to 31 * indicate to the {@link java.lang.Object#clone()} method that it 32 * is legal for that method to make a 33 * field-for-field copy of instances of that class. 34 * <p> 35 * Invoking Object's clone method on an instance that does not implement the 36 * <code>Cloneable</code> interface results in the exception 37 * <code>CloneNotSupportedException</code> being thrown. 38 * <p> 39 * By convention, classes that implement this interface should override 40 * <tt>Object.clone</tt> (which is protected) with a method. 41 * See {@link java.lang.Object#clone()} for details on overriding this 42 * method. 43 * <p> 44 * Note that this interface does <i>not</i> contain the <tt>clone</tt> method. 45 * Therefore, it is not possible to clone an object merely by virtue of the 46 * fact that it implements this interface. Even if the clone method is invoked 47 * reflectively, there is no guarantee that it will succeed. 48 */ 49 interface Cloneable { 50 } 51 52 53 interface Comparable(T) { 54 // TODO: Tasks pending completion -@zxp at 12/30/2018, 10:17:44 AM 55 // 56 // int opCmp(T o) nothrow; 57 int opCmp(T o); 58 59 deprecated("Use opCmp instead.") 60 alias compareTo = opCmp; 61 } 62 63 /** 64 * The <code>Runnable</code> interface should be implemented by any 65 * class whose instances are intended to be executed by a thread. The 66 * class must define a method of no arguments called <code>run</code>. 67 * <p> 68 * This interface is designed to provide a common protocol for objects that 69 * wish to execute code while they are active. For example, 70 * <code>Runnable</code> is implemented by class <code>Thread</code>. 71 * Being active simply means that a thread has been started and has not 72 * yet been stopped. 73 * <p> 74 * In addition, <code>Runnable</code> provides the means for a class to be 75 * active while not subclassing <code>Thread</code>. A class that implements 76 * <code>Runnable</code> can run without subclassing <code>Thread</code> 77 * by instantiating a <code>Thread</code> instance and passing itself in 78 * as the target. In most cases, the <code>Runnable</code> interface should 79 * be used if you are only planning to override the <code>run()</code> 80 * method and no other <code>Thread</code> methods. 81 * This is important because classes should not be subclassed 82 * unless the programmer intends on modifying or enhancing the fundamental 83 * behavior of the class. 84 * 85 * @author Arthur van Hoff 86 * @see Callable 87 */ 88 interface Runnable { 89 /** 90 * When an object implementing interface <code>Runnable</code> is used 91 * to create a thread, starting the thread causes the object's 92 * <code>run</code> method to be called in that separately executing 93 * thread. 94 * <p> 95 * The general contract of the method <code>run</code> is that it may 96 * take any action whatsoever. 97 */ 98 void run(); 99 } 100 101 102 /** 103 * A task that returns a result and may throw an exception. 104 * Implementors define a single method with no arguments called 105 * {@code call}. 106 * 107 * <p>The {@code Callable} interface is similar to {@link 108 * java.lang.Runnable}, in that both are designed for classes whose 109 * instances are potentially executed by another thread. A 110 * {@code Runnable}, however, does not return a result and cannot 111 * throw a checked exception. 112 * 113 * <p>The {@link Executors} class contains utility methods to 114 * convert from other common forms to {@code Callable} classes. 115 * 116 * @see Executor 117 * @author Doug Lea 118 * @param <V> the result type of method {@code call} 119 */ 120 interface Callable(V) { 121 /** 122 * Computes a result, or throws an exception if unable to do so. 123 * 124 * @return computed result 125 * @throws Exception if unable to compute a result 126 */ 127 V call(); 128 } 129 130 131 /** 132 * An object that executes submitted {@link Runnable} tasks. This 133 * interface provides a way of decoupling task submission from the 134 * mechanics of how each task will be run, including details of thread 135 * use, scheduling, etc. An {@code Executor} is normally used 136 * instead of explicitly creating threads. For example, rather than 137 * invoking {@code new Thread(new RunnableTask()).start()} for each 138 * of a set of tasks, you might use: 139 * 140 * <pre> {@code 141 * Executor executor = anExecutor(); 142 * executor.execute(new RunnableTask1()); 143 * executor.execute(new RunnableTask2()); 144 * ...}</pre> 145 * 146 * However, the {@code Executor} interface does not strictly require 147 * that execution be asynchronous. In the simplest case, an executor 148 * can run the submitted task immediately in the caller's thread: 149 * 150 * <pre> {@code 151 * class DirectExecutor implements Executor { 152 * public void execute(Runnable r) { 153 * r.run(); 154 * } 155 * }}</pre> 156 * 157 * More typically, tasks are executed in some thread other than the 158 * caller's thread. The executor below spawns a new thread for each 159 * task. 160 * 161 * <pre> {@code 162 * class ThreadPerTaskExecutor implements Executor { 163 * public void execute(Runnable r) { 164 * new Thread(r).start(); 165 * } 166 * }}</pre> 167 * 168 * Many {@code Executor} implementations impose some sort of 169 * limitation on how and when tasks are scheduled. The executor below 170 * serializes the submission of tasks to a second executor, 171 * illustrating a composite executor. 172 * 173 * <pre> {@code 174 * class SerialExecutor implements Executor { 175 * final Queue!(Runnable) tasks = new ArrayDeque<>(); 176 * final Executor executor; 177 * Runnable active; 178 * 179 * SerialExecutor(Executor executor) { 180 * this.executor = executor; 181 * } 182 * 183 * public synchronized void execute(Runnable r) { 184 * tasks.add(() -> { 185 * try { 186 * r.run(); 187 * } finally { 188 * scheduleNext(); 189 * } 190 * }); 191 * if (active is null) { 192 * scheduleNext(); 193 * } 194 * } 195 * 196 * protected synchronized void scheduleNext() { 197 * if ((active = tasks.poll()) !is null) { 198 * executor.execute(active); 199 * } 200 * } 201 * }}</pre> 202 * 203 * The {@code Executor} implementations provided in this package 204 * implement {@link ExecutorService}, which is a more extensive 205 * interface. The {@link ThreadPoolExecutor} class provides an 206 * extensible thread pool implementation. The {@link Executors} class 207 * provides convenient factory methods for these Executors. 208 * 209 * <p>Memory consistency effects: Actions in a thread prior to 210 * submitting a {@code Runnable} object to an {@code Executor} 211 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> 212 * its execution begins, perhaps in another thread. 213 * 214 * @since 1.5 215 * @author Doug Lea 216 */ 217 interface Executor { 218 219 /** 220 * Executes the given command at some time in the future. The command 221 * may execute in a new thread, in a pooled thread, or in the calling 222 * thread, at the discretion of the {@code Executor} implementation. 223 * 224 * @param command the runnable task 225 * @throws RejectedExecutionException if this task cannot be 226 * accepted for execution 227 * @throws NullPointerException if command is null 228 */ 229 void execute(Runnable command); 230 } 231 232 233 234 /** 235 * An object that may hold resources (such as file or socket handles) 236 * until it is closed. The {@link #close()} method of an {@code AutoCloseable} 237 * object is called automatically when exiting a {@code 238 * try}-with-resources block for which the object has been declared in 239 * the resource specification header. This construction ensures prompt 240 * release, avoiding resource exhaustion exceptions and errors that 241 * may otherwise occur. 242 * 243 * @apiNote 244 * <p>It is possible, and in fact common, for a base class to 245 * implement AutoCloseable even though not all of its subclasses or 246 * instances will hold releasable resources. For code that must operate 247 * in complete generality, or when it is known that the {@code AutoCloseable} 248 * instance requires resource release, it is recommended to use {@code 249 * try}-with-resources constructions. However, when using facilities such as 250 * {@link java.util.stream.Stream} that support both I/O-based and 251 * non-I/O-based forms, {@code try}-with-resources blocks are in 252 * general unnecessary when using non-I/O-based forms. 253 * 254 * @author Josh Bloch 255 */ 256 interface AutoCloseable { 257 /** 258 * Closes this resource, relinquishing any underlying resources. 259 * This method is invoked automatically on objects managed by the 260 * {@code try}-with-resources statement. 261 * 262 * <p>While this interface method is declared to throw {@code 263 * Exception}, implementers are <em>strongly</em> encouraged to 264 * declare concrete implementations of the {@code close} method to 265 * throw more specific exceptions, or to throw no exception at all 266 * if the close operation cannot fail. 267 * 268 * <p> Cases where the close operation may fail require careful 269 * attention by implementers. It is strongly advised to relinquish 270 * the underlying resources and to internally <em>mark</em> the 271 * resource as closed, prior to throwing the exception. The {@code 272 * close} method is unlikely to be invoked more than once and so 273 * this ensures that the resources are released in a timely manner. 274 * Furthermore it reduces problems that could arise when the resource 275 * wraps, or is wrapped, by another resource. 276 * 277 * <p><em>Implementers of this interface are also strongly advised 278 * to not have the {@code close} method throw {@link 279 * InterruptedException}.</em> 280 * 281 * This exception interacts with a thread's interrupted status, 282 * and runtime misbehavior is likely to occur if an {@code 283 * InterruptedException} is {@linkplain Throwable#addSuppressed 284 * suppressed}. 285 * 286 * More generally, if it would cause problems for an 287 * exception to be suppressed, the {@code AutoCloseable.close} 288 * method should not throw it. 289 * 290 * <p>Note that unlike the {@link java.io.Closeable#close close} 291 * method of {@link java.io.Closeable}, this {@code close} method 292 * is <em>not</em> required to be idempotent. In other words, 293 * calling this {@code close} method more than once may have some 294 * visible side effect, unlike {@code Closeable.close} which is 295 * required to have no effect if called more than once. 296 * 297 * However, implementers of this interface are strongly encouraged 298 * to make their {@code close} methods idempotent. 299 * 300 * @throws Exception if this resource cannot be closed 301 */ 302 void close(); 303 } 304 305 306 interface Closeable : AutoCloseable { 307 308 } 309 310 311 312 /** 313 * An object to which {@code char} sequences and values can be appended. The 314 * {@code Appendable} interface must be implemented by any class whose 315 * instances are intended to receive formatted output from a {@link 316 * java.util.Formatter}. 317 * 318 * <p> The characters to be appended should be valid Unicode characters as 319 * described in <a href="Character.html#unicode">Unicode Character 320 * Representation</a>. Note that supplementary characters may be composed of 321 * multiple 16-bit {@code char} values. 322 * 323 * <p> Appendables are not necessarily safe for multithreaded access. Thread 324 * safety is the responsibility of classes that extend and implement this 325 * interface. 326 * 327 * <p> Since this interface may be implemented by existing classes 328 * with different styles of error handling there is no guarantee that 329 * errors will be propagated to the invoker. 330 * 331 */ 332 interface Appendable { 333 334 /** 335 * Appends the specified character sequence to this {@code Appendable}. 336 * 337 * <p> Depending on which class implements the character sequence 338 * {@code csq}, the entire sequence may not be appended. For 339 * instance, if {@code csq} is a {@link java.nio.CharBuffer} then 340 * the subsequence to append is defined by the buffer's position and limit. 341 * 342 * @param csq 343 * The character sequence to append. If {@code csq} is 344 * {@code null}, then the four characters {@code "null"} are 345 * appended to this Appendable. 346 * 347 * @return A reference to this {@code Appendable} 348 * 349 * @throws IOException 350 * If an I/O error occurs 351 */ 352 Appendable append(string csq); 353 354 /** 355 * Appends a subsequence of the specified character sequence to this 356 * {@code Appendable}. 357 * 358 * <p> An invocation of this method of the form {@code out.append(csq, start, end)} 359 * when {@code csq} is not {@code null}, behaves in 360 * exactly the same way as the invocation 361 * 362 * <pre> 363 * out.append(csq.subSequence(start, end)) </pre> 364 * 365 * @param csq 366 * The character sequence from which a subsequence will be 367 * appended. If {@code csq} is {@code null}, then characters 368 * will be appended as if {@code csq} contained the four 369 * characters {@code "null"}. 370 * 371 * @param start 372 * The index of the first character in the subsequence 373 * 374 * @param end 375 * The index of the character following the last character in the 376 * subsequence 377 * 378 * @return A reference to this {@code Appendable} 379 * 380 * @throws IndexOutOfBoundsException 381 * If {@code start} or {@code end} are negative, {@code start} 382 * is greater than {@code end}, or {@code end} is greater than 383 * {@code csq.length()} 384 * 385 * @throws IOException 386 * If an I/O error occurs 387 */ 388 // Appendable append(CharSequence csq, int start, int end); 389 390 /** 391 * Appends the specified character to this {@code Appendable}. 392 * 393 * @param c 394 * The character to append 395 * 396 * @return A reference to this {@code Appendable} 397 * 398 * @throws IOException 399 * If an I/O error occurs 400 */ 401 Appendable append(char c); 402 } 403 404 405 /** 406 * A tagging interface that all event listener interfaces must extend. 407 */ 408 interface EventListener { 409 } 410 411 412 /** 413 * <p> 414 * A callback abstraction that handles completed/failed events of asynchronous 415 * operations. 416 * </p> 417 * <p> 418 * <p> 419 * Semantically this is equivalent to an optimise Promise<Void>, but 420 * callback is a more meaningful name than EmptyPromise 421 * </p> 422 */ 423 interface Callback { 424 /** 425 * Instance of Adapter that can be used when the callback methods need an 426 * empty implementation without incurring in the cost of allocating a new 427 * Adapter object. 428 */ 429 __gshared Callback NOOP; 430 431 shared static this() { 432 NOOP = new NoopCallback(); 433 } 434 435 /** 436 * <p> 437 * Callback invoked when the operation completes. 438 * </p> 439 * 440 * @see #failed(Throwable) 441 */ 442 void succeeded(); 443 444 /** 445 * <p> 446 * Callback invoked when the operation fails. 447 * </p> 448 * 449 * @param x the reason for the operation failure 450 */ 451 void failed(Exception x); 452 453 /** 454 * @return True if the callback is known to never block the caller 455 */ 456 bool isNonBlocking(); 457 } 458 459 /** 460 */ 461 class NestedCallback : Callback { 462 private Callback callback; 463 464 this(Callback callback) { 465 this.callback = callback; 466 } 467 468 this(NestedCallback nested) { 469 this.callback = nested.callback; 470 } 471 472 Callback getCallback() { 473 return callback; 474 } 475 476 void succeeded() { 477 callback.succeeded(); 478 } 479 480 void failed(Exception x) { 481 callback.failed(x); 482 } 483 484 bool isNonBlocking() { 485 return callback.isNonBlocking(); 486 } 487 } 488 489 /** 490 * <p> 491 * A callback abstraction that handles completed/failed events of asynchronous 492 * operations. 493 * </p> 494 * <p> 495 * <p> 496 * Semantically this is equivalent to an optimise Promise<Void>, but 497 * callback is a more meaningful name than EmptyPromise 498 * </p> 499 */ 500 class NoopCallback : Callback { 501 /** 502 * <p> 503 * Callback invoked when the operation completes. 504 * </p> 505 * 506 * @see #failed(Throwable) 507 */ 508 void succeeded() { 509 } 510 511 /** 512 * <p> 513 * Callback invoked when the operation fails. 514 * </p> 515 * 516 * @param x the reason for the operation failure 517 */ 518 void failed(Exception x) { 519 } 520 521 /** 522 * @return True if the callback is known to never block the caller 523 */ 524 bool isNonBlocking() { 525 return false; 526 } 527 } 528 529 530 /** 531 */ 532 class CompilerHelper { 533 534 static bool isGreaterThan(int ver) pure @safe @nogc nothrow { 535 return __VERSION__ >= ver; 536 } 537 538 static bool isLessThan(int ver) pure @safe @nogc nothrow { 539 return __VERSION__ <= ver; 540 } 541 } 542