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