index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/AbstractTask.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Skeletal implementation of a stateful {@link Task}.
*/
public abstract class AbstractTask implements Task {
/**
* Context used to manage this {@code Task}; {@code null} if this {@code
* Task} is not bound to an execution {@link Stage}.
*/
protected TaskContext taskContext;
@Override
public final TaskContext taskContext() {
return this.taskContext;
}
@Override
public void setTaskContext(TaskContext taskContext) {
this.taskContext = taskContext;
}
@Override
public abstract void runTask();
@Override
public boolean taskWillBlock() {
return false;
}
@Override
public void taskWillCue() {
// stub
}
@Override
public void taskDidCancel() {
// stub
}
/**
* Returns the execution {@code Stage} to which this task is bound.
* Delegates to the assigned {@link #taskContext}.
*
* @throws TaskException if {@link #taskContext} is {@code null}.
*/
public Stage stage() {
final TaskContext taskContext = this.taskContext;
if (taskContext == null) {
throw new TaskException("Unbound Task");
}
return taskContext.stage();
}
/**
* Returns {@code true} if the task is currently scheduled for execution.
* Delegates to the assigned {@link #taskContext}, if set; otherwise returns
* {@code false}.
*/
public boolean isCued() {
final TaskContext taskContext = this.taskContext;
return taskContext != null && taskContext.isCued();
}
/**
* Schedules this task to execute as a sequential process. Returns {@code
* true} if this operation caused the scheduling of this task; returns {@code
* false} if this task was already scheduled to execute. This task becomes
* uncued prior to the the invocation of {@code runTask()}, enabling this
* task to re-cue itself while running. Delegates to the assigned {@link
* #taskContext}.
*
* @throws TaskException if {@link #taskContext} is {@code null}.
*/
public boolean cue() {
final TaskContext taskContext = this.taskContext;
if (taskContext == null) {
throw new TaskException("Unbound Task");
}
return taskContext.cue();
}
/**
* Cancels this task to prevent it from executing. Returns {@code true} if
* this operation caused the cancellation of this task; returns {@code false}
* if this task was not scheduled to execute. Delegates to the assigned
* {@link #taskContext}.
*/
public boolean cancel() {
final TaskContext taskContext = this.taskContext;
if (taskContext == null) {
return false;
}
return taskContext.cancel();
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/AbstractTimer.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Skeletal implementation of a stateful {@link Timer}.
*/
public abstract class AbstractTimer implements Timer {
/**
* Context used to manage this {@code Timer}; {@code null} if this {@code
* Timer} is not bound to a {@link Schedule}.
*/
protected TimerContext timerContext;
@Override
public final TimerContext timerContext() {
return this.timerContext;
}
@Override
public void setTimerContext(TimerContext timerContext) {
this.timerContext = timerContext;
}
@Override
public abstract void runTimer();
@Override
public void timerWillSchedule(long millis) {
// stub
}
@Override
public void timerDidCancel() {
// stub
}
/**
* Returns the {@code Schedule} to which this timer is bound. Delegates to
* the assigned {@link #timerContext}.
*
* @throws TimerException if {@link #timerContext} is {@code null}.
*/
public Schedule schedule() {
final TimerContext timerContext = this.timerContext;
if (timerContext == null) {
throw new TimerException("Unbound Timer");
}
return timerContext.schedule();
}
/**
* Returns {@code true} if this timer is currently scheduled to execute.
* Delegates to the assigned {@link #timerContext}, if set; otherwise returns
* {@code false}.
*/
public boolean isScheduled() {
final TimerContext timerContext = this.timerContext;
return timerContext != null && timerContext.isScheduled();
}
/**
* Schedules this timer to execute after {@code millis} milliseconds has
* elapsed. If this timer is currently scheduled, it will not execute at its
* previously scheduled time; it will only execute at the newly scheduled
* time. Delegates to the assigned {@link #timerContext}.
*
* @throws TimerException if {@link #timerContext} is {@code null}, or if
* {@code millis} is negative.
*/
public void reschedule(long millis) {
final TimerContext timerContext = this.timerContext;
if (timerContext == null) {
throw new TimerException("Unbound Timer");
}
timerContext.reschedule(millis);
}
/**
* Cancels this timer to prevent it from executing. Returns {@code true} if
* this operation caused the cancellation of this timer; returns {@code false}
* if this {@code Timer} was not scheduled to execute.
*/
public boolean cancel() {
final TimerContext timerContext = this.timerContext;
if (timerContext == null) {
return false;
}
return timerContext.cancel();
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Call.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Handle used to eventually complete an asynchronous operation by invoking a
* {@link Cont}inuation. A {@code Call} abstracts over the execution context
* in which a {@code Cont}inuation runs. Think of a {@code Call} as a way to
* asynchronously invoke {@link Cont#bind(Object) Cont.bind(T)}, and {@code
* Cont#trap(Throwable)}. Use {@link Stage#call(Cont)} to get a {@code Call}
* that asynchronously executes a {@code Cont}inuation on an execution {@code
* Stage}.
*
* @see Cont
* @see Stage
*/
public interface Call<T> extends Cont<T> {
/**
* Returns the {@code Cont}inuation that this {@code Call} completes.
*/
Cont<T> cont();
/**
* Completes this {@code Call} with a {@code value} by eventually invoking
* the {@link Cont#bind(Object) bind(T)} method of this {@code Call}'s {@code
* Cont}inuation.
*
* @throws ContException if this {@code Call} has already been completed.
*/
void bind(T value);
/**
* Completes this {@code Call} with an {@code error} by eventually invoking
* the {@link Cont#trap(Throwable) trap(Throwable)} method of this {@code
* Call}'s {@code Cont}inuation.
*
* @throws ContException if this {@code Call} has already been completed.
*/
void trap(Throwable error);
/**
* Tries to complete this {@code Call} with a {@code value}, returning {@code
* true} if this operation caused the completion of the {@code Call}; returns
* {@code false} if this {@code Call} was already completed. If successful,
* the {@link Cont#bind(Object) bind(T)} method of this {@code Call}'s {@code
* Cont}inuation will eventually be invoked.
*/
boolean tryBind(T value);
/**
* Tries to complete this {@code Call} with an {@code error}, returning
* {@code true} if this operation caused the completion of the {@code Call};
* returns {@code false} if this {@code Call} was already completed. If
* successful, the {@link Cont#trap(Throwable) trap(Throwable)} method of
* this {@code Call}'s {@code Cont}inuation will eventually be invoked.
*/
boolean tryTrap(Throwable error);
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Clock.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* Hashed wheel timer {@link Schedule}.
*/
public class Clock implements Schedule {
/**
* Immutable array of {@link #tickCount} timer buckets, each containing a
* lock-free queue of timer events to execute for a particular modulus of
* clock ticks.
*/
final ClockQueue[] dial;
/**
* Barrier used to sequence clock startup.
*/
final CountDownLatch startLatch;
/**
* Barrier used to sequence clock shutdown.
*/
final CountDownLatch stopLatch;
/**
* Thread that executes timer events at their scheduled times.
*/
final ClockThread thread;
/**
* Time at which the clock started, in nanoseconds, with arbitrary origin.
* Set exactly once when the clock thread starts.
*/
volatile long startTime;
/**
* Number of nanoseconds between successive clock ticks.
*/
final long tickNanos;
/**
* Number of ticks per clock revolution.
*/
final int tickCount;
/**
* Atomic bit field with {@link #STARTED} and {@link #STOPPED} flags.
*/
volatile int status;
/**
* Constructs a new {@code Clock} with a timer resolution of {@code
* tickMillis} milliseconds, and a clock period of {@code tickCount} ticks
* per revolution.
*/
public Clock(int tickMillis, int tickCount) {
// Initialize the number of nanoseconds between clock ticks.
if (tickMillis <= 0) {
throw new IllegalArgumentException(Long.toString(tickMillis));
}
this.tickNanos = (long) tickMillis * 1000000L;
// Initialize the number of ticks per clock revolution.
if (tickCount <= 0) {
throw new IllegalArgumentException(Integer.toString(tickCount));
}
// Round the tick count up to the next power of two.
tickCount = tickCount - 1;
tickCount |= tickCount >> 1;
tickCount |= tickCount >> 2;
tickCount |= tickCount >> 4;
tickCount |= tickCount >> 8;
tickCount |= tickCount >> 16;
tickCount = tickCount + 1;
this.tickCount = tickCount;
// Initialize the clock dial with one revolution worth of clock ticks.
this.dial = new ClockQueue[tickCount];
for (int i = 0; i < tickCount; i += 1) {
this.dial[i] = new ClockQueue((long) i);
}
// Initialize the barrier used to sequence clock startup.
this.startLatch = new CountDownLatch(1);
// Initialize the barrier used to sequence clock shutdown.
this.stopLatch = new CountDownLatch(1);
// Initialize--but don't start--the clock thread.
this.thread = new ClockThread(this);
}
/**
* Constructs a new {@code Clock} with the timer resolution and clock period
* specified by the given {@code clockDef}.
*/
public Clock(ClockDef clockDef) {
this(clockDef.tickMillis, clockDef.tickCount);
}
/**
* Constructs a new {@code Clock} with a timer resolution of {@link
* #TICK_MILLIS} milliseconds, and a clock period of {@link #TICK_COUNT}
* ticks per revolution.
*/
public Clock() {
this(TICK_MILLIS, TICK_COUNT);
}
/**
* Returns the tick sequence number of the lowest clock tick that has yet to
* finish executing.
*/
public final long tick() {
return this.thread.tick;
}
/**
* Ensures that this {@code Clock} is up and running, starting up the clock
* thread if it has not yet been started.
*
* @throws ScheduleException if this {@code Clock} has been stopped.
*/
public final void start() {
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & STOPPED) == 0) {
// Clock hasn't yet stopped; make sure it has started.
if ((oldStatus & STARTED) == 0) {
final int newStatus = oldStatus | STARTED;
// Try to set the STARTED flag; linearization point for clock startup.
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
// Initiate clock thread startup.
willStart();
this.thread.start();
break;
}
} else {
// Clock thread already started.
break;
}
} else {
throw new ScheduleException("Can't restart stopped clock");
}
} while (true);
// Loop while the clock thread is not yet up and running.
boolean interrupted = false;
while (this.startLatch.getCount() != 0) {
try {
// Wait for clock thread startup to complete.
this.startLatch.await();
} catch (InterruptedException error) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
/**
* Ensures that this {@code Clock} has been permanently stopped, shutting
* down the clock thread, if it's currently running. Upon return, this
* {@code Clock} is guaranteed to be in the <em>stopped</em> state.
*/
public final void stop() {
boolean interrupted = false;
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & STOPPED) == 0) {
// Clock hasn't yet stopped; try to stop it.
final int newStatus = oldStatus | STOPPED;
// Try to set the STOPPED flag; linearization point for clock shutdown.
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
// Loop while the clock thread is still running.
while (this.thread.isAlive()) {
// Interrupt the clock thread so it will wakeup and die.
this.thread.interrupt();
try {
// Wait for the clock thread to exit.
this.thread.join(100);
} catch (InterruptedException error) {
interrupted = true;
}
}
}
} else {
// Clock thread already stopped.
break;
}
} while (true);
// Loop while the clock thread is still running.
while (this.stopLatch.getCount() != 0) {
try {
// Wait for clock thread shutdown to complete.
this.stopLatch.await();
} catch (InterruptedException e) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
@Override
public TimerRef timer(TimerFunction timer) {
// Ensure that the clock has started.
start();
// Create the context that binds the timer to this clock.
final ClockTimer context = new ClockTimer(this, timer);
if (timer instanceof Timer) {
((Timer) timer).setTimerContext(context);
}
// Return the timer context.
return context;
}
@Override
public TimerRef setTimer(long millis, TimerFunction timer) {
if (millis < 0L) {
throw new TimerException("negative timeout: " + Long.toString(millis));
}
// Ensure that the clock has started.
start();
// Create the context that binds the timer to this clock.
final ClockTimer context = new ClockTimer(this, timer);
if (timer instanceof Timer) {
((Timer) timer).setTimerContext(context);
}
// Schedule the timer for execution.
schedule(millis, context);
// Return the timer context.
return context;
}
/**
* Schedules a bound timer {@code context} for execution after {@code millis}
* milliseconds has elapsed.
*/
final void schedule(long millis, ClockTimer context) {
// Invoke timer scheduling introspection callbacks.
timerWillSchedule(context.timer, millis);
if (context.timer instanceof Timer) {
((Timer) context.timer).timerWillSchedule(millis);
}
// Convert the timeout to nanoseconds.
final long nanos = millis * 1000000L;
// Compute the deadline for the timer in nanoseconds since clock start.
final long deadline = Math.max(0L, nanoTime() + nanos - this.startTime);
// Divide the deadline by the tick interval to get the tick sequence number
// at which to fire the timer, rounding up to the next tick.
long targetTick = (deadline + (this.tickNanos - 1L)) / this.tickNanos;
// Take the modulus of the target tick with respect to to the number of
// ticks per clock revolution, yielding the index in the dial at which to
// insert the event.
int targetHand = (int) (targetTick % (long) this.tickCount);
// Create a timer event to insert into the clock.
final ClockEvent newEvent = new ClockEvent(0L, targetTick, context, context.timer);
// Atomically get the current timer event, and replace it with the
// to-be-scheduled event; linearization point for timer un-cancellation.
final ClockEvent oldEvent = ClockTimer.EVENT.getAndSet(context, newEvent);
// Check if the timer had a previously scheduled event.
if (oldEvent != null) {
// Remove the timer from the previously scheduled event;
// linearization point for timer cancellation.
oldEvent.cancel();
}
// Get the event queue for the target hand of the clock.
ClockQueue queue = this.dial[targetHand];
// Capture the current foot of the queue.
ClockEvent foot = queue.foot;
// Search for the last event of in the queue, starting with foot.
ClockEvent prev = foot;
// Loop until the event is inserted into the first queue that will execute
// after the timer deadline.
do {
// Load the next event after the currently referenced last event.
final ClockEvent next = prev.next;
if (next == null) {
// prev is the last event in the queue.
if (targetTick >= prev.insertTick) {
// prev was inserted before the target tick, indicating that the
// timer thread hasn't finished executing the target tick yet.
// prev.insertTick is the next tick sequence number that the clock
// thread will execute for the queue; set event.insertTick to match.
newEvent.insertTick = prev.insertTick;
// Try to insert the new event to the end of the queue;
// linearization point for timer scheduling.
if (ClockEvent.NEXT.compareAndSet(prev, null, newEvent)) {
// Only update the foot reference if it lags at least two events
// behind the last event in the queue.
if (prev != foot) {
// Try to update the foot reference; ok if this fails.
ClockQueue.FOOT.compareAndSet(queue, foot, newEvent);
}
break;
}
// Lost insertion race to another thread; try again.
} else {
// The clock thread is currently executing, or has already executed,
// the target tick; try the next hand of the clock.
targetTick += 1L;
targetHand = (int) (targetTick % (long) this.tickCount);
queue = this.dial[targetHand];
foot = queue.foot;
prev = foot;
}
} else {
// Jump to the new foot, if the previously loaded foot lags at least two
// events behind the prev event; otherwise advance to the next event.
final ClockEvent newFoot = queue.foot;
if (foot != newFoot) {
foot = newFoot;
prev = foot;
} else {
prev = next;
}
}
} while (true);
}
/**
* Lifecycle callback invoked before the clock thread starts.
*/
protected void willStart() {
// stub
}
/**
* Lifecycle callback invoked after the clock thread starts.
*/
protected void didStart() {
// stub
}
/**
* Introspection callback invoked after each tick of the clock. {@code tick}
* is the sequence number of the tick that was executed; {@code waitedMillis}
* is the number of milliseconds the clock thread slept before executing the
* tick. If {@code waitedMillis} is negative, then the clock thread didn't
* start executing the tick until {@code -waitedMillis} milliseconds after
* the scheduled tick deadline.
*/
protected void didTick(long tick, long waitedMillis) {
// stub
}
/**
* Lifecycle callback invoked before the clock thread stops.
*/
protected void willStop() {
// stub
}
/**
* Lifecycle callback invoked after the clock thread stops.
*/
protected void didStop() {
// stub
}
/**
* Lifecycle callback invoked if the timer thread throws a fatal {@code
* error}. The clock thread will stop after invoking {@code didFail}.
*/
protected void didFail(Throwable error) {
error.printStackTrace();
}
/**
* Introspection callback invoked before a {@code timer} is scheduled for
* execution with a delay of {@code millis} milliseconds.
*/
protected void timerWillSchedule(TimerFunction timer, long millis) {
// stub
}
/**
* Introspection callback invoked after a {@code timer} has been explicitly
* cancelled; not invoked when a timer is implicitly cancelled, such as when
* rescheduling an already scheduled timer.
*/
protected void timerDidCancel(TimerFunction timer) {
// stub
}
/**
* Introspection callback invoked before a {@code timer} is executed.
*/
protected void timerWillRun(TimerFunction timer) {
// stub
}
/**
* Invokes {@code timer.runTimer()}, or arranges for the asynchronous
* execution of the provided {@code runnable}, which will itself invoke
* {@code timer.runTimer()}.
*/
protected void runTimer(TimerFunction timer, Runnable runnable) {
timer.runTimer();
}
/**
* Introspection callback invoked after a {@code timer} executes nominally.
*/
protected void timerDidRun(TimerFunction timer) {
// stub
}
/**
* Introspection callback invoked after a {@code timer} execution fails by
* throwing an {@code error}.
*/
protected void timerDidFail(TimerFunction timer, Throwable error) {
// stub
}
/**
* Returns the current time, in nanoseconds, with arbitrary origin.
* Used by the clock thread to determine the current time. Defaults
* to {@link System#nanoTime()}. Can be overridden to substitute an
* alternative time source.
*/
protected long nanoTime() {
return System.nanoTime();
}
/**
* Parks the current thread for the specified number of {@code millis}.
* Used by the clock thread to wait for the next clock tick. Defaults
* to {@link Thread#sleep(long)}. Can be overridden to substitute an
* alternative wait mechanism.
*/
protected void sleep(long millis) throws InterruptedException {
Thread.sleep(millis);
}
/**
* Default number of milliseconds between clock ticks, used by the no-arg
* {@link #Clock()} constructor. Defaults to the value of the {@code
* swim.clock.tick.millis} system property, if defined; otherwise defaults to
* {@code 100} milliseconds.
*/
public static final int TICK_MILLIS;
/**
* Default number of ticks per clock revolution, used by the no-arg {@link
* #Clock()} constructor. Defaults to the value of the {@code
* swim.clock.tick.count} system property, if defined; otherwise defaults to
* {@code 512} clock ticks per revolution.
*/
public static final int TICK_COUNT;
/**
* Atomic {@link #status} bit flag indicating that the clock has started, and
* is currently running.
*/
static final int STARTED = 1 << 0;
/**
* Atomic {@link #status} bit flag indicating that the clock had previously
* started, but is now permanently stopped.
*/
static final int STOPPED = 1 << 1;
/**
* Atomic {@link #status} field updater, used to linearize clock startup and
* shutdown.
*/
static final AtomicIntegerFieldUpdater<Clock> STATUS =
AtomicIntegerFieldUpdater.newUpdater(Clock.class, "status");
static {
// Initializes the default number of milliseconds between clock ticks.
int tickMillis;
try {
tickMillis = Integer.parseInt(System.getProperty("swim.clock.tick.millis"));
} catch (NumberFormatException e) {
tickMillis = 100;
}
TICK_MILLIS = tickMillis;
// Initialize the default number of ticks per clock revolution.
int tickCount;
try {
tickCount = Integer.parseInt(System.getProperty("swim.clock.tick.count"));
} catch (NumberFormatException e) {
tickCount = 512;
}
TICK_COUNT = tickCount;
}
}
/**
* Context that binds a {@code TimerFunction} to a {@code Clock}, and manages
* the scheduling of at most one live {@code ClockEvent} at a time.
*/
final class ClockTimer implements TimerContext {
/**
* {@code Clock} to which the {@code timer} is bound.
*/
final Clock clock;
/**
* {@code TimerFunction} to invoke when a scheduled event fires.
*/
final TimerFunction timer;
/**
* Atomic reference to the currently scheduled event that will execute the
* {@code timer} when fired; {@code null} when the {@code timer} is not
* currently scheduled.
*/
volatile ClockEvent event;
/**
* Constructs a new {@code ClockTimer} that binds the {@code timer} to the
* {@code clock}.
*/
ClockTimer(Clock clock, TimerFunction timer) {
this.clock = clock;
this.timer = timer;
}
@Override
public Schedule schedule() {
return this.clock;
}
@Override
public boolean isScheduled() {
final ClockEvent event = EVENT.get(this);
return event != null && event.isScheduled();
}
@Override
public void reschedule(long millis) {
if (millis < 0L) {
throw new TimerException("negative timeout: " + Long.toString(millis));
}
this.clock.schedule(millis, this);
}
@Override
public boolean cancel() {
// Atomically get the current timer event, and replace it with null.
final ClockEvent event = EVENT.getAndSet(this, null);
// Check if the timer has a previously scheduled event.
if (event != null) {
// Remove the timer from the previously scheduled timer event;
// linearization point for timer cancellation.
final TimerFunction timer = event.cancel();
// Check if the timer event hadn't yet been fired or cancelled.
if (timer != null) {
// Invoke timer cancellation introspection callbacks.
if (timer instanceof Timer) {
((Timer) timer).timerDidCancel();
}
clock.timerDidCancel(timer);
return true;
}
}
return false;
}
/**
* Atomic {@link #event} field updater, used to linearize cancellation and
* rescheduling of the {@code timer}.
*/
static final AtomicReferenceFieldUpdater<ClockTimer, ClockEvent> EVENT =
AtomicReferenceFieldUpdater.newUpdater(ClockTimer.class, ClockEvent.class, "event");
}
/**
* Lock-free, multiple publisher, single consumer queue of linked {@code
* ClockEvent} items.
*/
final class ClockQueue {
/**
* First {@code ClockEvent} in the queue, from which all live events in the
* queue are reachable; always non-{@code null}. Only the clock thread is
* permitted to advance the head of the queue.
*/
volatile ClockEvent head;
/**
* Atomic reference from which the last {@code ClockEvent} in the queue can
* be reached in constant time; always non-{@code null}.
*/
volatile ClockEvent foot;
/**
* Constructs a new {@code ClockQueue} that will next execute the {@code
* insertTick} sequence number.
*/
ClockQueue(long insertTick) {
this.head = new ClockEvent(insertTick, insertTick, null, null);
this.foot = head;
}
/**
* Atomic {@link #foot} field updater, used to optimize event insertion.
*/
static final AtomicReferenceFieldUpdater<ClockQueue, ClockEvent> FOOT =
AtomicReferenceFieldUpdater.newUpdater(ClockQueue.class, ClockEvent.class, "foot");
}
/**
* Linked {@code ClockQueue} item holding a {@code TimerFunction} to execute.
*/
final class ClockEvent implements Runnable {
/**
* Tick sequence number of the next tick that the clock thread will execute
* at the time this {@code ClockEvent} was inserted into the queue. {@code
* insertTick} is non-decreasing over successive queued events, and the
* {@code insertTick} of the last event in the queue always represents the
* very next tick that the clock thread will execute.
*/
long insertTick;
/**
* Tick sequence number during which to fire this event.
*/
long targetTick;
/**
* {@code ClockTimer} on behalf of whom this {@code ClockEvent} is scheduled,
* or {@code null} if this is a placeholder event.
*/
final ClockTimer context;
/**
* Atomic reference to the {@code TimerFunction} to invoke when firing this
* event; {@code null} when this event has been cancelled.
*/
volatile TimerFunction timer;
/**
* Next {@code ClockEvent} in the linked queue; {@code null} if this is the
* last event in the queue.
*/
volatile ClockEvent next;
/**
* Constructs a new {@code ClockEvent} that will fire the {@code timer}
* at the {@code targetTick} sequence number, and will be inserted into the
* queue during the {@code insertTick} sequence number.
*/
ClockEvent(long insertTick, long targetTick, ClockTimer context, TimerFunction timer) {
this.insertTick = insertTick;
this.targetTick = targetTick;
this.context = context;
this.timer = timer;
}
/**
* Returns {@code true} if the {@link #timer} is non-{@code null}, indicating
* that this {@code ClockEvent} is scheduled for execution.
*/
boolean isScheduled() {
return TIMER.get(this) != null;
}
/**
* Atomically gets the scheduled {@link #timer}, and replaces it with {@code
* null}, thereby preventing future execution, or concurrent cancellation.
*/
TimerFunction cancel() {
// Atomically get the scheduled timer, and replace it with null;
// linearization point for timer execution and cancellation.
return TIMER.getAndSet(this, null);
}
/**
* Invokes the timer function of the associated timer context.
*/
@Override
public void run() {
this.context.timer.runTimer();
}
/**
* Atomic {@link #timer} field updater, used to linearize event cancellation.
*/
static final AtomicReferenceFieldUpdater<ClockEvent, TimerFunction> TIMER =
AtomicReferenceFieldUpdater.newUpdater(ClockEvent.class, TimerFunction.class, "timer");
/**
* Atomic {@link #next} field updater, used to linearize event scheduling.
*/
static final AtomicReferenceFieldUpdater<ClockEvent, ClockEvent> NEXT =
AtomicReferenceFieldUpdater.newUpdater(ClockEvent.class, ClockEvent.class, "next");
}
/**
* Thread of execution that fires clock events at the appropriate times.
*/
final class ClockThread extends Thread {
/**
* {@code Clock} whose events this {@code ClockThread} fires.
*/
final Clock clock;
/**
* Next tick sequence number that this {@code ClockThread} will execute.
*/
long tick;
/**
* Constructs a new {@code ClockThread} that fires events for {@code clock}.
*/
ClockThread(Clock clock) {
setName("SwimClock" + THREAD_COUNT.getAndIncrement());
setDaemon(true);
this.clock = clock;
}
@Override
public void run() {
final Clock clock = this.clock;
try {
// Initialize the relative clock start time.
long startTime = clock.nanoTime();
if (startTime == 0L) {
// Avoid clash with sentinel value that signifies an unstarted clock.
startTime = 1L;
}
clock.startTime = startTime;
// Linearization point for clock start.
clock.startLatch.countDown();
clock.didStart();
// Loop while the clock has not been stopped.
do {
final long tick = this.tick;
// Wait for the clock to reach the elapsed time of the next tick.
final long waitedMillis = waitForTick(clock, tick);
// Check if we had a nominal wakeup.
if (waitedMillis != Long.MIN_VALUE) {
// Execute the clock tick.
executeTick(clock, tick);
// Invoke the clock tick introspection callback, with a measure of the
// clock latency.
clock.didTick(tick, waitedMillis);
// Increment the tick sequence number.
this.tick = tick + 1L;
}
} while ((Clock.STATUS.get(clock) & Clock.STOPPED) == 0);
clock.willStop();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report internal clock error.
clock.didFail(error);
} else {
// Rethrow fatal error.
throw error;
}
} finally {
// Force the clock into the stopped state.
Clock.STATUS.set(clock, Clock.STOPPED);
// Linearization point for clock stop.
clock.stopLatch.countDown();
clock.didStop();
}
}
/**
* Parks the clock thread until the {@code clock} time has reached the
* elapsed time of the taregt {@code tick}. Returns the total number of
* milliseconds waited; the returned wait time can be negative if it's
* taking longer than the clock's tick interval to execute timers.
* Returns {@code Long.MIN_VALUE} if the clock was stopped while waiting
* for the target {@code tick}.
*/
static long waitForTick(final Clock clock, final long tick) {
// The clock elapsed time of the target tick.
final long deadline = clock.tickNanos * tick;
// The clock elapsed time of the first wait for the target tick.
final long initialTime = clock.nanoTime() - clock.startTime;
// The current clock elapsed time.
long currentTime = initialTime;
do {
// Check for elapsed time overflow.
if (currentTime < 0L) {
// Can't run for longer than about 292 years.
throw new InternalError("Clock elapsed time overflow");
}
// Calculate the number of milliseconds until the deadline for the target
// tick, rounding up to the next millisecond.
final long sleepMillis = ((deadline - currentTime) + 999999L) / 1000000L;
// Check if the deadline for the target tick is in the future.
if (sleepMillis > 0L) {
// Park the timer thread for the number of milliseconds until the
// deadline for the target tick.
try {
clock.sleep(sleepMillis);
} catch (InterruptedException e) {
// Interrupted while waiting for the target tick; check if the clock
// has been stopped.
if ((Clock.STATUS.get(clock) & Clock.STOPPED) != 0) {
// Return a sentinel value to signal that the clock stopped.
return Long.MIN_VALUE;
}
}
// Recompute the current clock elapsed time.
currentTime = clock.nanoTime() - clock.startTime;
} else {
// We've reached the deadline for the target tick; recompute the
// current clock elapsed time.
currentTime = clock.nanoTime() - clock.startTime;
// Compute the total number of milliseconds we waited.
return (currentTime - initialTime) / 1000000L;
}
} while (true);
}
/**
* Executes all {@code clock} timers set to fire at the target {@code tick}.
*/
static void executeTick(final Clock clock, final long tick) {
// Compute the tick sequence number for the next revolution of the clock.
final long nextTick = tick + (long) clock.tickCount;
// Compute the index in the clock dial of the target clock tick.
final int hand = (int) (tick % (long) clock.tickCount);
// Get the event queue for the target hand of the clock dial.
final ClockQueue queue = clock.dial[hand];
// The first known still scheduled event to keep in the queue.
ClockEvent head = null;
// The last known still scheduled event to keep in the queue.
ClockEvent prev = null;
// The next queued event to process.
ClockEvent next = queue.head;
// The sentinel event that will be inserted at the end of the queue to
// complete the execution of this tick.
final ClockEvent nextFoot = new ClockEvent(nextTick, nextTick, null, null);
// Loop until no events scheduled for this tick remain in the queue.
do {
if (next.targetTick <= tick) {
// The next event is scheduled for this tick; remove its timer.
final TimerFunction timer = next.cancel();
// Clear the event from the associated timer context.
if (next.context != null) {
ClockTimer.EVENT.compareAndSet(next.context, next, null);
}
if (timer != null) {
// The timer wasn't cancelled; fire the event.
try {
clock.timerWillRun(timer);
clock.runTimer(timer, next);
clock.timerDidRun(timer);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// The timer failed with a non-fatal error.
clock.timerDidFail(timer, error);
} else {
// The timer failed with a fatal error.
throw error;
}
}
}
} else if (next.isScheduled()) {
// The next event is scheduled for a future revolution of the clock.
if (prev != null) {
// Insert the next event after the last kept event in the queue,
// bypassing any fired or cancelled events.
prev.next = next;
} else {
// The next event is the first event to keep in the queue.
head = next;
}
// The next event is now the last known event to keep in the queue.
prev = next;
}
// Check if the next event is the last in the queue.
if (next.next == null) {
// Try to finish tick execution by appending a cancelled event to the
// end of the queue, whose insertTick is the next tick sequence number
// that the clock thread will execute for this queue, preventing
// further scheduling of events for the current tick.
if (ClockEvent.NEXT.compareAndSet(next, null, nextFoot)) {
// All events that will ever be scheduled for this tick have now been
// cancelled or fired; update the foot of the queue to reference the
// new foot event.
ClockQueue.FOOT.set(queue, nextFoot);
// Check if no events were kept in the queue.
if (head == null) {
// In which case the new foot is also the new head.
head = nextFoot;
}
// Update the head of the queue.
queue.head = head;
break;
}
}
// Advance to the next event in the queue.
next = next.next;
} while (true);
}
/**
* Total number of clock threads that have ever been instantiated. Used to
* uniquely name clock threads.
*/
static final AtomicInteger THREAD_COUNT = new AtomicInteger(0);
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/ClockDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class ClockDef implements ScheduleDef, Debug {
final int tickMillis;
final int tickCount;
public ClockDef(int tickMillis, int tickCount) {
this.tickMillis = tickMillis;
this.tickCount = tickCount;
}
public final int tickMillis() {
return this.tickMillis;
}
public ClockDef tickMillis(int tickMillis) {
return copy(tickMillis, this.tickCount);
}
public final int tickCount() {
return this.tickCount;
}
public ClockDef tickCount(int tickCount) {
return copy(this.tickMillis, tickCount);
}
protected ClockDef copy(int tickMillis, int tickCount) {
return new ClockDef(tickMillis, tickCount);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof ClockDef) {
final ClockDef that = (ClockDef) other;
return this.tickMillis == that.tickMillis
&& this.tickCount == that.tickCount;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(ClockDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.tickMillis), this.tickCount));
}
@Override
public void debug(Output<?> output) {
output = output.write("ClockDef").write('.').write("standard").write('(').write(')');
if (this.tickMillis != Clock.TICK_MILLIS) {
output = output.write('.').write("tickMillis").write('(').debug(tickMillis).write(')');
}
if (this.tickCount != Clock.TICK_COUNT) {
output = output.write('.').write("tickCount").write('(').debug(tickCount).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static ClockDef standard;
private static Form<ClockDef> clockForm;
public static ClockDef standard() {
if (standard == null) {
standard = new ClockDef(Clock.TICK_MILLIS, Clock.TICK_COUNT);
}
return standard;
}
@Kind
public static Form<ClockDef> clockForm() {
if (clockForm == null) {
clockForm = new ClockForm(standard());
}
return clockForm;
}
}
final class ClockForm extends Form<ClockDef> {
final ClockDef unit;
ClockForm(ClockDef unit) {
this.unit = unit;
}
@Override
public String tag() {
return "clock";
}
@Override
public ClockDef unit() {
return this.unit;
}
@Override
public Form<ClockDef> unit(ClockDef unit) {
return new ClockForm(unit);
}
@Override
public Class<ClockDef> type() {
return ClockDef.class;
}
@Override
public Item mold(ClockDef clockDef) {
if (clockDef != null) {
final Record record = Record.create(3).attr(tag());
record.slot("tickMillis", clockDef.tickMillis);
record.slot("tickCount", clockDef.tickCount);
return record;
} else {
return Item.extant();
}
}
@Override
public ClockDef cast(Item item) {
final Value value = item.toValue();
final Value header = value.getAttr(tag());
if (header.isDefined()) {
final int tickMillis = value.get("tickMillis").intValue(Clock.TICK_MILLIS);
final int tickCount = value.get("tickCount").intValue(Clock.TICK_COUNT);
return new ClockDef(tickMillis, tickCount);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/ConcurrentTrancheQueue.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ConcurrentTrancheQueue<T> {
final ConcurrentLinkedQueue<T>[] queues;
final float scale;
final int highest;
@SuppressWarnings("unchecked")
public ConcurrentTrancheQueue(int tranches) {
if (tranches == 0) {
throw new IllegalArgumentException();
}
this.queues = (ConcurrentLinkedQueue<T>[]) new ConcurrentLinkedQueue<?>[tranches];
for (int i = 0; i < tranches; i += 1) {
this.queues[i] = new ConcurrentLinkedQueue<T>();
}
this.scale = 0.5f * tranches;
this.highest = tranches - 1;
}
public int size() {
int size = 0;
for (int tranche = this.highest; tranche >= 0; tranche -= 1) {
size += this.queues[tranche].size();
}
return size;
}
public void add(T value, float prio) {
final int tranche = Math.max(0, Math.min((int) ((1.0f + prio) * this.scale), this.highest));
this.queues[tranche].add(value);
}
public T peek() {
for (int tranche = this.highest; tranche >= 0; tranche -= 1) {
final T value = this.queues[tranche].peek();
if (value != null) {
return value;
}
}
return null;
}
public T poll() {
for (int tranche = this.highest; tranche >= 0; tranche -= 1) {
final T value = this.queues[tranche].poll();
if (value != null) {
return value;
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Cont.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Continuation of an asynchronous operation. The {@link #bind(Object)
* bind(T)} method gets called when the asynchronous operation completes with a
* value; the {@link #trap(Throwable)} method gets called when the asynchronous
* operation fails with an exception.
*
* @see Conts
* @see Call
* @see Sync
*/
public interface Cont<T> {
/**
* Invoked when the asynchronous operation completes with a {@code value}.
*/
void bind(T value);
/**
* Invoked when the asynchronous operation fails with an {@code error}.
*/
void trap(Throwable error);
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/ContException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Thrown when performing an invalid operation on a {@link Call} or {@link
* Cont}inuation.
*/
public class ContException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ContException(String message, Throwable cause) {
super(message, cause);
}
public ContException(String message) {
super(message);
}
public ContException(Throwable cause) {
super(cause);
}
public ContException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Conts.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Factory functions for {@link Cont}inuation combinators.
*/
public final class Conts {
private Conts() {
}
private static Cont<Object> ignore;
/**
* Returns a {@code Runnable} that, when executed, invokes the given {@code
* cont}inuation with the provided constant {@code value}.
*/
public static <T> Runnable async(Cont<T> cont, T value) {
return new ConstantCont<Object, T>(cont, value);
}
/**
* Returns a {@code Cont}inuation that, when completed successfully,
* completes the given {@code cont}inuation with the provided constant {@code
* value}; and when failed with an error, fails the given {@code cont}inuation
* with the error.
*/
public static <X, T> Cont<X> constant(Cont<T> cont, T value) {
return new ConstantCont<X, T>(cont, value);
}
/**
* Returns a {@code Cont} continuation that, when completed successfully,
* does nothing; and when failed with an exception, throws the exception.
*/
@SuppressWarnings("unchecked")
public static <T> Cont<T> ignore() {
if (ignore == null) {
ignore = new IgnoreCont<Object>();
}
return (Cont<T>) ignore;
}
/**
* Returns {@code true} if {@code throwable} is a recoverable exception;
* returns {@code false} if {@code throwable} cannot be recovered from.
*/
public static boolean isNonFatal(Throwable throwable) {
return !(throwable instanceof InterruptedException
|| throwable instanceof LinkageError
|| throwable instanceof ThreadDeath
|| throwable instanceof VirtualMachineError);
}
}
final class ConstantCont<X, T> implements Cont<X>, Runnable {
private final Cont<T> cont;
private final T value;
ConstantCont(Cont<T> cont, T value) {
this.cont = cont;
this.value = value;
}
@Override
public void run() {
try {
this.cont.bind(this.value);
} catch (Throwable error) {
this.cont.trap(error);
}
}
@Override
public void bind(X object) {
try {
this.cont.bind(this.value);
} catch (Throwable error) {
this.cont.trap(error);
}
}
@Override
public void trap(Throwable error) {
this.cont.trap(error);
}
}
final class IgnoreCont<T> implements Cont<T> {
@Override
public void bind(T value) {
// nop
}
@Override
public void trap(Throwable error) {
if (error instanceof Error) {
throw (Error) error;
} else if (error instanceof RuntimeException) {
throw (RuntimeException) error;
} else {
throw new ContException(error);
}
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/MainStage.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* {@link Stage} that can be started and stopped.
*/
public interface MainStage extends Stage {
/**
* Ensures that this {@code Stage} is up and running.
*
* @throws IllegalStateException if this {@code Stage} has been stopped.
*/
void start();
/**
* Ensures that this {@code Stage} has been permanently stopped.
*/
void stop();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Preemptive.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Function interface that callers can optionally invoke concurrently.
*/
public interface Preemptive {
/**
* Returns {@code true} if callers can safely invoke this function object
* concurrently. Returns {@code false} if this function object is not
* thread safe. Returns {@code false} by default.
*/
default boolean isPreemptive() {
return false;
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/PullContext.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
public interface PullContext<T> {
void push(T value);
void skip();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/PullRequest.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
public interface PullRequest<T> {
float prio();
void pull(PullContext<? super T> context);
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/PushRequest.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
public class PushRequest<T> implements PullRequest<T> {
final T value;
final float prio;
public PushRequest(T value, float prio) {
this.value = value;
this.prio = prio;
}
public PushRequest(T value) {
this(value, 0f);
}
public final T get() {
return this.value;
}
@Override
public final float prio() {
return this.prio;
}
@Override
public void pull(PullContext<? super T> context) {
context.push(this.value);
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Schedule.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Timetable for executing timers at their scheduled times. {@code Schedule}
* is thread safe.
*
* @see Clock
*/
public interface Schedule {
/**
* Returns an unscheduled {@code TimerRef} bound to {@code timer}, which
* can later be used to schedule {@code timer}.
*/
TimerRef timer(TimerFunction timer);
/**
* Schedules {@code timer} to execute after {@code millis} milliseconds
* have elapsed. Returns a {@code TimerRef} that can be used to check the
* status of, reschedule, and cancel {@code timer}.
*/
TimerRef setTimer(long millis, TimerFunction timer);
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/ScheduleDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
/**
* Marker interface for a {@link Schedule} definition.
*/
public interface ScheduleDef {
@Kind
static Form<ScheduleDef> form() {
return new ScheduleForm(ClockDef.standard());
}
}
final class ScheduleForm extends Form<ScheduleDef> {
final ScheduleDef unit;
ScheduleForm(ScheduleDef unit) {
this.unit = unit;
}
@Override
public ScheduleDef unit() {
return this.unit;
}
@Override
public Form<ScheduleDef> unit(ScheduleDef unit) {
return new ScheduleForm(unit);
}
@Override
public Class<ScheduleDef> type() {
return ScheduleDef.class;
}
@Override
public Item mold(ScheduleDef scheduleDef) {
if (scheduleDef instanceof ClockDef) {
return ClockDef.clockForm().mold((ClockDef) scheduleDef);
} else {
return Item.extant();
}
}
@Override
public ScheduleDef cast(Item item) {
final ClockDef clockDef = ClockDef.clockForm().cast(item);
if (clockDef != null) {
return clockDef;
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/ScheduleException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Thrown when a {@link Schedule} encounters an error.
*/
public class ScheduleException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ScheduleException(String message, Throwable cause) {
super(message, cause);
}
public ScheduleException(String message) {
super(message);
}
public ScheduleException(Throwable cause) {
super(cause);
}
public ScheduleException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/SideStage.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* {@link Stage} wrapper that prevents its underlying stage from being started
* and stopped.
*/
public class SideStage implements Stage {
protected final Stage stage;
public SideStage(Stage stage) {
this.stage = stage;
}
@Override
public void execute(Runnable runnable) {
this.stage.execute(runnable);
}
@Override
public TaskRef task(TaskFunction task) {
return this.stage.task(task);
}
@Override
public <T> Call<T> call(Cont<T> cont) {
return this.stage.call(cont);
}
@Override
public TimerRef timer(TimerFunction timer) {
return this.stage.timer(timer);
}
@Override
public TimerRef setTimer(long millis, TimerFunction timer) {
return this.stage.setTimer(millis, timer);
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Stage.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import java.util.concurrent.Executor;
/**
* An execution context in which to schedule tasks, create continuation calls,
* and set timers. {@code Stage} is thread safe.
*
* @see MainStage
* @see Theater
*/
public interface Stage extends Executor, Schedule {
/**
* Returns an uncued {@code TaskRef} bound to the {@code task}, which can
* later be used to cue the {@code task}.
*/
TaskRef task(TaskFunction task);
/**
* Returns a {@code Call} that completes the {@code cont}inuation.
*/
<T> Call<T> call(Cont<T> cont);
/**
* Schedules a {@code runnable} for concurrent execution.
*/
@Override
void execute(Runnable runnable);
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/StageClock.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* {@link Clock} that invokes timer functions on an execution {@link Stage},
* rather than on the clock thread.
*/
public class StageClock extends Clock {
/**
* {@code Stage} on which to execute timer functions.
*/
protected final Stage stage;
/**
* Constructs a new {@code StageClock} with a timer resolution of {@code
* tickMillis} milliseconds, and a clock period of {@code tickCount} ticks
* per revolution, that executes timer functions on the given {@code stage}.
*/
public StageClock(Stage stage, int tickMillis, int tickCount) {
super(tickMillis, tickCount);
this.stage = stage;
}
/**
* Constructs a new {@code StageClock}, with the timer resolution and clock
* period specified by the given {@code clockDef}, that executes timer
* functions on the given {@code stage}.
*/
public StageClock(Stage stage, ClockDef clockDef) {
this(stage, clockDef.tickMillis, clockDef.tickCount);
}
/**
* Constructs a new {@code StageClock} with a timer resolution of {@link
* #TICK_MILLIS} milliseconds, and a clock period of {@link #TICK_COUNT}
* ticks per revolution, that executes timer functions on the given
* {@code stage}.
*/
public StageClock(Stage stage) {
this(stage, TICK_MILLIS, TICK_COUNT);
}
/**
* Returns the stage on which to execute timer functions.
*/
public final Stage stage() {
return this.stage;
}
/**
* Schedules the {@code runnable} to invoke {@code timer.runTimer()}
* on the execution {@link #stage}.
*/
@Override
protected void runTimer(TimerFunction timer, Runnable runnable) {
this.stage.execute(runnable);
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/StageDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
/**
* Marker interface for a {@link Stage} definition.
*/
public interface StageDef {
@Kind
static Form<StageDef> form() {
return new StageForm(TheaterDef.standard());
}
}
final class StageForm extends Form<StageDef> {
final StageDef unit;
StageForm(StageDef unit) {
this.unit = unit;
}
@Override
public StageDef unit() {
return this.unit;
}
@Override
public Form<StageDef> unit(StageDef unit) {
return new StageForm(unit);
}
@Override
public Class<StageDef> type() {
return StageDef.class;
}
@Override
public Item mold(StageDef stageDef) {
if (stageDef instanceof TheaterDef) {
return TheaterDef.theaterForm().mold((TheaterDef) stageDef);
} else {
return Item.extant();
}
}
@Override
public StageDef cast(Item item) {
final TheaterDef theaterDef = TheaterDef.theaterForm().cast(item);
if (theaterDef != null) {
return theaterDef;
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Sync.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* A {@link Cont}inuation whose completion can be synchronously awaited. A
* {@code Sync} continuation is used to await the completion of an asynchronous
* operation.
*/
public class Sync<T> implements Cont<T>, ForkJoinPool.ManagedBlocker {
/**
* Atomic completion status of this {@code Sync} continuation.
*/
volatile int status;
/**
* Completed result of this {@code Sync} continuation; either the bound value
* of type {@code T}, or the trapped error of type {@code Throwable}. The
* type of {@code result} is decided by the flags of the {@code status} field.
*/
volatile Object result;
/**
* Constructs a new {@code Sync} continuation that awaits a value of type
* {@code T}.
*/
public Sync() {
// nop
}
@Override
public boolean isReleasable() {
return this.status != 0;
}
@Override
public synchronized boolean block() throws InterruptedException {
if (this.status == 0) {
wait(TIMEOUT.get());
}
return true;
}
@Override
public synchronized void bind(T value) {
// Set the resulting value before updating the completion status.
this.result = value;
// Atomically set the status; linearization point for sync completion.
STATUS.set(this, BIND);
// Release all waiting threads.
notifyAll();
}
@Override
public synchronized void trap(Throwable error) {
// Set the resulting error before updating the completion status.
this.result = error;
// Atomically set the status; linearization point for sync completion.
STATUS.set(this, TRAP);
// Release all waiting threads.
notifyAll();
}
/**
* Waits a maximum of {@code timeout} milliseconds for this {@code Sync}
* continuation to complete. Performs a managed block to avoid thread
* starvation while waiting.
*
* @throws SyncException if the {@code timeout} milliseconds elapses and this
* {@code Sync} continuation still hasn't been completed.
*/
@SuppressWarnings("unchecked")
public T await(final long timeout) throws InterruptedException {
// Capture the monotonic system time at which the await began.
final long t0 = System.nanoTime();
// The remaining number milliseconds to wait for continuation completion.
long waitMillis = timeout;
// Loop until the continuation has been completed, or the timeout has elapsed.
do {
// Check if the continuation is uncompleted.
if (this.status == 0) {
// Set the thread local timeout variable to preserve it through the
// call to ForkJoinPool.managedBlock.
TIMEOUT.set(timeout);
// Perform a managed block so as not to starve the thread pool, if
// we're running in one.
ForkJoinPool.managedBlock(this);
}
// Recheck the status after waiting.
if (this.status != 0) {
// Non-zero status indicates that the continuation has completed.
break;
}
// Check if we're performing a timed wait.
if (timeout > 0L) {
// Update the remaining number of milliseconds to wait.
final long t1 = System.nanoTime();
final long elapsedMillis = (t1 - t0) / 1000000L;
waitMillis = timeout - elapsedMillis;
// Check if the timeout period has elapsed.
if (waitMillis <= 0L) {
throw new SyncException("timed out");
}
}
} while (true);
// Load the continuation completion status.
final int status = this.status;
// Load the completed result.
final Object result = this.result;
if (status == BIND) {
// Continuation completed with a value; return it.
return (T) result;
} else if (status == TRAP) {
// Continuation failed with an exception; throw it.
if (result instanceof Error) {
// Throw unchecked Error.
throw (Error) result;
} else if (result instanceof RuntimeException) {
// Throw unchecked RuntimeException.
throw (RuntimeException) result;
} else {
// Wrap checked exception in an unchecked ContException.
throw new ContException((Throwable) result);
}
} else {
// Unreachable.
throw new IllegalStateException();
}
}
/**
* Waits an unbounded amount of time for this {@code Sync} continuation to
* complete. Performs a managed block to avoid thread starvation while
* waiting.
*/
public T await() throws InterruptedException {
return await(0L);
}
/**
* {@link #status} value indicating the continuation completed with a value.
*/
static final int BIND = 1;
/**
* {@link #status} value indicating the continuation failed with an exception.
*/
static final int TRAP = 2;
/**
* Atomic {@link #status} field updater, used to linearize continuation completion.
*/
@SuppressWarnings("unchecked")
static final AtomicIntegerFieldUpdater<Sync<?>> STATUS =
AtomicIntegerFieldUpdater.newUpdater((Class<Sync<?>>) (Class<?>) Sync.class, "status");
/**
* Thread-local variable used to pass the await timeout through calls to
* {@code ForkJoinPool.managedBlock}.
*/
static final ThreadLocal<Long> TIMEOUT = new ThreadLocal<Long>();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/SyncException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Thrown when awaiting a {@link Sync} continuation times out.
*/
public class SyncException extends ContException {
private static final long serialVersionUID = 1L;
public SyncException(String message, Throwable cause) {
super(message, cause);
}
public SyncException(String message) {
super(message);
}
public SyncException(Throwable cause) {
super(cause);
}
public SyncException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Task.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Stateful {@link TaskFunction} to invoke as a sequential process on a
* concurrent execution {@link Stage}, with lifecycle callbacks, and a {@link
* TaskContext} for self-management. Use {@link Stage#task(TaskFunction)} to
* bind a new {@code Task} to a {@code Stage}, and invoke {@link TaskRef#cue()}
* to schedule the concurrent execution of the sequential task.
*
* <h3>Blocking</h3>
* {@code Task} implementations should not perform long running or blocking
* operations, if possible. If a {@code Task} does need to block, it should
* return {@code true} from {@link #taskWillBlock()} to avoid thread starvation
* of the execution {@code Stage}.
*
* @see AbstractTask
* @see Stage
*/
public interface Task extends TaskFunction {
/**
* Returns the context used to managed this {@code Task}. Returns {@code
* null} if this {@code Task} is not bound to a {@link Stage}.
*/
TaskContext taskContext();
/**
* Sets the context used to managed this {@code Task}. A {@code
* TaskContext} is assigned when binding this {@code Task} to a {@link Stage}.
*/
void setTaskContext(TaskContext taskContext);
/**
* Executes this sequential process. Only one thread at a time will execute
* {@code runTask} for this {@code Task}.
*/
@Override
void runTask();
/**
* Returns {@code true} if this {@code Task} might block its thread of
* execution when running; returns {@code false} if this {@code Task} will
* never block. Used by the execution {@code Stage} to prevent thread
* starvation when concurrently running many blocking tasks.
*/
boolean taskWillBlock();
/**
* Lifecycle callback invoked before this {@code Task} is scheduled for
* execution.
*/
void taskWillCue();
/**
* Lifecycle callback invoked after this {@code Task} is explicitly
* cancelled.
*/
void taskDidCancel();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TaskContext.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Internal context that binds a {@link Task} to an execution {@link Stage}.
* A {@code TaskContext} is used by a {@code Task} to re-cue itself for
* execution, to spawn child tasks, and to set timers. {@code TaskContext} is
* thread safe.
*
* @see Task
*/
public interface TaskContext extends TaskRef {
/**
* Returns the execution {@code Stage} to which the task is bound.
*/
Stage stage();
/**
* Returns {@code true} if the task is currently scheduled for execution.
*/
@Override
boolean isCued();
/**
* Schedules the task to execute as a sequential process. Returns {@code
* true} if this operation caused the scheduling of the task; returns {@code
* false} if the task was already scheduled to execute. {@link
* Task#runTask()} will be concurrently invoked exactly once for each time
* {@code cue()} returns {@code true}, minus the number of times {@code
* cancel()} returns {@code true}. The task becomes uncued prior to the the
* invocation of {@code runTask()}, enabling the task to re-cue itself while
* running.
*/
@Override
boolean cue();
/**
* Cancels the task to prevent it from executing. Returns {@code true} if
* this operation caused the cancellation of the task; returns {@code false}
* if the task was not scheduled to execute.
*/
@Override
boolean cancel();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TaskException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Thrown when performing an invalid operation on a {@link TaskFunction}.
*/
public class TaskException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TaskException(String message, Throwable cause) {
super(message, cause);
}
public TaskException(String message) {
super(message);
}
public TaskException(Throwable cause) {
super(cause);
}
public TaskException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TaskFunction.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Function to invoke as a sequential process on a concurrent execution {@link
* Stage}. Use {@link Stage#task(TaskFunction)} to bind a {@code TaskFunction}
* to a {@code Stage}, and invoke {@link TaskRef#cue()} to schedule the
* concurrent execution of the sequential task.
*
* <h3>Blocking</h3>
* {@code TaskFunction} implementations should not perform long running or
* blocking operations. If a blocking operation needs to be performed,
* implement a {@link Task} that returns {@code true} from {@link
* Task#taskWillBlock() taskWillBlock()} to avoid thread starvation of the
* execution {@code Stage}.
*
* @see Task
* @see Stage
*/
//@FunctionalInterface
public interface TaskFunction {
/**
* Executes this sequential process. Only one thread at a time will execute
* {@code runTask} for this {@code TaskFunction}.
*/
void runTask();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TaskRef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* External handle to a {@link TaskFunction} bound to an execution {@link
* Stage}. A {@code TaskRef} is used to cue a task for execution, and to
* cancel the execution of a cued task. {@code TaskRef} is thread safe.
*
* @see Stage
*/
public interface TaskRef {
/**
* Returns {@code true} if the task is currently scheduled for execution.
*/
boolean isCued();
/**
* Schedules the task to execute as a sequential process. Returns {@code
* true} if this operation caused the scheduling of the task; returns {@code
* false} if the task was already scheduled to execute. {@link
* TaskFunction#runTask()} will be concurrently invoked exactly once for
* each time {@code cue()} returns {@code true}, minus the number of times
* {@code cancel()} returns {@code true}. The task becomes uncued prior to
* the invocation of {@code runTask()}, enabling the task to re-cue itself
* while running.
*/
boolean cue();
/**
* Cancels the task to prevent it from executing. Returns {@code true} if
* this operation caused the cancellation of the task; returns {@code false}
* if the task was not scheduled to execute.
*/
boolean cancel();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Theater.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* {@link Stage} that executes timers, tasks, and continuations on a {@code
* ForkJoinPool}.
*/
public class Theater implements MainStage, Thread.UncaughtExceptionHandler {
/**
* Prefix for worker thread names.
*/
final String name;
/**
* Thread pool on which to execute timers, tasks, and continuations.
*/
final ForkJoinPool pool;
/**
* Schedule used to set timers.
*/
Schedule schedule;
/**
* Atomic bit field with {@link #STARTED} and {@link #STOPPED} flags.
*/
volatile int status;
public Theater(TheaterDef theaterDef) {
this.name = theaterDef.name != null ? theaterDef.name : "SwimStage" + THEATER_COUNT.getAndIncrement() + ".";
this.pool = new ForkJoinPool(theaterDef.parallelism, new TheaterWorkerFactory(this), this, true);
if (theaterDef.scheduleDef instanceof ClockDef) {
this.schedule = new StageClock(this, (ClockDef) theaterDef.scheduleDef);
} else {
this.schedule = new StageClock(this);
}
}
public Theater(String name, int parallelism, Schedule schedule) {
this.name = name != null ? name : "SwimStage" + THEATER_COUNT.getAndIncrement() + ".";
this.pool = new ForkJoinPool(parallelism, new TheaterWorkerFactory(this), this, true);
this.schedule = schedule != null ? schedule : new StageClock(this);
}
public Theater(String name, int parallelism) {
this(name, parallelism, null);
}
public Theater(String name, Schedule schedule) {
this(name, Runtime.getRuntime().availableProcessors(), schedule);
}
public Theater(String name) {
this(name, Runtime.getRuntime().availableProcessors(), null);
}
public Theater(int parallelism, Schedule schedule) {
this(null, parallelism, schedule);
}
public Theater(int parallelism) {
this(null, parallelism, null);
}
public Theater(Schedule schedule) {
this(null, Runtime.getRuntime().availableProcessors(), schedule);
}
public Theater() {
this(null, Runtime.getRuntime().availableProcessors(), null);
}
public final String name() {
return this.name;
}
public final int parallelism() {
return this.pool.getParallelism();
}
public final Schedule schedule() {
return this.schedule;
}
public void setSchedule(Schedule schedule) {
this.schedule = schedule;
}
/**
* Ensures that this {@code Theater} is up and running.
*
* @throws IllegalStateException if this {@code Theater} has been stopped.
*/
public void start() {
int oldStatus;
int newStatus;
do {
oldStatus = STATUS.get(this);
if ((oldStatus & STOPPED) == 0) {
newStatus = oldStatus | STARTED;
} else {
newStatus = oldStatus;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
didStart();
} else if ((oldStatus & STOPPED) != 0) {
throw new IllegalStateException("Can't restart stopped theater");
}
}
/**
* Ensures that this {@code Theater} has been permanently stopped, shutting
* down the thread pool, if it's currently running. Upon return, this
* {@code Theater} is guaranteed to be in the <em>stopped</em> state.
*/
public void stop() {
int oldStatus;
int newStatus;
do {
oldStatus = STATUS.get(this);
newStatus = oldStatus | STOPPED;
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.pool.shutdown();
boolean interrupted = false;
while (!this.pool.isTerminated()) {
try {
this.pool.awaitTermination(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
interrupted = true;
}
}
didStop();
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
@Override
public void execute(Runnable runnable) {
start();
this.pool.execute(runnable);
}
@Override
public TaskRef task(TaskFunction task) {
start();
final TheaterTask context = new TheaterTask(this, task);
if (task instanceof Task) {
((Task) task).setTaskContext(context);
}
return context;
}
@Override
public <T> Call<T> call(Cont<T> cont) {
start();
return new TheaterCall<T>(this, cont);
}
@Override
public TimerRef timer(TimerFunction timer) {
start();
return this.schedule.timer(timer);
}
@Override
public TimerRef setTimer(long millis, TimerFunction timer) {
start();
return this.schedule.setTimer(millis, timer);
}
/**
* Lifecycle callback invoked before the thread pool starts up.
*/
protected void didStart() {
// stub
}
/**
* Lifecycle callback invoked after the thread pool shuts down.
*/
protected void didStop() {
// stub
}
/**
* Lifecycle callback invoked if this {@code Theater} encounters
* an internal {@code error}.
*/
protected void didFail(Throwable error) {
error.printStackTrace();
}
/**
* Introspection callback invoked before a {@code task} is cued for execution.
*/
protected void taskWillCue(TaskFunction task) {
// stub
}
/**
* Introspection callback invoked after a cued {@code task} is canceled.
*/
protected void taskDidCancel(TaskFunction task) {
// stub
}
/**
* Introspection callback invoked immediately before {@code task.runTask()}
* is executed.
*/
protected void taskWillRun(TaskFunction task) {
// stub
}
/**
* Introspection callback invoked immediately after {@code task.runTask()}
* returns nominally.
*/
protected void taskDidRun(TaskFunction task) {
// stub
}
/**
* Introspection callback invoked immediately after {@code task.runTask()}
* fails by throwing an {@code error}.
*/
protected void taskDidFail(TaskFunction task, Throwable error) {
// stub
}
/**
* Introspection callback invoked before a {@code cont} call is cued for
* execution.
*/
protected void callWillCue(Cont<?> cont) {
// stub
}
/**
* Introspection callback invoked immediately before a call to {@code
* cont.bind(value)}.
*/
protected <T> void callWillBind(Cont<T> cont, T value) {
// stub
}
/**
* Introspection callback invoked immediately after a call to {@code
* cont.bind(value)} returns nominally.
*/
protected <T> void callDidBind(Cont<?> cont, T value) {
// stub
}
/**
* Introspection callback invoked immediately before a call to {@code
* cont.trap(error)}.
*/
protected void callWillTrap(Cont<?> cont, Throwable error) {
// stub
}
/**
* Introspection callback invoked immediately after a call to {@code
* cont.trap(error)} returns nominally.
*/
protected void callDidTrap(Cont<?> cont, Throwable error) {
// stub
}
/**
* Introspection callback invoked immediately after a call to {@code
* cont.bind(T)} fails by throwing an {@code error}.
*/
protected void callDidFail(Cont<?> cont, Throwable error) {
// stub
}
@Override
public void uncaughtException(Thread thead, Throwable error) {
didFail(error);
}
/**
* Atomic {@link #status} bit flag indicating that the theater has started,
* and is currently running.
*/
static final int STARTED = 1 << 0;
/**
* Atomic {@link #status} bit flag indicating that the theater had previously
* started, but is now permanently stopped.
*/
static final int STOPPED = 1 << 1;
/**
* Total number of theaters that have ever been instantiated. Used to
* uniquely name theater threads.
*/
static final AtomicInteger THEATER_COUNT = new AtomicInteger(0);
/**
* Atomic {@link #status} field updater, used to linearize theater startup
* and shutdown.
*/
static final AtomicIntegerFieldUpdater<Theater> STATUS =
AtomicIntegerFieldUpdater.newUpdater(Theater.class, "status");
}
/**
* {@code TaskContext} that executes its sequential process on a {@code
* Theater} stage.
*/
class TheaterTask implements TaskContext, Runnable, ForkJoinPool.ManagedBlocker {
/**
* {@code Theater} to which the {@code task} is bound.
*/
final Theater theater;
/**
* {@code TaskFunction} to invoke when the cued task executes.
*/
final TaskFunction task;
/**
* Atomic bit field with {@link #CUED} and {@link #RUNNING} flags.
*/
volatile int status;
TheaterTask(Theater theater, TaskFunction task) {
this.theater = theater;
this.task = task;
}
@Override
public Stage stage() {
return this.theater;
}
@Override
public boolean isCued() {
return (this.status & CUED) != 0;
}
@Override
public boolean isReleasable() {
return (this.status & RUNNING) == 0;
}
@Override
public boolean cue() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & CUED) == 0) {
newStatus = oldStatus | CUED;
} else {
newStatus = oldStatus;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus && (newStatus & RUNNING) == 0) {
this.theater.taskWillCue(this.task);
if (this.task instanceof Task) {
((Task) this.task).taskWillCue();
}
this.theater.execute(this);
return true;
} else {
return false;
}
}
@Override
public boolean cancel() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~CUED;
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus && (newStatus & RUNNING) == 0) {
if (this.task instanceof Task) {
((Task) this.task).taskDidCancel();
}
this.theater.taskDidCancel(this.task);
return true;
} else {
return false;
}
}
@Override
public void run() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = (oldStatus | RUNNING) & ~CUED;
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & CUED) != 0) {
this.theater.taskWillRun(this.task);
try {
if (this.task instanceof Task && ((Task) this.task).taskWillBlock()) {
ForkJoinPool.managedBlock(this);
} else {
this.task.runTask();
}
this.theater.taskDidRun(this.task);
} catch (Throwable error) {
this.theater.taskDidFail(this.task, error);
}
}
do {
oldStatus = this.status;
newStatus = oldStatus & ~RUNNING;
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if ((newStatus & CUED) != 0) {
this.theater.taskWillCue(this.task);
if (this.task instanceof Task) {
((Task) this.task).taskWillCue();
}
this.theater.execute(this);
}
}
@Override
public boolean block() {
this.task.runTask();
return true;
}
/**
* Atomic {@link #status} bit flag indicating that the task is currently
* cued for execution.
*/
static final int CUED = 1 << 0;
/**
* Atomic {@link #status} bit flag indicating that the task is currently
* executing.
*/
static final int RUNNING = 1 << 1;
/**
* Atomic {@link #status} field updater, used to linearize task cueing.
*/
static final AtomicIntegerFieldUpdater<TheaterTask> STATUS =
AtomicIntegerFieldUpdater.newUpdater(TheaterTask.class, "status");
}
/**
* {@code Call} that executes its {@code Cont}inuation on a {@code Theater}
* stage.
*/
final class TheaterCall<T> implements Call<T>, Runnable {
/**
* {@code Theater} stage on which the {@code cont}inuation executes.
*/
final Theater theater;
/**
* {@code Cont}inuation to invoke when the call is completed.
*/
final Cont<T> cont;
/**
* Completed result of this call; either the bound value of type {@code T},
* or the trapped error of type {@code Throwable}. The type of {@code result}
* is decided by the flags of the {@code status} field.
*/
volatile Object result;
/**
* Atomic bit field with {@link #BIND}, {@link #TRAP}, {@link #CUED}, and
* {@link #DONE} flags.
*/
volatile int status;
TheaterCall(Theater theater, Cont<T> cont) {
this.theater = theater;
this.cont = cont;
}
@Override
public Cont<T> cont() {
return this.cont;
}
@Override
public void bind(T value) {
if (!tryBind(value)) {
throw new ContException("continuation already completed");
}
}
@Override
public void trap(Throwable error) {
if (!tryTrap(error)) {
throw new ContException("continuation already completed");
}
}
@Override
public boolean tryBind(T value) {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if (oldStatus == 0) {
newStatus = oldStatus | BIND | CUED;
} else {
newStatus = oldStatus;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.result = value;
this.theater.callWillCue(this.cont);
this.theater.execute(this);
return true;
} else {
return false;
}
}
@Override
public boolean tryTrap(Throwable error) {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if (oldStatus == 0) {
newStatus = oldStatus | TRAP | CUED;
} else {
newStatus = oldStatus;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.result = error;
this.theater.callWillCue(this.cont);
this.theater.execute(this);
return true;
} else {
return false;
}
}
@SuppressWarnings("unchecked")
@Override
public void run() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & CUED) != 0) {
newStatus = oldStatus & ~CUED;
} else {
newStatus = oldStatus;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
if ((newStatus & BIND) != 0) {
final T result = (T) this.result;
this.theater.callWillBind(this.cont, result);
try {
this.cont.bind(result);
this.theater.callDidBind(this.cont, result);
} catch (Throwable error) {
this.theater.callDidFail(this.cont, error);
this.cont.trap(error);
}
} else if ((newStatus & TRAP) != 0) {
final Throwable result = (Throwable) this.result;
this.theater.callWillTrap(this.cont, result);
try {
this.cont.trap(result);
this.theater.callDidTrap(this.cont, result);
} catch (Throwable error) {
this.theater.callDidFail(this.cont, error);
}
}
}
do {
oldStatus = this.status;
newStatus = oldStatus | DONE;
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
}
/**
* Atomic {@link #status} bit flag indicating that the call has completed
* with a value.
*/
static final int BIND = 1 << 0;
/**
* Atomic {@link #status} bit flag indicating that the call has failed with
* an error.
*/
static final int TRAP = 1 << 1;
/**
* Atomic {@link #status} bit flag indicating that the continuation has been
* cued for execution.
*/
static final int CUED = 1 << 2;
/**
* Atomic {@link #status} bit flag indicating that the continuation has
* finished executing, completing the continuation.
*/
static final int DONE = 1 << 3;
/**
* Atomic {@link #status} field updater, used to linearize cont completion.
*/
@SuppressWarnings("unchecked")
static final AtomicIntegerFieldUpdater<TheaterCall<?>> STATUS =
AtomicIntegerFieldUpdater.newUpdater((Class<TheaterCall<?>>) (Class<?>) TheaterCall.class, "status");
}
/**
* Factory for {@code TheaterWorker} threads.
*/
final class TheaterWorkerFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory {
/**
* {@code Theater} for which this factory instantiates workers.
*/
final Theater theater;
/**
* Total number of worker threads ever started by this factory.
*/
volatile int workerCount;
TheaterWorkerFactory(Theater theater) {
this.theater = theater;
}
@Override
public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
return new TheaterWorker(pool, this.theater, WORKER_COUNT.getAndIncrement(this));
}
/**
* Atomic {@link #workerCount} field updater, used to count instantiated
* worker threads.
*/
static final AtomicIntegerFieldUpdater<TheaterWorkerFactory> WORKER_COUNT =
AtomicIntegerFieldUpdater.newUpdater(TheaterWorkerFactory.class, "workerCount");
}
/**
* {@code Theater} worker thread.
*/
final class TheaterWorker extends ForkJoinWorkerThread {
TheaterWorker(ForkJoinPool pool, Theater theater, int workerId) {
super(pool);
setName(theater.name + workerId);
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TheaterDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Slot;
import swim.structure.Value;
import swim.util.Murmur3;
public class TheaterDef implements StageDef, Debug {
final String name;
final int parallelism;
final ScheduleDef scheduleDef;
public TheaterDef(String name, int parallelism, ScheduleDef scheduleDef) {
this.name = name;
this.parallelism = parallelism;
this.scheduleDef = scheduleDef;
}
public final String name() {
return this.name;
}
public TheaterDef name(String name) {
return copy(name, this.parallelism, this.scheduleDef);
}
public final int parallelism() {
return this.parallelism;
}
public TheaterDef parallelism(int parallelism) {
return copy(this.name, parallelism, this.scheduleDef);
}
public final ScheduleDef scheduleDef() {
return this.scheduleDef;
}
public TheaterDef scheduleDef(ScheduleDef scheduleDef) {
return copy(this.name, this.parallelism, scheduleDef);
}
protected TheaterDef copy(String name, int parallelism, ScheduleDef scheduleDef) {
return new TheaterDef(name, parallelism, scheduleDef);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof TheaterDef) {
final TheaterDef that = (TheaterDef) other;
return (this.name == null ? that.name == null : this.name.equals(that.name))
&& this.parallelism == that.parallelism
&& (this.scheduleDef == null ? that.scheduleDef == null : this.scheduleDef.equals(that.scheduleDef));
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(TheaterDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.name)), this.parallelism), Murmur3.hash(this.scheduleDef)));
}
@Override
public void debug(Output<?> output) {
output = output.write("TheaterDef").write('.').write("standard").write('(').write(')');
if (this.name != null) {
output = output.write('.').write("name").write('(').debug(name).write(')');
}
if (this.parallelism != Runtime.getRuntime().availableProcessors()) {
output = output.write('.').write("parallelism").write('(').debug(parallelism).write(')');
}
if (this.scheduleDef != null) {
output = output.write('.').write("scheduleDef").write('(').debug(scheduleDef).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static TheaterDef standard;
private static Form<TheaterDef> theaterForm;
public static TheaterDef standard() {
if (standard == null) {
standard = new TheaterDef(null, 0, null);
}
return standard;
}
public static Form<TheaterDef> theaterForm(Form<ScheduleDef> scheduleForm) {
return new TheaterForm(scheduleForm, standard());
}
@Kind
public static Form<TheaterDef> theaterForm() {
if (theaterForm == null) {
theaterForm = new TheaterForm(ScheduleDef.form(), standard());
}
return theaterForm;
}
}
final class TheaterForm extends Form<TheaterDef> {
final Form<ScheduleDef> scheduleForm;
final TheaterDef unit;
TheaterForm(Form<ScheduleDef> scheduleForm, TheaterDef unit) {
this.scheduleForm = scheduleForm;
this.unit = unit;
}
@Override
public String tag() {
return "theater";
}
@Override
public TheaterDef unit() {
return this.unit;
}
@Override
public Form<TheaterDef> unit(TheaterDef unit) {
return new TheaterForm(this.scheduleForm, unit);
}
@Override
public Class<TheaterDef> type() {
return TheaterDef.class;
}
@Override
public Item mold(TheaterDef theaterDef) {
if (theaterDef != null) {
final Record record = Record.create(3).attr(tag());
record.slot("parallelism", theaterDef.parallelism);
if (theaterDef.scheduleDef != null) {
record.add(this.scheduleForm.mold(theaterDef.scheduleDef));
}
return theaterDef.name != null ? Slot.of(theaterDef.name, record) : record;
} else {
return Item.extant();
}
}
@Override
public TheaterDef cast(Item item) {
final Value value = item.toValue();
final Value header = value.getAttr(tag());
if (header.isDefined()) {
final String name = item.key().stringValue(null);
int parallelism = Runtime.getRuntime().availableProcessors();
ScheduleDef scheduleDef = null;
for (int i = 0, n = value.length(); i < n; i += 1) {
final Item member = value.getItem(i);
if (member.keyEquals("parallelism")) {
parallelism = member.toValue().intValue(parallelism);
continue;
}
final ScheduleDef newScheduleDef = this.scheduleForm.cast(member);
if (newScheduleDef != null) {
scheduleDef = newScheduleDef;
continue;
}
}
return new TheaterDef(name, parallelism, scheduleDef);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/Timer.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Stateful {@link TimerFunction} to invoke at a scheduled time, with lifecycle
* callbacks, and a {@link TimerContext} for self-management. Use {@link
* Schedule#setTimer(long, TimerFunction)} to schedule a new {@code Timer} for
* execution.
*
* @see AbstractTimer
* @see Schedule
*/
public interface Timer extends TimerFunction {
/**
* Returns the context used to manage this {@code Timer}. Returns {@code
* null} if this {@code Timer} is not bound to a {@link Schedule}.
*/
TimerContext timerContext();
/**
* Sets the context used to manage this {@code Timer}. A {@code
* TimerContext} is assigned when binding this {@code Timer} to a {@link
* Schedule}.
*/
void setTimerContext(TimerContext timerContext);
/**
* Executes scheduled logic when this {@code Timer} fires.
*/
@Override
void runTimer();
/**
* Lifecycle callback invoked before this {@code Timer} is scheduled for
* execution.
*/
void timerWillSchedule(long millis);
/**
* Lifecycle callback invoked after this {@code Timer} is explicitly
* cancelled.
*/
void timerDidCancel();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TimerContext.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Internal context that binds a {@link Timer} to a {@link Schedule}.
* A {@code TimerContext} can be used by a {@code Timer} to check its status,
* to reschedule itself, and to cancel itself. {@code TimerContext} is thread
* safe.
*
* @see Timer
*/
public interface TimerContext extends TimerRef {
/**
* Returns the {@code Schedule} to which the timer is bound.
*/
Schedule schedule();
/**
* Returns {@code true} if the timer is currently scheduled to execute.
*/
@Override
boolean isScheduled();
/**
* Schedules the timer to execute after {@code millis} milliseconds has
* elapsed. If the timer is currently scheduled, it will not ececute at its
* previously scheduled time; it will only execute at the newly scheduled
* time.
*
* @throws TimerException if {@code millis} is negative.
*/
@Override
void reschedule(long millis);
/**
* Cancels the timer to prevent it from executing. Returns {@code true} if
* this operation caused the cancellation of the timer; returns {@code false}
* if the timer was not scheduled to execute.
*/
@Override
boolean cancel();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TimerException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Thrown when performing an invalid operation on a {@link TimerFunction}.
*/
public class TimerException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TimerException(String message, Throwable cause) {
super(message, cause);
}
public TimerException(String message) {
super(message);
}
public TimerException(Throwable cause) {
super(cause);
}
public TimerException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TimerFunction.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* Function to invoke at a scheduled time. Use {@link Schedule#setTimer(long,
* TimerFunction)} to schedule a {@code TimerFunction} for future execution.
*
* @see Timer
* @see Schedule
*/
//@FunctionalInterface
public interface TimerFunction {
/**
* Executes scheduled logic when this timer fires.
*/
void runTimer();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/TimerRef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.concurrent;
/**
* External handle to a {@link TimerFunction} bound to a {@link Schedule}. A
* {@code TimerRef} can be used to check the status of a timer, to reschedule
* it, and to cancel it. {@code TimerRef} is thread safe.
*
* @see Schedule
*/
public interface TimerRef {
/**
* Returns {@code true} if the timer is currently scheduled to execute.
*/
boolean isScheduled();
/**
* Schedules the timer to execute after {@code millis} milliseconds has
* elapsed. If the timer is currently scheduled, it will not execute at its
* previously scheduled time; it will only execute at the newly scheduled
* time.
*
* @throws TimerException if {@code millis} is negative.
*/
void reschedule(long millis);
/**
* Cancels the timer to prevent it from executing. Returns {@code true} if
* this operation caused the cancellation of the timer; returns {@code false}
* if the timer was not scheduled to execute.
*/
boolean cancel();
}
|
0 | java-sources/ai/swim/swim-concurrent/3.10.0/swim | java-sources/ai/swim/swim-concurrent/3.10.0/swim/concurrent/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Lightweight timers, tasks, and continuations.
*
* <h2>Timers</h2>
*
* <p>A {@link TimerFunction} represents a function to invoke at a scheduled
* time. Scheduling a timer yields a {@link TimerRef}, which can be used to
* check the status of the timer, to reschedule it, and to cancel it. A {@link
* Timer} represents a stateful {@code TimerFunction}, with lifecycle callbacks,
* and a {@link TimerContext} that enables self-management.</p>
*
* <h2>Tasks</h2>
*
* <p>A {@link TaskFunction} represents a function to invoke as a sequential
* process in a concurrent environment. Registering a task yields a {@link
* TaskRef}, which is used to cue the task for execution. A {@link Task}
* represents a stateful {@code TaskFunction}, with lifecycle callbacks, and a
* {@link TaskContext} that enables self-management. A {@code Task} is like a
* primitive <a href="https://en.wikipedia.org/wiki/Actor_model">actor</a> that
* lacks a builtin mailbox.</p>
*
* <h2>Conts</h2>
*
* <p>A {@link Cont} represents the continuation of an asynchronous operation.
* {@link Conts} has factory functions to construct various {@code Cont}inuation
* combinators. {@link Sync} implements a synchronous {@code Cont}inuation that
* continues the current thread of execution after an asynchronous operation
* completes.</p>
*
* <h2>Calls</h2>
*
* <p>A {@link Call} provides a handle used to eventually complete an
* asynchronous operation by invoking a {@code Cont}inuation. Although a
* {@code Cont}inuation can be completed directly, by invoking {@link
* Cont#bind(Object) bind(T)}, or {@link Cont#trap(Throwable)}, completeing a
* {@code Cont}inuation through a {@code Call} abstracts over the execution
* context in which the {@code Cont}inuation runs. For example, a {@code Call}
* returned by {@link Stage#call(Cont)} invokes its bound {@code Cont}inuation
* in an asynchronous task, preventing unbounded stack growth from occurring
* when chaining large numbers of {@code Cont}inuations together.</p>
*
* <h2>Schedules</h2>
*
* <p>A {@link Schedule} arranges for the on-time execution of timers. {@link
* Clock} implements a {@code Schedule} algorithm that efficiently scales to
* large numbers of timers.</p>
*
* <h2>Stages</h2>
*
* <p>A {@link Stage} concurrently executes sequential tasks. {@link Theater}
* implements an execution {@code Stage} backed by a {@code ForkJoinPool}.</p>
*/
package swim.concurrent;
|
0 | java-sources/ai/swim/swim-dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Dynamic structured data model.
*/
module swim.dataflow {
requires swim.util;
requires transitive swim.structure;
requires transitive swim.collections;
requires transitive swim.streamlet;
exports swim.dataflow;
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/AbstractRecordOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import java.util.Iterator;
import swim.collections.HashTrieMap;
import swim.streamlet.Inlet;
import swim.streamlet.KeyEffect;
import swim.streamlet.KeyOutlet;
import swim.streamlet.MapInlet;
import swim.streamlet.Outlet;
import swim.streamlet.StreamletContext;
import swim.streamlet.StreamletScope;
import swim.structure.Field;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Text;
import swim.structure.Value;
import swim.util.Cursor;
public abstract class AbstractRecordOutlet extends Record implements RecordOutlet {
protected HashTrieMap<Value, KeyEffect> effects;
protected HashTrieMap<Value, KeyOutlet<Value, Value>> outlets;
protected Inlet<? super Record>[] outputs;
protected int version;
public AbstractRecordOutlet() {
this.effects = HashTrieMap.empty();
this.outlets = HashTrieMap.empty();
this.outputs = null;
this.version = -1;
}
@Override
public StreamletScope<? extends Value> streamletScope() {
return null;
}
@Override
public StreamletContext streamletContext() {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope != null) {
return scope.streamletContext();
}
return null;
}
public boolean containsOwnKey(Value key) {
return containsKey(key);
}
@Override
public abstract Iterator<Value> keyIterator();
@Override
public Record get() {
return this;
}
@Override
public Outlet<Value> outlet(Value key) {
if (!containsOwnKey(key)) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof RecordOutlet && ((RecordOutlet) scope).containsKey(key)) {
// TODO: Support dynamic shadowing?
return ((RecordOutlet) scope).outlet(key);
}
}
KeyOutlet<Value, Value> outlet = this.outlets.get(key);
if (outlet == null) {
outlet = new KeyOutlet<Value, Value>(this, key);
this.outlets = this.outlets.updated(key, outlet);
invalidateInputKey(key, KeyEffect.UPDATE);
}
return outlet;
}
@Override
public Outlet<Value> outlet(String key) {
return outlet(Text.from(key));
}
@Override
public Iterator<Inlet<? super Record>> outputIterator() {
return this.outputs != null ? Cursor.array(this.outputs) : Cursor.empty();
}
@SuppressWarnings("unchecked")
@Override
public void bindOutput(Inlet<? super Record> output) {
final Inlet<? super Record>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
final Inlet<? super Record>[] newOutputs = (Inlet<? super Record>[]) new Inlet<?>[n + 1];
if (n > 0) {
System.arraycopy(oldOutputs, 0, newOutputs, 0, n);
}
newOutputs[n] = output;
this.outputs = newOutputs;
}
@SuppressWarnings("unchecked")
@Override
public void unbindOutput(Inlet<? super Record> output) {
final Inlet<? super Record>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
for (int i = 0; i < n; i += 1) {
if (oldOutputs[i] == output) {
if (n > 1) {
final Inlet<? super Record>[] newOutputs = (Inlet<? super Record>[]) new Inlet<?>[n - 1];
System.arraycopy(oldOutputs, 0, newOutputs, 0, i);
System.arraycopy(oldOutputs, i + 1, newOutputs, i, (n - 1) - i);
this.outputs = newOutputs;
} else {
this.outputs = null;
}
break;
}
}
}
@Override
public void unbindOutputs() {
final HashTrieMap<Value, KeyOutlet<Value, Value>> outlets = this.outlets;
if (!outlets.isEmpty()) {
this.outlets = HashTrieMap.empty();
final Iterator<KeyOutlet<Value, Value>> keyOutlets = outlets.valueIterator();
while (keyOutlets.hasNext()) {
final KeyOutlet<Value, Value> keyOutlet = keyOutlets.next();
keyOutlet.unbindOutputs();
}
}
final Inlet<? super Record>[] oldOutputs = this.outputs;
if (oldOutputs != null) {
this.outputs = null;
for (int i = 0, n = oldOutputs.length; i < n; i += 1) {
oldOutputs[i].unbindInput();
}
}
}
@Override
public void disconnectOutputs() {
final HashTrieMap<Value, KeyOutlet<Value, Value>> outlets = this.outlets;
if (!outlets.isEmpty()) {
this.outlets = HashTrieMap.empty();
final Iterator<KeyOutlet<Value, Value>> keyOutlets = outlets.valueIterator();
while (keyOutlets.hasNext()) {
final KeyOutlet<Value, Value> keyOutlet = keyOutlets.next();
keyOutlet.disconnectOutputs();
}
}
final Inlet<? super Record>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super Record> output = outputs[i];
output.unbindInput();
output.disconnectOutputs();
}
}
for (Item member : this) {
if (member instanceof Field) {
member = member.toValue();
}
if (member instanceof RecordOutlet) {
((RecordOutlet) member).disconnectOutputs();
} else if (member instanceof RecordStreamlet) {
((RecordStreamlet) member).disconnectOutputs();
}
}
}
@Override
public void disconnectInputs() {
// nop
}
@SuppressWarnings("unchecked")
@Override
public void invalidateInputKey(Value key, KeyEffect effect) {
final HashTrieMap<Value, KeyEffect> oldEffects = this.effects;
if (oldEffects.get(key) != effect) {
willInvalidateInputKey(key, effect);
this.effects = oldEffects.updated(key, effect);
this.version = -1;
onInvalidateInputKey(key, effect);
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
final Inlet<?> output = this.outputs[i];
if (output instanceof MapInlet<?, ?, ?>) {
((MapInlet<Value, Value, ? super Record>) output).invalidateOutputKey(key, effect);
} else {
output.invalidateOutput();
}
}
final KeyOutlet<Value, Value> outlet = this.outlets.get(key);
if (outlet != null) {
outlet.invalidateInput();
}
didInvalidateInputKey(key, effect);
}
}
@Override
public void invalidateInput() {
if (this.version >= 0) {
willInvalidateInput();
this.version = -1;
onInvalidateInput();
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].invalidateOutput();
}
final Iterator<KeyOutlet<Value, Value>> outlets = this.outlets.valueIterator();
while (outlets.hasNext()) {
outlets.next().invalidateInput();
}
didInvalidateInput();
}
}
@SuppressWarnings("unchecked")
@Override
public void reconcileInputKey(Value key, int version) {
if (this.version < 0) {
final HashTrieMap<Value, KeyEffect> oldEffects = this.effects;
final KeyEffect effect = oldEffects.get(key);
if (effect != null) {
willReconcileInputKey(key, effect, version);
this.effects = oldEffects.removed(key);
onReconcileInputKey(key, effect, version);
for (int i = 0, n = this.outputs != null ? this.outputs.length : 0; i < n; i += 1) {
final Inlet<?> output = this.outputs[i];
if (output instanceof MapInlet<?, ?, ?>) {
((MapInlet<Value, Value, ? super Record>) output).reconcileOutputKey(key, version);
}
}
final KeyOutlet<Value, Value> outlet = this.outlets.get(key);
if (outlet != null) {
outlet.reconcileInput(version);
}
didReconcileInputKey(key, effect, version);
}
}
}
@Override
public void reconcileInput(int version) {
if (this.version < 0) {
willReconcileInput(version);
final Iterator<Value> keys = this.effects.keyIterator();
while (keys.hasNext()) {
reconcileInputKey(keys.next(), version);
}
this.version = version;
onReconcileInput(version);
for (int i = 0, n = this.outputs != null ? this.outputs.length : 0; i < n; i += 1) {
this.outputs[i].reconcileOutput(version);
}
for (Item member : this) {
if (member instanceof Field) {
member = member.toValue();
}
if (member instanceof RecordOutlet) {
((RecordOutlet) member).reconcileInput(version);
} else if (member instanceof RecordStreamlet) {
((RecordStreamlet) member).reconcile(version);
}
}
didReconcileInput(version);
}
}
protected void willInvalidateInputKey(Value key, KeyEffect effect) {
// stub
}
protected void onInvalidateInputKey(Value key, KeyEffect effect) {
// stub
}
protected void didInvalidateInputKey(Value key, KeyEffect effect) {
// stub
}
protected void willInvalidateInput() {
// stub
}
protected void onInvalidateInput() {
// stub
}
protected void didInvalidateInput() {
// stub
}
protected void willReconcileInputKey(Value key, KeyEffect effect, int version) {
// stub
}
protected void onReconcileInputKey(Value key, KeyEffect effect, int version) {
// stub
}
protected void didReconcileInputKey(Value key, KeyEffect effect, int version) {
// stub
}
protected void willReconcileInput(int version) {
// stub
}
protected void onReconcileInput(int version) {
// stub
}
protected void didReconcileInput(int version) {
// stub
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/AbstractRecordStreamlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import java.util.Map;
import swim.streamlet.AbstractStreamlet;
import swim.streamlet.GenericStreamlet;
import swim.streamlet.In;
import swim.streamlet.Inlet;
import swim.streamlet.Inout;
import swim.streamlet.Inoutlet;
import swim.streamlet.Outlet;
import swim.streamlet.Streamlet;
import swim.streamlet.StreamletContext;
import swim.streamlet.StreamletInlet;
import swim.streamlet.StreamletInoutlet;
import swim.streamlet.StreamletOutlet;
import swim.streamlet.StreamletScope;
import swim.structure.Field;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Slot;
import swim.structure.Text;
import swim.structure.Value;
public abstract class AbstractRecordStreamlet<I extends Value, O extends Value> extends RecordStreamlet<I, O> implements GenericStreamlet<I, O> {
protected StreamletScope<? extends O> scope;
protected StreamletContext context;
protected int version;
public AbstractRecordStreamlet(StreamletScope<? extends O> scope) {
this.scope = scope;
this.version = -1;
}
public AbstractRecordStreamlet() {
this(null);
}
@Override
public StreamletScope<? extends O> streamletScope() {
return this.scope;
}
@Override
public void setStreamletScope(StreamletScope<? extends O> scope) {
this.scope = scope;
}
@Override
public StreamletContext streamletContext() {
if (this.context != null) {
return this.context;
}
final StreamletScope<? extends O> scope = streamletScope();
if (scope != null) {
return scope.streamletContext();
}
return null;
}
@Override
public void setStreamletContext(StreamletContext context) {
this.context = context;
}
@Override
public boolean isEmpty() {
return size() != 0;
}
@Override
public int size() {
return AbstractStreamlet.reflectOutletCount(getClass());
}
@Override
public boolean containsKey(Value key) {
if (!(key instanceof Text)) {
return false;
}
final Outlet<O> outlet = outlet(((Text) key).stringValue());
return outlet != null;
}
@Override
public boolean containsKey(String key) {
final Outlet<O> outlet = outlet(key);
return outlet != null;
}
@Override
public Value get(Value key) {
if (!(key instanceof Text)) {
return Value.absent();
}
final Outlet<O> outlet = outlet(((Text) key).stringValue());
if (outlet != null) {
final Value output = outlet.get();
if (output != null) {
return output;
}
}
return Value.absent();
}
@Override
public Value get(String key) {
final Outlet<O> outlet = outlet(key);
if (outlet != null) {
final Value output = outlet.get();
if (output != null) {
return output;
}
}
return Value.absent();
}
@Override
public Value getAttr(Text key) {
return Value.absent();
}
@Override
public Value getAttr(String key) {
return Value.absent();
}
@Override
public Value getSlot(Value key) {
return get(key);
}
@Override
public Value getSlot(String key) {
return get(key);
}
@Override
public Field getField(Value key) {
final Value value = get(key);
if (value.isDefined()) {
return Slot.of(key, value);
}
return null;
}
@Override
public Field getField(String key) {
final Value value = get(key);
if (value.isDefined()) {
return Slot.of(key, value);
}
return null;
}
@Override
public Item get(int index) {
final Map.Entry<String, Outlet<O>> entry = AbstractStreamlet.reflectOutletIndex(index, this, getClass());
if (entry != null) {
final String name = entry.getKey();
final Value output = entry.getValue().get();
if (output != null) {
return Slot.of(name, output);
}
}
throw new IndexOutOfBoundsException(Integer.toString(index));
}
@Override
public Item getItem(int index) {
final Map.Entry<String, Outlet<O>> entry = AbstractStreamlet.reflectOutletIndex(index, this, getClass());
if (entry != null) {
final String name = entry.getKey();
Value output = entry.getValue().get();
if (output == null) {
output = Value.extant();
}
return Slot.of(name, output);
}
return Item.absent();
}
@Override
public Value put(Value key, Value newValue) {
throw new UnsupportedOperationException();
}
@Override
public Value put(String key, Value newValue) {
throw new UnsupportedOperationException();
}
@Override
public Value putAttr(Text key, Value newValue) {
throw new UnsupportedOperationException();
}
@Override
public Value putAttr(String key, Value newValue) {
throw new UnsupportedOperationException();
}
@Override
public Value putSlot(Value key, Value newValue) {
throw new UnsupportedOperationException();
}
@Override
public Value putSlot(String key, Value newValue) {
throw new UnsupportedOperationException();
}
@Override
public Item setItem(int index, Item item) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(Item item) {
throw new UnsupportedOperationException();
}
@Override
public void add(int index, Item item) {
throw new UnsupportedOperationException();
}
@Override
public Item remove(int index) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeKey(Value key) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeKey(String key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Inlet<I> inlet(String key) {
return AbstractStreamlet.reflectInletKey(key, this, getClass());
}
protected <I2 extends I> Inlet<I2> inlet() {
return new StreamletInlet<I2>(this);
}
@Override
public void bindInput(String key, Outlet<? extends I> input) {
final Inlet<I> inlet = inlet(key);
if (inlet == null) {
throw new IllegalArgumentException(key.toString());
}
inlet.bindInput(input);
}
@Override
public void unbindInput(String key) {
final Inlet<I> inlet = inlet(key);
if (inlet == null) {
throw new IllegalArgumentException(key.toString());
}
inlet.unbindInput();
}
@Override
public Outlet<O> outlet(String key) {
return AbstractStreamlet.reflectOutletKey(key, this, getClass());
}
@SuppressWarnings("unchecked")
protected <O2 extends Value> Outlet<O2> outlet() {
return new StreamletOutlet<O2>((Streamlet<I, ? extends O2>) this);
}
@SuppressWarnings("unchecked")
protected <I2 extends I, O2> Inoutlet<I2, O2> inoutlet() {
return new StreamletInoutlet<I2, O2>((Streamlet<? super I2, ? extends O2>) this);
}
@Override
public void invalidate() {
if (this.version >= 0) {
willInvalidate();
this.version = -1;
onInvalidate();
onInvalidateOutlets();
didInvalidate();
}
}
@Override
public void reconcile(int version) {
if (this.version < 0) {
willReconcile(version);
this.version = version;
onReconcileInlets(version);
onReconcile(version);
onReconcileOutlets(version);
didReconcile(version);
}
}
public <I2 extends I> I2 getInput(Inlet<I2> inlet) {
final Outlet<? extends I2> input = inlet.input();
if (input != null) {
return input.get();
}
return null;
}
@SuppressWarnings("unchecked")
public <I2 extends I> I2 getInput(String key) {
final Inlet<I2> inlet = (Inlet<I2>) inlet(key);
if (inlet != null) {
return getInput(inlet);
}
return null;
}
public <I2 extends I> I2 getInput(Inlet<I2> inlet, I2 orElse) {
I2 input = getInput(inlet);
if (input == null) {
input = orElse;
}
return input;
}
public <I2 extends I> I2 getInput(String key, I2 orElse) {
I2 input = getInput(key);
if (input == null) {
input = orElse;
}
return input;
}
public <T> T castInput(Inlet<? extends I> inlet, Form<T> form) {
final I input = getInput(inlet);
T object = null;
if (input != null) {
object = form.cast(input);
}
return object;
}
public <T> T castInput(String key, Form<T> form) {
final I input = getInput(key);
T object = null;
if (input != null) {
object = form.cast(input);
}
return object;
}
public <T> T castInput(Inlet<? extends I> inlet, Form<T> form, T orElse) {
final I input = getInput(inlet);
T object = null;
if (input != null) {
object = form.cast(input);
}
if (object == null) {
object = orElse;
}
return object;
}
public <T> T castInput(String key, Form<T> form, T orElse) {
final I input = getInput(key);
T object = null;
if (input != null) {
object = form.cast(input);
}
if (object == null) {
object = orElse;
}
return object;
}
public <T> T coerceInput(Inlet<? extends I> inlet, Form<T> form) {
final I input = getInput(inlet);
T object = null;
if (input != null) {
object = form.cast(input);
}
if (object == null) {
object = form.unit();
}
return object;
}
public <T> T coerceInput(String key, Form<T> form) {
final I input = getInput(key);
T object = null;
if (input != null) {
object = form.cast(input);
}
if (object == null) {
object = form.unit();
}
return object;
}
public <T> T coerceInput(Inlet<? extends I> inlet, Form<T> form, T orElse) {
final I input = getInput(inlet);
T object = null;
if (input != null) {
object = form.cast(input);
}
if (object == null) {
object = form.unit();
}
if (object == null) {
object = orElse;
}
return object;
}
public <T> T coerceInput(String key, Form<T> form, T orElse) {
final I input = getInput(key);
T object = null;
if (input != null) {
object = form.cast(input);
}
if (object == null) {
object = form.unit();
}
if (object == null) {
object = orElse;
}
return object;
}
@Override
public O getOutput(Outlet<? super O> outlet) {
return null;
}
public O getOutput(String key) {
final Outlet<O> outlet = outlet(key);
if (outlet != null) {
return getOutput(outlet);
}
return null;
}
@Override
public void disconnectInputs() {
AbstractStreamlet.disconnectInputs(this, getClass());
}
@Override
public void disconnectOutputs() {
AbstractStreamlet.disconnectOutputs(this, getClass());
}
@Override
public void willInvalidateInlet(Inlet<? extends I> inlet) {
// stub
}
@Override
public void didInvalidateInlet(Inlet<? extends I> inlet) {
invalidate();
}
@Override
public void willReconcileInlet(Inlet<? extends I> inlet, int version) {
// stub
}
@Override
public void didReconcileInlet(Inlet<? extends I> inlet, int version) {
reconcile(version);
}
@Override
public void willInvalidateOutlet(Outlet<? super O> outlet) {
// stub
}
@Override
public void didInvalidateOutlet(Outlet<? super O> outlet) {
// stub
}
@Override
public void willReconcileOutlet(Outlet<? super O> outlet, int version) {
// stub
}
@Override
public void didReconcileOutlet(Outlet<? super O> outlet, int version) {
// stub
}
protected void willInvalidate() {
// stub
}
protected void onInvalidate() {
// stub
}
protected void onInvalidateOutlets() {
AbstractStreamlet.invalidateOutlets(this, getClass());
}
protected void didInvalidate() {
// stub
}
protected void willReconcile(int version) {
// stub
}
protected void onReconcileInlets(int version) {
AbstractStreamlet.reconcileInlets(version, this, getClass());
}
protected void onReconcile(int version) {
// stub
}
protected void onReconcileOutlets(int version) {
AbstractStreamlet.reconcileOutlets(version, this, getClass());
}
protected void didReconcile(int version) {
// stub
}
public static <I extends Value, O extends Value> void compileInlets(Class<?> streamletClass, RecordStreamlet<I, O> streamlet) {
while (streamletClass != null) {
final java.lang.reflect.Field[] fields = streamletClass.getDeclaredFields();
for (java.lang.reflect.Field field : fields) {
if (Inlet.class.isAssignableFrom(field.getType())) {
final In in = field.getAnnotation(In.class);
if (in != null) {
String name = in.value();
if (name.isEmpty()) {
name = field.getName();
}
final Inlet<I> inlet = AbstractStreamlet.reflectInletField(streamlet, field);
streamlet.compileInlet(inlet, name);
continue;
}
final Inout inout = field.getAnnotation(Inout.class);
if (inout != null) {
String name = inout.value();
if (name.isEmpty()) {
name = field.getName();
}
final Inoutlet<I, O> inoutlet = AbstractStreamlet.reflectInoutletField(streamlet, field);
streamlet.compileInlet(inoutlet, name);
continue;
}
}
}
streamletClass = streamletClass.getSuperclass();
}
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/Dataflow.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import swim.dataflow.operator.AndOutlet;
import swim.dataflow.operator.BinaryOutlet;
import swim.dataflow.operator.BitwiseAndOutlet;
import swim.dataflow.operator.BitwiseNotOutlet;
import swim.dataflow.operator.BitwiseOrOutlet;
import swim.dataflow.operator.BitwiseXorOutlet;
import swim.dataflow.operator.ConditionalOutlet;
import swim.dataflow.operator.DivideOutlet;
import swim.dataflow.operator.EqOutlet;
import swim.dataflow.operator.GeOutlet;
import swim.dataflow.operator.GtOutlet;
import swim.dataflow.operator.InvokeOutlet;
import swim.dataflow.operator.LeOutlet;
import swim.dataflow.operator.LtOutlet;
import swim.dataflow.operator.MinusOutlet;
import swim.dataflow.operator.ModuloOutlet;
import swim.dataflow.operator.NeOutlet;
import swim.dataflow.operator.NegativeOutlet;
import swim.dataflow.operator.NotOutlet;
import swim.dataflow.operator.OrOutlet;
import swim.dataflow.operator.PlusOutlet;
import swim.dataflow.operator.PositiveOutlet;
import swim.dataflow.operator.TimesOutlet;
import swim.dataflow.operator.UnaryOutlet;
import swim.dataflow.selector.GetOutlet;
import swim.streamlet.KeyOutlet;
import swim.streamlet.Outlet;
import swim.streamlet.StreamletScope;
import swim.streamlet.ValueInput;
import swim.structure.Operator;
import swim.structure.Record;
import swim.structure.Selector;
import swim.structure.Value;
import swim.structure.operator.AndOperator;
import swim.structure.operator.BinaryOperator;
import swim.structure.operator.BitwiseAndOperator;
import swim.structure.operator.BitwiseNotOperator;
import swim.structure.operator.BitwiseOrOperator;
import swim.structure.operator.BitwiseXorOperator;
import swim.structure.operator.ConditionalOperator;
import swim.structure.operator.DivideOperator;
import swim.structure.operator.EqOperator;
import swim.structure.operator.GeOperator;
import swim.structure.operator.GtOperator;
import swim.structure.operator.InvokeOperator;
import swim.structure.operator.LeOperator;
import swim.structure.operator.LtOperator;
import swim.structure.operator.MinusOperator;
import swim.structure.operator.ModuloOperator;
import swim.structure.operator.NeOperator;
import swim.structure.operator.NegativeOperator;
import swim.structure.operator.NotOperator;
import swim.structure.operator.OrOperator;
import swim.structure.operator.PlusOperator;
import swim.structure.operator.PositiveOperator;
import swim.structure.operator.TimesOperator;
import swim.structure.operator.UnaryOperator;
import swim.structure.selector.ChildrenSelector;
import swim.structure.selector.DescendantsSelector;
import swim.structure.selector.FilterSelector;
import swim.structure.selector.GetAttrSelector;
import swim.structure.selector.GetItemSelector;
import swim.structure.selector.GetSelector;
import swim.structure.selector.IdentitySelector;
import swim.structure.selector.KeysSelector;
import swim.structure.selector.ValuesSelector;
public final class Dataflow {
private Dataflow() {
// nop
}
/**
* Returns an {@code Outlet} that evaluates the given {@code expr} in the
* context of the giveb {@code scope}, and updates whenever any dependent
* expression updates.
*/
@SuppressWarnings("unchecked")
public static Outlet<Value> compile(Value expr, Outlet<? extends Value> scope) {
if (scope instanceof KeyOutlet<?, ?>) {
final Value value = ((KeyOutlet<Value, Value>) scope).get();
if (value instanceof Outlet<?>) {
scope = (Outlet<? extends Value>) value;
}
}
if (expr.isConstant()) {
return new ValueInput<Value>(expr);
} else if (expr instanceof Selector) {
return compileSelector((Selector) expr, scope);
} else if (expr instanceof Operator) {
return compileOperator((Operator) expr, scope);
}
throw new IllegalArgumentException(expr.toString());
}
private static Outlet<Value> compileSelector(Selector selector, Outlet<? extends Value> scope) {
if (selector instanceof IdentitySelector) {
return compileIdentitySelector(scope);
} else if (selector instanceof GetSelector) {
return compileGetSelector((GetSelector) selector, scope);
} else if (selector instanceof GetAttrSelector) {
return compileGetAttrSelector((GetAttrSelector) selector, scope);
} else if (selector instanceof GetItemSelector) {
return compileGetItemSelector((GetItemSelector) selector, scope);
} else if (selector instanceof KeysSelector) {
return compileKeysSelector(scope);
} else if (selector instanceof ValuesSelector) {
return compileValuesSelector(scope);
} else if (selector instanceof ChildrenSelector) {
return compileChildrenSelector(scope);
} else if (selector instanceof DescendantsSelector) {
return compileDescendantsSelector(scope);
} else if (selector instanceof FilterSelector) {
return compileFilterSelector((FilterSelector) selector, scope);
}
throw new IllegalArgumentException(selector.toString());
}
@SuppressWarnings("unchecked")
private static Outlet<Value> compileIdentitySelector(Outlet<? extends Value> scope) {
return (Outlet<Value>) scope;
}
@SuppressWarnings("unchecked")
private static Outlet<Value> compileGetSelector(GetSelector selector, Outlet<? extends Value> scope) {
final Value key = selector.accessor();
if (key.isConstant()) {
if (scope instanceof RecordOutlet) {
final Outlet<Value> outlet = ((RecordScope) scope).outlet(key);
if (outlet != null) {
return compile(selector.then(), outlet);
}
} else if (scope instanceof StreamletScope<?>) {
final String name = key.stringValue(null);
if (name != null) {
final Outlet<Value> outlet = ((StreamletScope<Value>) scope).outlet(name);
if (outlet != null) {
return compile(selector.then(), outlet);
}
}
}
} else {
final GetOutlet getOutlet = new GetOutlet();
final Outlet<Value> outlet = compile(key, scope);
getOutlet.keyInlet().bindInput(outlet);
getOutlet.mapInlet().bindInput((Outlet<? extends Value>) scope);
return getOutlet;
}
return null;
}
private static Outlet<Value> compileGetAttrSelector(GetAttrSelector selector, Outlet<? extends Value> scope) {
throw new UnsupportedOperationException(); // TODO
}
private static Outlet<Value> compileGetItemSelector(GetItemSelector selector, Outlet<? extends Value> scope) {
throw new UnsupportedOperationException(); // TODO
}
private static Outlet<Value> compileKeysSelector(Outlet<? extends Value> scope) {
throw new UnsupportedOperationException(); // TODO
}
private static Outlet<Value> compileValuesSelector(Outlet<? extends Value> scope) {
throw new UnsupportedOperationException(); // TODO
}
private static Outlet<Value> compileChildrenSelector(Outlet<? extends Value> scope) {
throw new UnsupportedOperationException(); // TODO
}
private static Outlet<Value> compileDescendantsSelector(Outlet<? extends Value> scope) {
throw new UnsupportedOperationException(); // TODO
}
private static Outlet<Value> compileFilterSelector(FilterSelector selector, Outlet<? extends Value> scope) {
throw new UnsupportedOperationException(); // TODO
}
private static Outlet<Value> compileOperator(Operator operator, Outlet<? extends Value> scope) {
if (operator instanceof ConditionalOperator) {
return compileConditionalOperator((ConditionalOperator) operator, scope);
} else if (operator instanceof BinaryOperator) {
return compileBinaryOperator((BinaryOperator) operator, scope);
} else if (operator instanceof UnaryOperator) {
return compileUnaryOperator((UnaryOperator) operator, scope);
} else if (operator instanceof InvokeOperator) {
return compileInvokeOperator((InvokeOperator) operator, scope);
}
throw new IllegalArgumentException(operator.toString());
}
private static Outlet<Value> compileConditionalOperator(ConditionalOperator operator, Outlet<? extends Value> scope) {
final ConditionalOutlet outlet = new ConditionalOutlet();
final Value ifTerm = operator.ifTerm().toValue();
final Value thenTerm = operator.thenTerm().toValue();
final Value elseTerm = operator.elseTerm().toValue();
final Outlet<Value> ifOutlet = compile(ifTerm, scope);
final Outlet<Value> thenOutlet = compile(thenTerm, scope);
final Outlet<Value> elseOutlet = compile(elseTerm, scope);
outlet.ifInlet().bindInput(ifOutlet);
outlet.thenInlet().bindInput(thenOutlet);
outlet.elseInlet().bindInput(elseOutlet);
return outlet;
}
private static Outlet<Value> compileBinaryOperator(BinaryOperator operator, Outlet<? extends Value> scope) {
if (operator instanceof OrOperator) {
return compileOrOperator((OrOperator) operator, scope);
} else if (operator instanceof AndOperator) {
return compileAndOperator((AndOperator) operator, scope);
} else if (operator instanceof BitwiseOrOperator) {
return compileBitwiseOrOperator((BitwiseOrOperator) operator, scope);
} else if (operator instanceof BitwiseXorOperator) {
return compileBitwiseXorOperator((BitwiseXorOperator) operator, scope);
} else if (operator instanceof BitwiseAndOperator) {
return compileBitwiseAndOperator((BitwiseAndOperator) operator, scope);
} else if (operator instanceof LtOperator) {
return compileLtOperator((LtOperator) operator, scope);
} else if (operator instanceof LeOperator) {
return compileLeOperator((LeOperator) operator, scope);
} else if (operator instanceof EqOperator) {
return compileEqOperator((EqOperator) operator, scope);
} else if (operator instanceof NeOperator) {
return compileNeOperator((NeOperator) operator, scope);
} else if (operator instanceof GeOperator) {
return compileGeOperator((GeOperator) operator, scope);
} else if (operator instanceof GtOperator) {
return compileGtOperator((GtOperator) operator, scope);
} else if (operator instanceof PlusOperator) {
return compilePlusOperator((PlusOperator) operator, scope);
} else if (operator instanceof MinusOperator) {
return compileMinusOperator((MinusOperator) operator, scope);
} else if (operator instanceof TimesOperator) {
return compileTimesOperator((TimesOperator) operator, scope);
} else if (operator instanceof DivideOperator) {
return compileDivideOperator((DivideOperator) operator, scope);
} else if (operator instanceof ModuloOperator) {
return compileModuloOperator((ModuloOperator) operator, scope);
}
throw new IllegalArgumentException(operator.toString());
}
private static Outlet<Value> compileBinaryOutlet(BinaryOperator operator, BinaryOutlet outlet, Outlet<? extends Value> scope) {
final Value operand1 = operator.operand1().toValue();
final Value operand2 = operator.operand2().toValue();
final Outlet<Value> operand1Outlet = compile(operand1, scope);
final Outlet<Value> operand2Outlet = compile(operand2, scope);
outlet.operand1Inlet().bindInput(operand1Outlet);
outlet.operand2Inlet().bindInput(operand2Outlet);
return outlet;
}
private static Outlet<Value> compileOrOperator(OrOperator operator, Outlet<? extends Value> scope) {
final OrOutlet outlet = new OrOutlet();
final Value operand1 = operator.operand1().toValue();
final Value operand2 = operator.operand2().toValue();
final Outlet<Value> operand1Outlet = compile(operand1, scope);
final Outlet<Value> operand2Outlet = compile(operand2, scope);
outlet.operand1Inlet().bindInput(operand1Outlet);
outlet.operand2Inlet().bindInput(operand2Outlet);
return outlet;
}
private static Outlet<Value> compileAndOperator(AndOperator operator, Outlet<? extends Value> scope) {
final AndOutlet outlet = new AndOutlet();
final Value operand1 = operator.operand1().toValue();
final Value operand2 = operator.operand2().toValue();
final Outlet<Value> operand1Outlet = compile(operand1, scope);
final Outlet<Value> operand2Outlet = compile(operand2, scope);
outlet.operand1Inlet().bindInput(operand1Outlet);
outlet.operand2Inlet().bindInput(operand2Outlet);
return outlet;
}
private static Outlet<Value> compileBitwiseOrOperator(BitwiseOrOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new BitwiseOrOutlet(), scope);
}
private static Outlet<Value> compileBitwiseXorOperator(BitwiseXorOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new BitwiseXorOutlet(), scope);
}
private static Outlet<Value> compileBitwiseAndOperator(BitwiseAndOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new BitwiseAndOutlet(), scope);
}
private static Outlet<Value> compileLtOperator(LtOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new LtOutlet(), scope);
}
private static Outlet<Value> compileLeOperator(LeOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new LeOutlet(), scope);
}
private static Outlet<Value> compileEqOperator(EqOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new EqOutlet(), scope);
}
private static Outlet<Value> compileNeOperator(NeOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new NeOutlet(), scope);
}
private static Outlet<Value> compileGeOperator(GeOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new GeOutlet(), scope);
}
private static Outlet<Value> compileGtOperator(GtOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new GtOutlet(), scope);
}
private static Outlet<Value> compilePlusOperator(PlusOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new PlusOutlet(), scope);
}
private static Outlet<Value> compileMinusOperator(MinusOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new MinusOutlet(), scope);
}
private static Outlet<Value> compileTimesOperator(TimesOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new TimesOutlet(), scope);
}
private static Outlet<Value> compileDivideOperator(DivideOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new DivideOutlet(), scope);
}
private static Outlet<Value> compileModuloOperator(ModuloOperator operator, Outlet<? extends Value> scope) {
return compileBinaryOutlet(operator, new ModuloOutlet(), scope);
}
private static Outlet<Value> compileUnaryOperator(UnaryOperator operator, Outlet<? extends Value> scope) {
if (operator instanceof NotOperator) {
return compileNotOperator((NotOperator) operator, scope);
} else if (operator instanceof BitwiseNotOperator) {
return compileBitwiseNotOperator((BitwiseNotOperator) operator, scope);
} else if (operator instanceof NegativeOperator) {
return compileNegativeOperator((NegativeOperator) operator, scope);
} else if (operator instanceof PositiveOperator) {
return compilePositiveOperator((PositiveOperator) operator, scope);
}
throw new IllegalArgumentException(operator.toString());
}
private static Outlet<Value> compileUnaryOutlet(UnaryOperator operator, UnaryOutlet outlet, Outlet<? extends Value> scope) {
final Value operand = operator.operand().toValue();
final Outlet<Value> operandOutlet = compile(operand, scope);
outlet.operandInlet().bindInput(operandOutlet);
return outlet;
}
private static Outlet<Value> compileNotOperator(NotOperator operator, Outlet<? extends Value> scope) {
return compileUnaryOutlet(operator, new NotOutlet(), scope);
}
private static Outlet<Value> compileBitwiseNotOperator(BitwiseNotOperator operator, Outlet<? extends Value> scope) {
return compileUnaryOutlet(operator, new BitwiseNotOutlet(), scope);
}
private static Outlet<Value> compileNegativeOperator(NegativeOperator operator, Outlet<? extends Value> scope) {
return compileUnaryOutlet(operator, new NegativeOutlet(), scope);
}
private static Outlet<Value> compilePositiveOperator(PositiveOperator operator, Outlet<? extends Value> scope) {
return compileUnaryOutlet(operator, new PositiveOutlet(), scope);
}
private static Outlet<Value> compileInvokeOperator(InvokeOperator operator, Outlet<? extends Value> scope) {
final Value func = operator.func();
final Value args = operator.args();
final InvokeOutlet invokeOutlet = new InvokeOutlet((Record) scope);
final Outlet<Value> funcOutlet = compile(func, scope);
final Outlet<Value> argsOutlet = compile(args, scope);
invokeOutlet.funcInlet().bindInput(funcOutlet);
invokeOutlet.argsInlet().bindInput(argsOutlet);
return invokeOutlet;
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/RecordFieldUpdater.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import swim.streamlet.AbstractInlet;
import swim.streamlet.KeyEffect;
import swim.structure.Record;
import swim.structure.Value;
public class RecordFieldUpdater extends AbstractInlet<Value> {
protected final Record record;
protected final Value key;
public RecordFieldUpdater(Record record, Value key) {
this.record = record;
this.key = key;
}
@Override
protected void onInvalidateOutput() {
if (this.record instanceof RecordOutlet) {
((RecordOutlet) this.record).invalidateInputKey(this.key, KeyEffect.UPDATE);
}
}
@Override
protected void onReconcileOutput(int version) {
if (this.input != null) {
final Value value = this.input.get();
if (value != null) {
this.record.put(this.key, value);
} else {
this.record.remove(this.key);
}
}
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/RecordModel.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import java.util.Iterator;
import swim.collections.HashTrieMap;
import swim.streamlet.KeyEffect;
import swim.streamlet.MapOutlet;
import swim.streamlet.Outlet;
import swim.streamlet.StreamletScope;
import swim.structure.Field;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Slot;
import swim.structure.Text;
import swim.structure.Value;
import swim.structure.func.MathModule;
public class RecordModel extends AbstractRecordOutlet {
protected Record state;
protected HashTrieMap<Value, RecordFieldUpdater> fieldUpdaters;
public RecordModel(Record state) {
this.state = state;
this.fieldUpdaters = HashTrieMap.empty();
}
public RecordModel() {
this(Record.create());
}
@Override
public boolean isEmpty() {
return this.state.isEmpty();
}
@Override
public boolean isArray() {
return this.state.isArray();
}
@Override
public boolean isObject() {
return this.state.isObject();
}
@Override
public int size() {
return this.state.size();
}
@Override
public int fieldCount() {
return this.state.fieldCount();
}
@Override
public int valueCount() {
return this.state.valueCount();
}
@Override
public boolean containsKey(Value key) {
if (this.state.containsKey(key)) {
return true;
} else {
final StreamletScope<? extends Value> scope = streamletScope();
return scope instanceof Record ? ((Record) scope).containsKey(key) : false;
}
}
@Override
public boolean containsOwnKey(Value key) {
return this.state.containsKey(key);
}
@Override
public int indexOf(Object item) {
return this.state.indexOf(item);
}
@Override
public int lastIndexOf(Object item) {
return this.state.lastIndexOf(item);
}
@Override
public Value get(Value key) {
Value value = this.state.get(key);
if (!value.isDefined()) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof Record) {
value = ((Record) scope).get(key);
}
}
return value;
}
@Override
public Value getAttr(Text key) {
Value value = this.state.getAttr(key);
if (!value.isDefined()) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof Record) {
value = ((Record) scope).getAttr(key);
}
}
return value;
}
@Override
public Value getSlot(Value key) {
Value value = this.state.getSlot(key);
if (!value.isDefined()) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof Record) {
value = ((Record) scope).getSlot(key);
}
}
return value;
}
@Override
public Field getField(Value key) {
Field field = this.state.getField(key);
if (field == null) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof Record) {
field = ((Record) scope).getField(key);
}
}
return field;
}
@Override
public Item get(int index) {
return this.state.get(index);
}
@Override
public Item getItem(int index) {
return this.state.getItem(index);
}
public void bindValue(Value key, Value expr) {
final RecordFieldUpdater fieldUpdater = new RecordFieldUpdater(this, key);
final Outlet<? extends Value> valueInput = Dataflow.compile(expr, this);
fieldUpdater.bindInput(valueInput);
// TODO: clean up existing field updater
this.fieldUpdaters = this.fieldUpdaters.updated(key, fieldUpdater);
}
@Override
public Value put(Value key, Value newValue) {
final Value oldValue;
if (!this.state.containsKey(key)) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof Record && ((Record) scope).containsKey(key)) {
oldValue = ((Record) scope).put(key, newValue);
} else {
oldValue = this.state.put(key, newValue);
}
} else {
oldValue = this.state.put(key, newValue);
}
invalidateInputKey(key, KeyEffect.UPDATE);
return oldValue;
}
@Override
public Value put(String key, Value newValue) {
return put(Text.from(key), newValue);
}
@Override
public Value putAttr(Text key, Value newValue) {
final Value oldValue;
if (!this.state.containsKey(key)) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof Record && ((Record) scope).containsKey(key)) {
oldValue = ((Record) scope).putAttr(key, newValue);
} else {
oldValue = this.state.putAttr(key, newValue);
}
} else {
oldValue = this.state.putAttr(key, newValue);
}
invalidateInputKey(key, KeyEffect.UPDATE);
return oldValue;
}
@Override
public Value putAttr(String key, Value newValue) {
return putAttr(Text.from(key), newValue);
}
@Override
public Value putSlot(Value key, Value newValue) {
final Value oldValue;
if (!this.state.containsKey(key)) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof Record && ((Record) scope).containsKey(key)) {
oldValue = ((Record) scope).putSlot(key, newValue);
} else {
oldValue = this.state.putSlot(key, newValue);
}
} else {
oldValue = this.state.putSlot(key, newValue);
}
invalidateInputKey(key, KeyEffect.UPDATE);
return oldValue;
}
@Override
public Value putSlot(String key, Value newValue) {
return putSlot(Text.from(key), newValue);
}
@Override
public Item setItem(int index, Item newItem) {
final Item oldItem = this.state.setItem(index, newItem);
if (oldItem instanceof Field && newItem instanceof Field) {
if (oldItem.key().equals(newItem.key())) {
invalidateInputKey(oldItem.key(), KeyEffect.UPDATE);
} else {
invalidateInputKey(oldItem.key(), KeyEffect.REMOVE);
invalidateInputKey(newItem.key(), KeyEffect.UPDATE);
}
} else if (oldItem instanceof Field) {
invalidateInputKey(oldItem.key(), KeyEffect.REMOVE);
} else if (newItem instanceof Field) {
invalidateInputKey(newItem.key(), KeyEffect.UPDATE);
} else {
invalidateInput();
}
return oldItem;
}
@Override
public boolean add(Item item) {
this.state.add(item);
if (item instanceof Field) {
invalidateInputKey(item.key(), KeyEffect.UPDATE);
}
return true;
}
@Override
public void add(int index, Item item) {
this.state.add(index, item);
if (item instanceof Field) {
invalidateInputKey(item.key(), KeyEffect.UPDATE);
}
}
@SuppressWarnings("unchecked")
@Override
public Item remove(int index) {
final Item oldItem = this.state.remove(index);
if (oldItem instanceof Field) {
invalidateInputKey(oldItem.key(), KeyEffect.REMOVE);
}
return oldItem;
}
@Override
public void clear() {
final Record oldState = this.state.branch();
this.state.clear();
for (Item oldItem : oldState) {
if (oldItem instanceof Field) {
invalidateInputKey(oldItem.key(), KeyEffect.REMOVE);
}
}
}
@Override
public Record subList(int fromIndex, int toIndex) {
return this.state.subList(fromIndex, toIndex);
}
@Override
public final Iterator<Value> keyIterator() {
return this.state.keyIterator();
}
@Override
public void disconnectInputs() {
final HashTrieMap<Value, RecordFieldUpdater> fieldUpdaters = this.fieldUpdaters;
if (!fieldUpdaters.isEmpty()) {
this.fieldUpdaters = HashTrieMap.empty();
final Iterator<RecordFieldUpdater> inlets = fieldUpdaters.valueIterator();
while (inlets.hasNext()) {
final RecordFieldUpdater inlet = inlets.next();
inlet.disconnectInputs();
}
}
}
@Override
public MapOutlet<Value, Value, Record> memoize() {
return this;
}
public void materialize(Record record) {
for (Item item : record) {
materializeItem(item);
}
}
public void materializeItem(Item item) {
if (item instanceof Field) {
materializeField((Field) item);
} else {
materializeValue((Value) item);
}
}
@SuppressWarnings("unchecked")
public void materializeField(Field field) {
final Value value = field.value();
if (value instanceof RecordStreamlet<?, ?>) {
((RecordStreamlet<? super Value, ? super Value>) value).setStreamletScope(this);
this.state.add(field);
} else if (value instanceof Record) {
// Add recursively materialized nested scope.
final RecordScope child = new RecordScope(this);
child.materialize((Record) value);
this.state.add(field.updatedValue(child));
} else {
this.state.add(field);
}
}
@SuppressWarnings("unchecked")
public void materializeValue(Value value) {
if (value instanceof RecordStreamlet<?, ?>) {
((RecordStreamlet<? super Value, ? super Value>) value).setStreamletScope(this);
this.state.add(value);
} else if (value instanceof Record) {
// Add recursively materialized nested scope.
final RecordScope child = new RecordScope(this);
child.materialize((Record) value);
this.state.add(child);
} else {
this.state.add(value);
}
}
public void compile(Record record) {
int index = 0;
for (Item item : record) {
compileItem(item, index);
index += 1;
}
}
public void compileItem(Item item, int index) {
if (item instanceof Field) {
compileField((Field) item, index);
} else {
compileValue((Value) item, index);
}
}
public void compileField(Field field, int index) {
final Value key = field.key();
final Value value = field.value();
if (!key.isConstant()) {
// TODO: Add dynamic key updater.
} else if (!value.isConstant()) {
if (value instanceof RecordStreamlet) {
// Lexically bind nested streamlet.
((RecordStreamlet) value).compile();
// Invalidate nested scope key.
invalidateInputKey(key, KeyEffect.UPDATE);
} else if (value instanceof Record) {
// Recursively compile nested scope.
((RecordModel) this.state.getItem(index).toValue()).compile((Record) value);
// Invalidate nested scope key.
invalidateInputKey(key, KeyEffect.UPDATE);
} else {
// Set placeholder value.
field.setValue(Value.extant());
// Bind dynamic value updater.
bindValue(key, value);
}
} else {
// Invalidate constant key.
invalidateInputKey(key, KeyEffect.UPDATE);
}
}
public void compileValue(Value value, int index) {
if (value instanceof RecordStreamlet) {
((RecordStreamlet) value).compile();
} else if (value instanceof Record) {
// Recursively compile nested scope.
((RecordModel) this.state.getItem(index)).compile((Record) value);
} else if (!value.isConstant()) {
// TODO: Bind dynamic item updater.
} else {
// TODO: Fold constant expressions.
}
}
public void transmute(Transmuter transmuter) {
int index = 0;
for (Item oldItem : this) {
final Item newItem = transmuteItem(oldItem, transmuter);
if (oldItem != newItem) {
setItem(index, newItem);
}
index += 1;
}
}
public void transmute() {
transmute(Transmuter.system());
}
public Item transmuteItem(Item item, Transmuter transmuter) {
if (item instanceof Field) {
return transmuteField((Field) item, transmuter);
} else {
return transmuteValue((Value) item, transmuter);
}
}
public Field transmuteField(Field field, Transmuter transmuter) {
final Value oldValue = field.value();
final Value newValue = transmuteValue(oldValue, transmuter);
if (oldValue != newValue) {
return field.updatedValue(newValue);
} else {
return field;
}
}
public Value transmuteValue(Value oldValue, Transmuter transmuter) {
if (oldValue instanceof RecordModel) {
Record newValue = this.transmuteModel((RecordModel) oldValue);
if (oldValue == newValue && transmuter != null) {
newValue = transmuter.transmute((RecordModel) oldValue);
}
return newValue;
} else {
return oldValue;
}
}
public Record transmuteModel(RecordModel model) {
final StreamletScope<? extends Value> scope = streamletScope();
if (scope instanceof RecordModel) {
return ((RecordModel) scope).transmuteModel(model);
} else {
return model;
}
}
public static RecordModel from(Record record) {
final RecordModel model = new RecordModel();
model.materialize(record);
model.compile(record);
return model;
}
public static RecordModel of() {
return new RecordModel();
}
public static RecordModel of(Object object) {
return from(Record.of(object));
}
public static RecordModel of(Object... objects) {
return from(Record.of(objects));
}
public static RecordModel globalScope() {
final RecordModel model = new RecordModel();
model.materializeField(Slot.of("math", MathModule.scope().branch()));
return model;
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/RecordOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import swim.streamlet.MapOutlet;
import swim.streamlet.Outlet;
import swim.streamlet.StreamletScope;
import swim.structure.Record;
import swim.structure.Value;
public interface RecordOutlet extends Outlet<Record>, MapOutlet<Value, Value, Record>, StreamletScope<Value> {
@Override
Outlet<Value> outlet(Value key);
@Override
Outlet<Value> outlet(String key);
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/RecordScope.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import swim.streamlet.StreamletScope;
import swim.structure.Record;
import swim.structure.Value;
public class RecordScope extends RecordModel {
protected StreamletScope<? extends Value> scope;
public RecordScope(StreamletScope<? extends Value> scope, Record state) {
super(state);
this.scope = scope;
}
public RecordScope(StreamletScope<? extends Value> scope) {
super();
this.scope = scope;
}
@Override
public final StreamletScope<? extends Value> streamletScope() {
return this.scope;
}
public static RecordScope from(Record record) {
final RecordScope scope = new RecordScope(globalScope());
scope.materialize(record);
scope.compile(record);
return scope;
}
public static RecordScope of() {
return new RecordScope(globalScope());
}
public static RecordScope of(Object object) {
return from(Record.of(object));
}
public static RecordScope of(Object... objects) {
return from(Record.of(objects));
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/RecordStreamlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.streamlet.Streamlet;
import swim.streamlet.StreamletScope;
import swim.structure.Record;
import swim.structure.Value;
public abstract class RecordStreamlet<I extends Value, O extends Value> extends Record implements Streamlet<I, O> {
@Override
public boolean isConstant() {
return false;
}
public void compile() {
AbstractRecordStreamlet.compileInlets(getClass(), this);
}
@SuppressWarnings("unchecked")
public void compileInlet(Inlet<I> inlet, String name) {
final StreamletScope<? extends O> scope = streamletScope();
if (scope != null) {
final Outlet<? extends O> input = scope.outlet(name);
if (input != null) {
// Assume Outlet<? super O> conforms to Outlet<I>.
inlet.bindInput((Outlet<I>) (Outlet<?>) input);
}
}
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/Transmuter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow;
import swim.structure.Record;
public abstract class Transmuter {
public abstract Record transmute(RecordModel model);
public static Transmuter system() {
return null; // TODO
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Dynamic structured data model.
*/
package swim.dataflow;
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/AndOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.streamlet.AbstractOutlet;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.streamlet.OutletInlet;
import swim.structure.Value;
public final class AndOutlet extends AbstractOutlet<Value> {
final Inlet<Value> operand1Inlet;
final Inlet<Value> operand2Inlet;
public AndOutlet() {
this.operand1Inlet = new OutletInlet<Value>(this);
this.operand2Inlet = new OutletInlet<Value>(this);
}
public Inlet<Value> operand1Inlet() {
return this.operand1Inlet;
}
public Inlet<Value> operand2Inlet() {
return this.operand2Inlet;
}
@Override
public Value get() {
final Outlet<? extends Value> operand1Input = this.operand1Inlet.input();
final Value argument1 = operand1Input != null ? operand1Input.get() : null;
if (argument1 != null) {
if (argument1.booleanValue(false)) {
final Outlet<? extends Value> operand2Input = this.operand2Inlet.input();
final Value argument2 = operand2Input != null ? operand2Input.get() : null;
if (argument2 != null) {
return argument2;
}
}
return argument1;
}
return Value.absent();
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/BinaryOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.streamlet.AbstractOutlet;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.streamlet.OutletInlet;
import swim.structure.Item;
import swim.structure.Value;
public abstract class BinaryOutlet extends AbstractOutlet<Value> {
final Inlet<Value> operand1Inlet;
final Inlet<Value> operand2Inlet;
public BinaryOutlet() {
this.operand1Inlet = new OutletInlet<Value>(this);
this.operand2Inlet = new OutletInlet<Value>(this);
}
public Inlet<Value> operand1Inlet() {
return this.operand1Inlet;
}
public Inlet<Value> operand2Inlet() {
return this.operand2Inlet;
}
@Override
public Value get() {
final Outlet<? extends Value> operand1Input = this.operand1Inlet.input();
final Outlet<? extends Value> operand2Input = this.operand2Inlet.input();
if (operand1Input != null && operand2Input != null) {
final Value argument1 = operand1Input.get();
final Value argument2 = operand2Input.get();
if (argument1 != null && argument2 != null) {
final Item result = evaluate(argument1, argument2);
return result.toValue();
}
}
return Value.absent();
}
protected abstract Item evaluate(Value argument1, Value argument2);
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/BitwiseAndOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class BitwiseAndOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.bitwiseAnd(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/BitwiseNotOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class BitwiseNotOutlet extends UnaryOutlet {
@Override
protected Item evaluate(Value argument) {
return argument.bitwiseNot();
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/BitwiseOrOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class BitwiseOrOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.bitwiseOr(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/BitwiseXorOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class BitwiseXorOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.bitwiseXor(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/ConditionalOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.streamlet.AbstractOutlet;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.streamlet.OutletInlet;
import swim.structure.Value;
public final class ConditionalOutlet extends AbstractOutlet<Value> {
final Inlet<Value> ifInlet;
final Inlet<Value> thenInlet;
final Inlet<Value> elseInlet;
public ConditionalOutlet() {
this.ifInlet = new OutletInlet<Value>(this);
this.thenInlet = new OutletInlet<Value>(this);
this.elseInlet = new OutletInlet<Value>(this);
}
public Inlet<Value> ifInlet() {
return this.ifInlet;
}
public Inlet<Value> thenInlet() {
return this.thenInlet;
}
public Inlet<Value> elseInlet() {
return this.elseInlet;
}
@Override
public Value get() {
final Outlet<? extends Value> ifInput = this.ifInlet.input();
if (ifInput != null) {
final Value ifTerm = ifInput.get();
if (ifTerm != null) {
if (ifTerm.booleanValue(false)) {
final Outlet<? extends Value> thenInput = this.thenInlet.input();
if (thenInput != null) {
final Value thenTerm = thenInput.get();
if (thenTerm != null) {
return thenTerm;
}
}
} else {
final Outlet<? extends Value> elseInput = this.elseInlet.input();
if (elseInput != null) {
final Value elseTerm = elseInput.get();
if (elseTerm != null) {
return elseTerm;
}
}
}
}
}
return Value.absent();
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/DivideOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class DivideOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.divide(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/EqOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class EqOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.eq(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/GeOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class GeOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.ge(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/GtOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class GtOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.gt(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/InvokeOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.streamlet.AbstractOutlet;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.streamlet.OutletInlet;
import swim.structure.Func;
import swim.structure.Interpreter;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
public final class InvokeOutlet extends AbstractOutlet<Value> {
final Record scope;
final Inlet<Value> funcInlet;
final Inlet<Value> argsInlet;
public InvokeOutlet(Record scope) {
this.scope = scope;
this.funcInlet = new OutletInlet<Value>(this);
this.argsInlet = new OutletInlet<Value>(this);
}
public Inlet<Value> funcInlet() {
return this.funcInlet;
}
public Inlet<Value> argsInlet() {
return this.argsInlet;
}
@Override
public Value get() {
final Outlet<? extends Value> funcInput = this.funcInlet.input();
final Outlet<? extends Value> argsInput = this.argsInlet.input();
if (funcInput != null && argsInput != null) {
final Value func = this.funcInlet.input().get();
if (func instanceof Func) {
final Value args = this.argsInlet.input().get();
if (args != null) {
final Interpreter interpreter = new Interpreter();
interpreter.pushScope(this.scope);
final Item result = ((Func) func).invoke(args, interpreter, null /* TODO: generalize InvokeOperator to InvokeContext */);
return result.toValue();
}
}
}
return Value.absent();
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/LeOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class LeOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.le(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/LtOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class LtOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.lt(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/MinusOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class MinusOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.minus(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/ModuloOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class ModuloOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.modulo(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/NeOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class NeOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.ne(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/NegativeOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class NegativeOutlet extends UnaryOutlet {
@Override
protected Item evaluate(Value argument) {
return argument.negative();
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/NotOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class NotOutlet extends UnaryOutlet {
@Override
protected Item evaluate(Value argument) {
return argument.not();
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/OrOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.streamlet.AbstractOutlet;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.streamlet.OutletInlet;
import swim.structure.Value;
public final class OrOutlet extends AbstractOutlet<Value> {
final Inlet<Value> operand1Inlet;
final Inlet<Value> operand2Inlet;
public OrOutlet() {
this.operand1Inlet = new OutletInlet<Value>(this);
this.operand2Inlet = new OutletInlet<Value>(this);
}
public Inlet<Value> operand1Inlet() {
return this.operand1Inlet;
}
public Inlet<Value> operand2Inlet() {
return this.operand2Inlet;
}
@Override
public Value get() {
final Outlet<? extends Value> operand1Input = this.operand1Inlet.input();
final Value argument1 = operand1Input != null ? operand1Input.get() : null;
if (argument1 != null && argument1.booleanValue(false)) {
return argument1;
}
final Outlet<? extends Value> operand2Input = this.operand2Inlet.input();
final Value argument2 = operand2Input != null ? operand2Input.get() : null;
if (argument2 != null) {
return argument2;
}
return Value.absent();
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/PlusOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class PlusOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.plus(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/PositiveOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class PositiveOutlet extends UnaryOutlet {
@Override
protected Item evaluate(Value argument) {
return argument.positive();
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/TimesOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.structure.Item;
import swim.structure.Value;
public final class TimesOutlet extends BinaryOutlet {
@Override
protected Item evaluate(Value argument1, Value argument2) {
return argument1.times(argument2);
}
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/operator/UnaryOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.operator;
import swim.streamlet.AbstractOutlet;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.streamlet.OutletInlet;
import swim.structure.Item;
import swim.structure.Value;
public abstract class UnaryOutlet extends AbstractOutlet<Value> {
final Inlet<Value> operandInlet;
public UnaryOutlet() {
this.operandInlet = new OutletInlet<Value>(this);
}
public Inlet<Value> operandInlet() {
return this.operandInlet;
}
@Override
public Value get() {
final Outlet<? extends Value> operandInput = this.operandInlet.input();
if (operandInput != null) {
final Value argument = operandInput.get();
if (argument != null) {
final Item result = evaluate(argument);
return result.toValue();
}
}
return Value.absent();
}
protected abstract Item evaluate(Value argument);
}
|
0 | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow | java-sources/ai/swim/swim-dataflow/3.10.0/swim/dataflow/selector/GetOutlet.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dataflow.selector;
import swim.streamlet.AbstractOutlet;
import swim.streamlet.Inlet;
import swim.streamlet.MapInlet;
import swim.streamlet.MapOutlet;
import swim.streamlet.Outlet;
import swim.streamlet.OutletInlet;
import swim.streamlet.OutletMapInlet;
import swim.structure.Value;
public final class GetOutlet extends AbstractOutlet<Value> {
final OutletInlet<Value> keyInlet;
final OutletMapInlet<Value, Value, Object> mapInlet;
public GetOutlet() {
this.keyInlet = new OutletInlet<Value>(this);
this.mapInlet = new OutletMapInlet<Value, Value, Object>(this);
}
public Inlet<Value> keyInlet() {
return this.keyInlet;
}
public MapInlet<Value, Value, Object> mapInlet() {
return this.mapInlet;
}
@Override
public Value get() {
final Outlet<? extends Value> keyInput = this.keyInlet.input();
if (keyInput != null) {
final Value key = keyInput.get();
if (key != null) {
final MapOutlet<Value, Value, ?> mapInput = this.mapInlet.input();
if (mapInput != null) {
final Value value = mapInput.get(key);
if (value != null) {
return value;
}
}
}
}
return Value.absent();
}
}
|
0 | java-sources/ai/swim/swim-decipher | java-sources/ai/swim/swim-decipher/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Format-detecting parsers and decoders.
*/
module swim.decipher {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.structure;
requires transitive swim.recon;
requires transitive swim.json;
requires transitive swim.xml;
requires transitive swim.protobuf;
exports swim.decipher;
}
|
0 | java-sources/ai/swim/swim-decipher/3.10.0/swim | java-sources/ai/swim/swim-decipher/3.10.0/swim/decipher/AnyDecoder.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.decipher;
import swim.codec.Binary;
import swim.codec.Decoder;
import swim.codec.DecoderException;
import swim.codec.InputBuffer;
import swim.codec.Parser;
import swim.codec.Utf8;
import swim.codec.UtfErrorMode;
final class AnyDecoder<I, V> extends Decoder<V> {
final DecipherDecoder<I, V> decipher;
final Parser<V> xmlParser;
final Parser<V> jsonParser;
final Parser<V> reconParser;
final Decoder<V> protobufDecoder;
final Decoder<V> textDecoder;
final Decoder<V> dataDecoder;
final int consumed;
AnyDecoder(DecipherDecoder<I, V> decipher, Parser<V> xmlParser, Parser<V> jsonParser,
Parser<V> reconParser, Decoder<V> protobufDecoder, Decoder<V> textDecoder,
Decoder<V> dataDecoder, int consumed) {
this.decipher = decipher;
this.xmlParser = xmlParser;
this.jsonParser = jsonParser;
this.reconParser = reconParser;
this.protobufDecoder = protobufDecoder;
this.textDecoder = textDecoder;
this.dataDecoder = dataDecoder;
this.consumed = consumed;
}
AnyDecoder(DecipherDecoder<I, V> decipher) {
this(decipher, null, null, null, null, null, null, 0);
}
@Override
public Decoder<V> feed(InputBuffer input) {
return decode(input, this.decipher, this.xmlParser, this.jsonParser,
this.reconParser, this.protobufDecoder, this.textDecoder,
this.dataDecoder, this.consumed);
}
static <I, V> Decoder<V> decode(InputBuffer input, DecipherDecoder<I, V> decipher,
Parser<V> xmlParser, Parser<V> jsonParser, Parser<V> reconParser,
Decoder<V> protobufDecoder, Decoder<V> textDecoder,
Decoder<V> dataDecoder, int consumed) {
final int inputStart = input.index();
final int inputLimit = input.limit();
final int inputRemaining = inputLimit - inputStart;
int inputConsumed = 0;
if (xmlParser == null || xmlParser.isCont()) {
if (xmlParser == null) {
xmlParser = Utf8.parseDecoded(decipher.xmlParser(), input, UtfErrorMode.fatalNonZero());
} else {
xmlParser = xmlParser.feed(input);
}
if (input.isDone() && xmlParser.isDone()) {
return done(xmlParser.bind());
}
inputConsumed = Math.max(inputConsumed, input.index() - inputStart);
}
if (jsonParser == null || jsonParser.isCont()) {
input = input.index(inputStart).limit(inputLimit);
if (jsonParser == null) {
jsonParser = Utf8.parseDecoded(decipher.jsonParser(), input, UtfErrorMode.fatalNonZero());
} else {
jsonParser = jsonParser.feed(input);
}
if (input.isDone() && jsonParser.isDone()) {
return done(jsonParser.bind());
}
inputConsumed = Math.max(inputConsumed, input.index() - inputStart);
}
if (reconParser == null || reconParser.isCont()) {
input = input.index(inputStart).limit(inputLimit);
if (reconParser == null) {
reconParser = Utf8.parseDecoded(decipher.reconParser(), input, UtfErrorMode.fatalNonZero());
} else {
reconParser = reconParser.feed(input);
}
if (input.isDone() && reconParser.isDone()) {
return done(reconParser.bind());
}
inputConsumed = Math.max(inputConsumed, input.index() - inputStart);
}
if (protobufDecoder == null || protobufDecoder.isCont()) {
input = input.index(inputStart).limit(inputLimit);
if (protobufDecoder == null) {
protobufDecoder = decipher.decodeProtobuf(input);
} else {
protobufDecoder = protobufDecoder.feed(input);
}
if (input.isDone() && protobufDecoder.isDone()) {
return protobufDecoder;
}
inputConsumed = Math.max(inputConsumed, input.index() - inputStart);
} else {
protobufDecoder = DETECTION_FAILED.asError();
}
if (consumed + inputConsumed < DETECTION_WINDOW) {
input = input.index(inputStart).limit(inputLimit);
if (textDecoder == null) {
textDecoder = Utf8.decodeOutput(decipher.textOutput(), input, UtfErrorMode.fatalNonZero());
} else {
textDecoder = textDecoder.feed(input);
}
if (input.isDone() && textDecoder.isDone()) {
return textDecoder;
}
inputConsumed = Math.max(inputConsumed, input.index() - inputStart);
} else {
textDecoder = DETECTION_FAILED.asError();
}
if (consumed + inputConsumed < DETECTION_WINDOW) {
input = input.index(inputStart).limit(inputLimit);
if (dataDecoder == null) {
dataDecoder = Binary.parseOutput(decipher.dataOutput(), input);
} else {
dataDecoder = dataDecoder.feed(input);
}
if (input.isDone() && dataDecoder.isDone()) {
return dataDecoder;
}
inputConsumed = Math.max(inputConsumed, input.index() - inputStart);
} else {
dataDecoder = DETECTION_FAILED.asError();
}
if (jsonParser.isError() && reconParser.isError() && protobufDecoder.isError()
&& textDecoder.isError() && dataDecoder.isError()) {
return xmlParser;
} else if (xmlParser.isError() && reconParser.isError() && protobufDecoder.isError()
&& textDecoder.isError() && dataDecoder.isError()) {
return jsonParser;
} else if (xmlParser.isError() && jsonParser.isError() && protobufDecoder.isError()
&& textDecoder.isError() && dataDecoder.isError()) {
return reconParser;
} else if (xmlParser.isError() && jsonParser.isError() && reconParser.isError()
&& textDecoder.isError() && dataDecoder.isError()) {
return protobufDecoder;
} else if (xmlParser.isError() && jsonParser.isError() && reconParser.isError()
&& protobufDecoder.isError() && dataDecoder.isError()) {
return textDecoder;
} else if (xmlParser.isError() && jsonParser.isError() && reconParser.isError()
&& protobufDecoder.isError() && textDecoder.isError()) {
return dataDecoder;
}
if (input.isDone()) {
return error(new DecoderException("unexpected end of input"));
} else if (input.isError()) {
return error(input.trap());
}
consumed += inputConsumed;
return new AnyDecoder<I, V>(decipher, xmlParser, jsonParser, reconParser,
protobufDecoder, textDecoder, dataDecoder, consumed);
}
static <I, V> Decoder<V> decode(InputBuffer input, DecipherDecoder<I, V> decipher) {
return decode(input, decipher, null, null, null, null, null, null, 0);
}
static final int DETECTION_WINDOW;
static final Decoder<Object> DETECTION_FAILED;
static {
int detectionWindow;
try {
detectionWindow = Integer.parseInt(System.getProperty("swim.any.decoder.detection.window"));
} catch (NumberFormatException e) {
detectionWindow = 128;
}
DETECTION_WINDOW = detectionWindow;
DETECTION_FAILED = error(new DecoderException("detection failed"));
}
}
|
0 | java-sources/ai/swim/swim-decipher/3.10.0/swim | java-sources/ai/swim/swim-decipher/3.10.0/swim/decipher/AnyParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.decipher;
import swim.codec.Input;
import swim.codec.Parser;
final class AnyParser<I, V> extends Parser<V> {
final DecipherParser<I, V> decipher;
final Parser<V> xmlParser;
final Parser<V> jsonParser;
final Parser<V> reconParser;
AnyParser(DecipherParser<I, V> decipher, Parser<V> xmlParser,
Parser<V> jsonParser, Parser<V> reconParser) {
this.decipher = decipher;
this.xmlParser = xmlParser;
this.jsonParser = jsonParser;
this.reconParser = reconParser;
}
AnyParser(DecipherParser<I, V> decipher) {
this(decipher, null, null, null);
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.decipher, this.xmlParser, this.jsonParser, this.reconParser);
}
static <I, V> Parser<V> parse(Input input, DecipherParser<I, V> decipher, Parser<V> xmlParser,
Parser<V> jsonParser, Parser<V> reconParser) {
if (xmlParser == null || xmlParser.isCont()) {
final Input xmlInput = input.clone();
if (xmlParser == null) {
xmlParser = decipher.parseXml(xmlInput);
} else {
xmlParser = xmlParser.feed(xmlInput);
}
if (xmlInput.isDone() && xmlParser.isDone()) {
return xmlParser;
}
}
if (jsonParser == null || jsonParser.isCont()) {
final Input jsonInput = input.clone();
if (jsonParser == null) {
jsonParser = decipher.parseJson(jsonInput);
} else {
jsonParser = jsonParser.feed(jsonInput);
}
if (jsonInput.isDone() && jsonParser.isDone()) {
return jsonParser;
}
}
if (reconParser == null || reconParser.isCont()) {
final Input reconInput = input.clone();
if (reconParser == null) {
reconParser = decipher.parseRecon(reconInput);
} else {
reconParser = reconParser.feed(reconInput);
}
if (reconInput.isDone() && reconParser.isDone()) {
return reconParser;
}
}
if (jsonParser.isError() && reconParser.isError()) {
return xmlParser;
} else if (xmlParser.isError() && reconParser.isError()) {
return jsonParser;
} else if (xmlParser.isError() && jsonParser.isError()) {
return reconParser;
}
if (input.isError()) {
return error(input.trap());
}
return new AnyParser<I, V>(decipher, xmlParser, jsonParser, reconParser);
}
static <I, V> Parser<V> parse(Input input, DecipherParser<I, V> decipher) {
return parse(input, decipher, null, null, null);
}
}
|
0 | java-sources/ai/swim/swim-decipher/3.10.0/swim | java-sources/ai/swim/swim-decipher/3.10.0/swim/decipher/Decipher.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.decipher;
import swim.codec.Decoder;
import swim.codec.Parser;
import swim.structure.Item;
import swim.structure.Value;
/**
* Factory for constructing format-detecting parsers and decoders.
*/
public final class Decipher {
private Decipher() {
// stub
}
static boolean isSpace(int c) {
return c == 0x20 || c == 0x9;
}
static boolean isNewline(int c) {
return c == 0xa || c == 0xd;
}
static boolean isWhitespace(int c) {
return isSpace(c) || isNewline(c);
}
private static DecipherDecoder<Item, Value> structureDecoder;
private static DecipherParser<Item, Value> structureParser;
public static DecipherDecoder<Item, Value> structureDecoder() {
if (structureDecoder == null) {
structureDecoder = new DecipherStructureDecoder();
}
return structureDecoder;
}
public static DecipherParser<Item, Value> structureParser() {
if (structureParser == null) {
structureParser = new DecipherStructureParser();
}
return structureParser;
}
public static Value parse(String any) {
return structureParser().parseAnyString(any);
}
public static Parser<Value> parser() {
return structureParser().anyParser();
}
public static Decoder<Value> decoder() {
return structureDecoder().anyDecoder();
}
}
|
0 | java-sources/ai/swim/swim-decipher/3.10.0/swim | java-sources/ai/swim/swim-decipher/3.10.0/swim/decipher/DecipherDecoder.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.decipher;
import swim.codec.Decoder;
import swim.codec.Input;
import swim.codec.InputBuffer;
import swim.codec.Output;
import swim.codec.Parser;
/**
* Factory for constructing Format-detecting decoders.
*/
public abstract class DecipherDecoder<I, V> {
public abstract Parser<V> xmlParser();
public abstract Parser<V> parseXml(Input input);
public abstract Parser<V> jsonParser();
public abstract Parser<V> parseJson(Input input);
public abstract Parser<V> reconParser();
public abstract Parser<V> parseRecon(Input input);
public abstract Decoder<V> protobufDecoder();
public abstract Decoder<V> decodeProtobuf(InputBuffer input);
public abstract Output<V> textOutput();
public abstract Output<V> dataOutput();
public Decoder<V> decodeAny(InputBuffer input) {
return AnyDecoder.decode(input, this);
}
public Decoder<V> anyDecoder() {
return new AnyDecoder<I, V>(this);
}
}
|
0 | java-sources/ai/swim/swim-decipher/3.10.0/swim | java-sources/ai/swim/swim-decipher/3.10.0/swim/decipher/DecipherParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.decipher;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Parser;
import swim.codec.Unicode;
/**
* Factory for constructing Format-detecting parsers.
*/
public abstract class DecipherParser<I, V> {
public abstract Parser<V> parseXml(Input input);
public abstract Parser<V> parseJson(Input input);
public abstract Parser<V> parseRecon(Input input);
public Parser<V> parseAny(Input input) {
return AnyParser.parse(input, this);
}
public Parser<V> anyParser() {
return new AnyParser<I, V>(this);
}
public V parseAnyString(String string) {
Input input = Unicode.stringInput(string);
while (input.isCont() && Decipher.isWhitespace(input.head())) {
input = input.step();
}
Parser<V> parser = parseAny(input);
if (parser.isDone()) {
while (input.isCont() && Decipher.isWhitespace(input.head())) {
input = input.step();
}
}
if (input.isCont() && !parser.isError()) {
parser = Parser.error(Diagnostic.unexpected(input));
} else if (input.isError()) {
parser = Parser.error(input.trap());
}
return parser.bind();
}
}
|
0 | java-sources/ai/swim/swim-decipher/3.10.0/swim | java-sources/ai/swim/swim-decipher/3.10.0/swim/decipher/DecipherStructureDecoder.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.decipher;
import swim.codec.Decoder;
import swim.codec.Input;
import swim.codec.InputBuffer;
import swim.codec.Output;
import swim.codec.Parser;
import swim.json.Json;
import swim.protobuf.Protobuf;
import swim.recon.Recon;
import swim.structure.Data;
import swim.structure.Item;
import swim.structure.Text;
import swim.structure.Value;
import swim.xml.Xml;
public class DecipherStructureDecoder extends DecipherDecoder<Item, Value> {
@Override
public Parser<Value> xmlParser() {
return Xml.structureParser().documentParser();
}
@Override
public Parser<Value> parseXml(Input input) {
return Xml.structureParser().parseDocument(input);
}
@Override
public Parser<Value> jsonParser() {
return Json.structureParser().objectParser();
}
@Override
public Parser<Value> parseJson(Input input) {
return Json.structureParser().parseObject(input);
}
@Override
public Parser<Value> reconParser() {
return Recon.structureParser().blockParser();
}
@Override
public Parser<Value> parseRecon(Input input) {
return Recon.structureParser().parseBlock(input);
}
@Override
public Decoder<Value> protobufDecoder() {
return Protobuf.structureDecoder().payloadDecoder();
}
@Override
public Decoder<Value> decodeProtobuf(InputBuffer input) {
return Protobuf.structureDecoder().decodePayload(input);
}
@SuppressWarnings("unchecked")
@Override
public Output<Value> textOutput() {
return (Output<Value>) (Output<?>) Text.output();
}
@SuppressWarnings("unchecked")
@Override
public Output<Value> dataOutput() {
return (Output<Value>) (Output<?>) Data.output();
}
}
|
0 | java-sources/ai/swim/swim-decipher/3.10.0/swim | java-sources/ai/swim/swim-decipher/3.10.0/swim/decipher/DecipherStructureParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.decipher;
import swim.codec.Input;
import swim.codec.Parser;
import swim.json.Json;
import swim.recon.Recon;
import swim.structure.Item;
import swim.structure.Value;
import swim.xml.Xml;
public class DecipherStructureParser extends DecipherParser<Item, Value> {
@Override
public Parser<Value> parseXml(Input input) {
return Xml.structureParser().parseDocument(input);
}
@Override
public Parser<Value> parseJson(Input input) {
return Json.structureParser().parseObject(input);
}
@Override
public Parser<Value> parseRecon(Input input) {
return Recon.structureParser().parseBlock(input);
}
}
|
0 | java-sources/ai/swim/swim-decipher/3.10.0/swim | java-sources/ai/swim/swim-decipher/3.10.0/swim/decipher/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Format-detecting parsers and decoders.
*/
package swim.decipher;
|
0 | java-sources/ai/swim/swim-deflate | java-sources/ai/swim/swim-deflate/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* DEFLATE compression codec.
*/
module swim.deflate {
requires swim.util;
requires transitive swim.codec;
exports swim.deflate;
}
|
0 | java-sources/ai/swim/swim-deflate/3.10.0/swim | java-sources/ai/swim/swim-deflate/3.10.0/swim/deflate/Adler32.java | // Based on zlib-1.2.8
// Copyright (c) 1995-2013 Jean-loup Gailly and Mark Adler
// Copyright (c) 2016-2018 Swim.it inc.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
package swim.deflate;
final class Adler32 {
private Adler32() {
// stub
}
// largest prime smaller than 65536
static final int BASE = 65521;
// largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
static final int NMAX = 5552;
static int adler32(int adler, byte[] buffer, int offset, int length) {
int sum2;
int n;
// split Adler-32 into component sums
sum2 = (adler >>> 16) & 0xFFFF;
adler &= 0xFFFF;
// in case user likes doing a byte at a time, keep it fast
if (length == 1) {
adler += buffer[0];
if (adler >= BASE) {
adler -= BASE;
}
sum2 += adler;
if (sum2 >= BASE) {
sum2 -= BASE;
}
return adler | (sum2 << 16);
}
// initial Adler-32 value (deferred check for length == 1 speed)
if (buffer == null) {
return 1;
}
// in case short lengths are provided, keep it somewhat fast
if (length < 16) {
while (length-- != 0) {
adler += buffer[offset++]; sum2 += adler;
}
if (adler >= BASE) {
adler -= BASE;
}
sum2 %= BASE; // only added so many BASE's
return adler | (sum2 << 16);
}
// do length NMAX blocks -- requires just one modulo operation
while (length >= NMAX) {
length -= NMAX;
n = NMAX / 16; // NMAX is divisible by 16
do {
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
} while (--n != 0);
adler %= BASE;
sum2 %= BASE;
}
// do remaining bytes (less than NMAX, still just one modulo)
if (length != 0) { // avoid modulos if none remaining
while (length >= 16) {
length -= 16;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
adler += buffer[offset++]; sum2 += adler;
}
while (length-- != 0) {
adler += buffer[offset++]; sum2 += adler;
}
adler %= BASE;
sum2 %= BASE;
}
// return recombined sums
return adler | (sum2 << 16);
}
}
|
0 | java-sources/ai/swim/swim-deflate/3.10.0/swim | java-sources/ai/swim/swim-deflate/3.10.0/swim/deflate/CRC32.java | // Based on zlib-1.2.8
// Copyright (c) 1995-2013 Jean-loup Gailly and Mark Adler
// Copyright (c) 2016-2018 Swim.it inc.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
package swim.deflate;
final class CRC32 {
private CRC32() {
// stub
}
static final int[] CRC_TABLE = makeCRCTable();
// Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
static int[] makeCRCTable() {
final int[] crcTable = new int[256];
for (int n = 0; n < 256; n++) { // generate a crc for every 8-bit value
int c = n;
for (int k = 0; k < 8; k++) {
c = (c & 1) != 0 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1;
}
crcTable[n] = c;
}
return crcTable;
}
static int crc32(int crc, byte[] buffer, int offset, int length) {
if (buffer == null) {
return 0;
}
crc = ~crc;
while (length >= 8) {
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
length -= 8;
}
if (length != 0) {
do {
crc = CRC_TABLE[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >>> 8);
} while (--length != 0);
}
return ~crc;
}
}
|
0 | java-sources/ai/swim/swim-deflate/3.10.0/swim | java-sources/ai/swim/swim-deflate/3.10.0/swim/deflate/Deflate.java | // Based on zlib-1.2.8
// Copyright (c) 1995-2013 Jean-loup Gailly and Mark Adler
// Copyright (c) 2016-2018 Swim.it inc.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
package swim.deflate;
import swim.codec.Binary;
import swim.codec.Encoder;
import swim.codec.EncoderException;
import swim.codec.OutputBuffer;
import static swim.deflate.Adler32.adler32;
import static swim.deflate.CRC32.crc32;
@SuppressWarnings("checkstyle:all")
public class Deflate<O> extends Encoder<Encoder<?, O>, O> implements Cloneable {
// deflated input source
public Encoder<?, O> input;
// flush mode for pull operations
protected int flush;
// total number of input bytes read so far
public long total_in;
// output buffer
public byte[] next_out;
// next output byte should be put there
public int next_out_index;
// remaining free space at next_out_index
public int avail_out;
// total number of bytes output so far
public long total_out;
// best guess about the data type: binary or text
int data_type;
// adler32 value of the uncompressed data
int adler;
// as the name implies
int status;
// output still pending
byte[] pending_buf;
// size of pending_buf
//int pending_buf_size;
// next pending byte to output to the stream
int pending_out;
// number of bytes in the pending buffer
int pending;
// bit 0 true for zlib, bit 1 true for gzip
int wrap;
// gzip header information to write
GzHeader gzhead;
// where in extra, name, or comment
int gzindex;
// can only be DEFLATED
//byte method;
// value of flush param for previous deflate call
int last_flush;
// LZ77 window size (32K by default)
int w_size;
// log2(w_size) (8..16)
int w_bits;
// w_size - 1
int w_mask;
// Sliding window. Input bytes are read into the second half of the window,
// and move to the first half later to keep a dictionary of at least wSize
// bytes. With this organization, matches are limited to a distance of
// wSize-MAX_MATCH bytes, but this ensures that IO is always
// performed with a length multiple of the block size. Also, it limits
// the window size to 64K, which is quite useful on MSDOS.
// To do: use the user input buffer as sliding window.
byte[] window;
// Input writes directly to sliding window through this buffer.
OutputBuffer<?> window_buffer;
// Actual size of window: 2*wSize, except when the user input buffer
// is directly used as sliding window.
int window_size;
// Link to older string with same hash index. To limit the size of this
// array to 64K, this link is maintained only for the last 32K strings.
// An index in this array is thus a window index modulo 32K.
short[] prev;
// Heads of the hash chains or NIL.
short[] head;
// hash index of string to be inserted
int ins_h;
// number of elements in hash table
int hash_size;
// log2(hash_size)
int hash_bits;
// hash_size-1
int hash_mask;
// Number of bits by which ins_h must be shifted at each input
// step. It must be such that after MIN_MATCH steps, the oldest
// byte no longer takes part in the hash key, that is:
// hash_shift * MIN_MATCH >= hash_bits
int hash_shift;
// Window position at the beginning of the current output block. Gets
// negative when the window is moved backwards.
int block_start;
// length of best match
int match_length;
// previous match
int prev_match;
// set if previous match exists
int match_available;
// start of string to insert
int strstart;
// start of matching string
int match_start;
// number of valid bytes ahead in window
int lookahead;
// Length of the best match at previous step. Matches not greater than this
// are discarded. This is used in the lazy match evaluation.
int prev_length;
// To speed up deflation, hash chains are never searched beyond this length.
// A higher limit improves compression ratio but degrades the speed.
int max_chain_length;
// Attempt to find a better match only when the current match is strictly
// smaller than this value. This mechanism is used only for compression
// levels >= 4.
int max_lazy_match;
// compression level (1..9)
int level;
// favor or force Huffman coding
int strategy;
// Use a faster search when the previous match is longer than this
int good_match;
// Stop searching when current match exceeds this
int nice_match;
// literal and length tree
short[] dyn_ltree = new short[HEAP_SIZE * 2];
// distance tree
short[] dyn_dtree = new short[(2 * D_CODES + 1) * 2];
// Huffman tree for bit lengths
short[] bl_tree = new short[(2 * BL_CODES + 1) * 2];
// desc for literal tree;
Tree l_desc;
// desc for distance tree
Tree d_desc;
// desc for bit length tree
Tree bl_desc;
// number of codes at each bit length for an optimal tree
short[] bl_count = new short[MAX_BITS + 1];
// next code value for each bit length within gen_codes()
short[] next_code = new short[MAX_BITS + 1];
// heap used to build the Huffman trees
int[] heap = new int[2 * L_CODES + 1];
// number of elements in the heap
int heap_len;
// element of largest frequency
int heap_max;
// Depth of each subtree used as tie breaker for trees of equal frequency
byte[] depth = new byte[2 * L_CODES + 1];
// index for literals or lengths */
byte[] l_buf;
// Size of match buffer for literals/lengths. There are 4 reasons for
// limiting lit_bufsize to 64K:
// - frequencies can be kept in 16 bit counters
// - if compression is not successful for the first block, all input
// data is still in the window so we can still emit a stored block even
// when input comes from standard input. (This can also be done for
// all blocks if lit_bufsize is not greater than 32K.)
// - if compression is not successful for a file smaller than 64K, we can
// even emit a stored file instead of a stored block (saving 5 bytes).
// This is applicable only for zip (not gzip or zlib).
// - creating new Huffman trees less frequently may not provide fast
// adaptation to changes in the input data statistics. (Take for
// example a binary file with poorly compressible code followed by
// a highly compressible string table.) Smaller buffer sizes give
// fast adaptation but have of course the overhead of transmitting
// trees more frequently.
// - I can't count above 4
int lit_bufsize;
// running index in l_buf
int last_lit;
// Buffer for distances. To simplify the code, d_buf and l_buf have
// the same number of elements. To use different lengths, an extra flag
// array would be necessary.
int d_buf;
// bit length of current block with optimal trees
int opt_len;
// bit length of current block with static trees
int static_len;
// number of string matches in current block
int matches;
// bytes at end of window left to insert
int insert;
// Output buffer. bits are inserted starting at the bottom (least
// significant bits).
short bi_buf;
// Number of valid bits in bi_buf. All bits above the last valid bit
// are always zero.
int bi_valid;
public Deflate(Encoder<?, O> input, int wrap, int level, int windowBits, int memLevel, int strategy) {
this.input = input;
l_desc = new Tree();
d_desc = new Tree();
bl_desc = new Tree();
deflateInit(wrap, level, windowBits, memLevel, strategy);
}
public Deflate(Encoder<?, O> input, int wrap, int level, int windowBits, int memlevel) {
this(input, wrap, level, windowBits, memlevel, Z_DEFAULT_STRATEGY);
}
public Deflate(Encoder<?, O> input, int wrap, int level, int windowBits) {
this(input, wrap, level, windowBits, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
public Deflate(Encoder<?, O> input, int wrap, int level) {
this(input, wrap, level, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
public Deflate(Encoder<?, O> input, int wrap) {
this(input, wrap, Z_DEFAULT_COMPRESSION, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
public Deflate(Encoder<?, O> input) {
this(input, Z_NO_WRAP, Z_DEFAULT_COMPRESSION, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
public Deflate(int wrap, int level, int windowBits, int memLevel, int strategy) {
this(null, wrap, level, windowBits, memLevel, strategy);
}
public Deflate(int wrap, int level, int windowBits, int memlevel) {
this(null, wrap, level, windowBits, memlevel, Z_DEFAULT_STRATEGY);
}
public Deflate(int wrap, int level, int windowBits) {
this(null, wrap, level, windowBits, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
public Deflate(int wrap, int level) {
this(null, wrap, level, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
public Deflate(int wrap) {
this(null, wrap, Z_DEFAULT_COMPRESSION, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
public Deflate() {
this(null, Z_NO_WRAP, Z_DEFAULT_COMPRESSION, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
Deflate(Deflate<O> from) {
input = from.input;
flush = from.flush;
total_in = from.total_in;
next_out = from.next_out;
next_out_index = from.next_out_index;
avail_out = from.avail_out;
total_out = from.total_out;
data_type = from.data_type;
adler = from.adler;
status = from.status;
pending_buf = pending_buf;
//pending_buf_size = from.pending_buf_size;
pending_out = from.pending_out;
pending = from.pending;
wrap = from.wrap;
if (gzhead != null) {
gzhead = from.gzhead.clone();
}
gzindex = from.gzindex;
//method = from.method;
last_flush = from.last_flush;
w_size = from.w_size;
w_bits = from.w_bits;
w_mask = from.w_mask;
if (from.window != null) {
window = new byte[from.window.length];
System.arraycopy(from.window, 0, window, 0, window.length);
window_buffer = Binary.outputBuffer(window);
}
window_size = from.window_size;
if (from.prev != null) {
prev = new short[from.prev.length];
System.arraycopy(from.prev, 0, prev, 0, prev.length);
}
if (from.head != null) {
head = new short[from.head.length];
System.arraycopy(from.head, 0, head, 0, head.length);
}
ins_h = from.ins_h;
hash_size = from.hash_size;
hash_bits = from.hash_bits;
hash_mask = from.hash_mask;
hash_shift = from.hash_shift;
block_start = from.block_start;
match_length = from.match_length;
prev_match = from.prev_match;
match_available = from.match_available;
strstart = from.strstart;
match_start = from.match_start;
lookahead = from.lookahead;
prev_length = from.prev_length;
max_chain_length = from.max_chain_length;
max_lazy_match = from.max_lazy_match;
level = from.level;
strategy = from.strategy;
good_match = from.good_match;
nice_match = from.nice_match;
System.arraycopy(from.dyn_ltree, 0, dyn_ltree, 0, dyn_ltree.length);
System.arraycopy(from.dyn_dtree, 0, dyn_dtree, 0, dyn_dtree.length);
System.arraycopy(from.bl_tree, 0, bl_tree, 0, bl_tree.length);
l_desc = from.l_desc.clone();
d_desc = from.d_desc.clone();
bl_desc = from.bl_desc.clone();
System.arraycopy(from.bl_count, 0, bl_count, 0, bl_count.length);
System.arraycopy(from.next_code, 0, next_code, 0, next_code.length);
System.arraycopy(from.heap, 0, heap, 0, heap.length);
heap_len = from.heap_len;
heap_max = from.heap_max;
System.arraycopy(from.depth, 0, depth, 0, depth.length);
if (from.l_buf != null) {
l_buf = new byte[from.l_buf.length];
System.arraycopy(from.l_buf, 0, l_buf, 0, l_buf.length);
}
lit_bufsize = from.lit_bufsize;
last_lit = from.last_lit;
d_buf = from.d_buf;
opt_len = from.opt_len;
static_len = from.static_len;
matches = from.matches;
insert = from.insert;
bi_buf = from.bi_buf;
bi_valid = from.bi_valid;
}
protected void deflateInit(int wrap, int level, int windowBits, int memLevel, int strategy) {
if (level == Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (flush < 0 || flush > Z_BLOCK ||
memLevel < 1 || memLevel > MAX_MEM_LEVEL ||
windowBits < 8 || windowBits > 15 ||
level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
throw new DeflateException(Z_STREAM_ERROR);
}
if (windowBits == 8) {
windowBits = 9; // until 256-byte window bug fixed
}
this.wrap = wrap;
gzhead = null;
w_bits = windowBits;
w_size = 1 << w_bits;
w_mask = w_size - 1;
hash_bits = memLevel + 7;
hash_size = 1 << hash_bits;
hash_mask = hash_size - 1;
hash_shift = (hash_bits + MIN_MATCH - 1) / MIN_MATCH;
window = new byte[w_size * 2];
window_buffer = Binary.outputBuffer(window);
prev = new short[w_size];
head = new short[hash_size];
lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
// We overlay pending_buf and d_buf+l_buf. This works since the average
// output size for (length,distance) codes is <= 24 bits.
pending_buf = new byte[lit_bufsize * 3];
//pending_buf_size = lit_bufsize * 3;
d_buf = lit_bufsize;
l_buf = new byte[lit_bufsize];
this.level = level;
this.strategy = strategy;
deflateReset();
}
public void deflateResetKeep() {
total_in = total_out = 0L;
data_type = Z_UNKNOWN;
pending = 0;
pending_out = 0;
if (wrap < 0) {
wrap = -wrap; // was made negative by deflate(..., Z_FINISH)
}
status = wrap != 0 ? INIT_STATE : BUSY_STATE;
if (wrap == 1) {
adler = adler32(0, null, 0, 0);
} else if (wrap == 2) {
adler = crc32(0, null, 0, 0);
} else {
adler = 0;
}
last_flush = Z_NO_FLUSH;
tr_init();
}
public void deflateReset() {
deflateResetKeep();
lm_init();
}
public void deflateParams(int level, int strategy) {
if (level == Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
throw new DeflateException(Z_STREAM_ERROR);
}
if (strategy != this.strategy &&
configuration_table[this.level].func != configuration_table[level].func &&
total_in != 0) {
// Flush the last buffer:
try {
deflate(Z_PARTIAL_FLUSH);
} catch (DeflateException e) {
if (e.code() != Z_BUF_ERROR || pending != 0) {
throw e;
}
}
}
if (this.level != level) {
this.level = level;
max_lazy_match = configuration_table[level].max_lazy;
good_match = configuration_table[level].good_length;
nice_match = configuration_table[level].nice_length;
max_chain_length = configuration_table[level].max_chain;
}
this.strategy = strategy;
}
@Override
public Deflate<O> clone() {
return new Deflate<O>(this);
}
// Set the current flush mode.
public Deflate<O> flush(int flush) {
if (flush < 0 || flush > Z_BLOCK) {
throw new DeflateException(Z_STREAM_ERROR);
}
this.flush = flush;
return this;
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
protected void flush_pending() {
tr_flush_bits();
int len = pending;
if (len > avail_out) {
len = avail_out;
}
if (len == 0) {
return;
}
System.arraycopy(pending_buf, pending_out, next_out, next_out_index, len);
next_out_index += len;
pending_out += len;
total_out += len;
avail_out -= len;
pending -= len;
if (pending == 0) {
pending_out = 0;
}
}
@Override
public Deflate<O> feed(Encoder<?, O> input) {
this.input = input;
return this;
}
@Override
public Encoder<Encoder<?, O>, O> pull(OutputBuffer<?> output) {
next_out = output.array();
next_out_index = output.arrayOffset() + output.index();
avail_out = output.remaining();
try {
final boolean needsMore = deflate(flush);
output.index(next_out_index - output.arrayOffset());
if (input.isDone() && !needsMore) {
return input.asDone();
} else if (input.isError()) {
return input.asError();
} else if (output.isDone()) {
return error(new EncoderException("truncated"));
} else if (output.isError()) {
return error(output.trap());
} else {
return this;
}
} catch (DeflateException cause) {
return error(cause);
} finally {
next_out = null;
next_out_index = 0;
avail_out = 0;
}
}
public boolean deflate(int flush) {
int old_flush; // value of flush param for previous deflate call
if (flush > Z_BLOCK || flush < 0) {
throw new DeflateException(Z_STREAM_ERROR);
}
if (next_out == null ||
//(next_in == null && avail_in != 0) ||
(status == FINISH_STATE && flush != Z_FINISH)) {
throw new DeflateException(Z_STREAM_ERROR);
}
if (avail_out == 0) {
throw new DeflateException(Z_BUF_ERROR);
}
old_flush = last_flush;
last_flush = flush;
// Write the header
if (status == INIT_STATE) {
if (wrap == 2) {
adler = crc32(0, null, 0, 0);
put_byte(31);
put_byte(139);
put_byte(8);
if (gzhead == null) {
put_byte(0);
put_byte(0);
put_byte(0);
put_byte(0);
put_byte(0);
put_byte(level == 9 ? 2 : strategy >= Z_HUFFMAN_ONLY || level < 2 ? 4 : 0);
put_byte(OS_CODE);
status = BUSY_STATE;
} else {
put_byte((gzhead.text ? 1 : 0) +
(gzhead.hcrc ? 2 : 0) +
(gzhead.extra == null ? 0 : 4) +
(gzhead.name == null ? 0 : 8) +
(gzhead.comment == null ? 0 : 16));
put_byte(gzhead.time);
put_byte(gzhead.time >> 8);
put_byte(gzhead.time >> 16);
put_byte(gzhead.time >> 24);
put_byte(level == 9 ? 2 : strategy >= Z_HUFFMAN_ONLY || level < 2 ? 4 : 0);
put_byte(gzhead.os);
if (gzhead.extra != null) {
put_byte(gzhead.extra_len);
put_byte(gzhead.extra_len >> 8);
}
if (gzhead.hcrc) {
adler = crc32(adler, pending_buf, pending_out, pending);
}
gzindex = 0;
status = EXTRA_STATE;
}
} else {
int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
int level_flags;
if (strategy >= Z_HUFFMAN_ONLY || level < 2) {
level_flags = 0;
} else if (level < 6) {
level_flags = 1;
} else if (level == 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= level_flags << 6;
if (strstart != 0) {
header |= PRESET_DICT;
}
header += 31 - (header % 31);
status = BUSY_STATE;
putShortMSB(header);
// Save the adler32 of the preset dictionary:
if (strstart != 0) {
putShortMSB(adler >>> 16);
putShortMSB(adler & 0xFFFF);
}
adler = adler32(0, null, 0, 0);
}
}
if (status == EXTRA_STATE) {
if (gzhead.extra != null) {
int beg = pending; // start of bytes to update crc
while (gzindex < (gzhead.extra_len & 0xFFFF)) {
if (pending == pending_buf.length) {
if (gzhead.hcrc && pending > beg) {
adler = crc32(adler, pending_buf, beg, pending - beg);
}
flush_pending();
beg = pending;
if (pending == pending_buf.length) {
break;
}
}
put_byte(gzhead.extra[gzindex]);
gzindex++;
}
if (gzhead.hcrc && pending > beg) {
adler = crc32(adler, pending_buf, beg, pending - beg);
}
if (gzindex == gzhead.extra_len) {
gzindex = 0;
status = NAME_STATE;
}
} else {
status = NAME_STATE;
}
}
if (status == NAME_STATE) {
if (gzhead.name != null) {
int beg = pending; // start of bytes to update crc
int val;
do {
if (pending == pending_buf.length) {
if (gzhead.hcrc && pending > beg) {
adler = crc32(adler, pending_buf, beg, pending - beg);
}
flush_pending();
beg = pending;
if (pending == pending_buf.length) {
val = 1;
break;
}
}
val = gzhead.name[gzindex++];
put_byte(val);
} while (val != 0);
if (gzhead.hcrc && pending > beg) {
adler = crc32(adler, pending_buf, beg, pending - beg);
}
if (val == 0) {
gzindex = 0;
status = COMMENT_STATE;
}
} else {
status = COMMENT_STATE;
}
}
if (status == COMMENT_STATE) {
if (gzhead.comment != null) {
int beg = pending; // start of bytes to update crc
int val;
do {
if (pending == pending_buf.length) {
if (gzhead.hcrc && pending > beg) {
adler = crc32(adler, pending_buf, beg, pending - beg);
}
flush_pending();
beg = pending;
if (pending == pending_buf.length) {
val = 1;
break;
}
}
val = gzhead.comment[gzindex++];
put_byte(val);
} while (val != 0);
if (gzhead.hcrc && pending > beg) {
adler = crc32(adler, pending_buf, beg, pending - beg);
}
if (val == 0) {
status = HCRC_STATE;
}
} else {
status = HCRC_STATE;
}
}
if (status == HCRC_STATE) {
if (gzhead.hcrc) {
if (pending + 2 > pending_buf.length) {
flush_pending();
}
if (pending + 2 <= pending_buf.length) {
put_byte(adler);
put_byte(adler >>> 8);
adler = crc32(0, null, 0, 0);
status = BUSY_STATE;
}
} else {
status = BUSY_STATE;
}
}
// Flush as much pending output as possible
if (pending != 0) {
flush_pending();
if (avail_out == 0) {
// Since avail_out is 0, deflate will be called again with
// more output space, but possibly with both pending and
// avail_in equal to zero. There won't be anything to do,
// but this is not an error situation so make sure we
// return OK instead of BUF_ERROR at next call of deflate:
last_flush = -1;
return true;
}
// Make sure there is something to do and avoid duplicate consecutive
// flushes. For repeated and useless calls with Z_FINISH, we keep
// returning Z_STREAM_END instead of Z_BUF_ERROR.
} else if (input.isDone() && flush <= old_flush && flush != Z_FINISH) {
throw new DeflateException(Z_BUF_ERROR);
}
// User must not provide more input after the first FINISH:
if (status == FINISH_STATE && !input.isDone()) {
throw new DeflateException(Z_BUF_ERROR);
}
// Start a new block or continue the current one.
if (!input.isDone() || lookahead != 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
int bstate;
switch (configuration_table[level].func) {
case STORED:
bstate = deflate_stored(flush);
break;
case FAST:
bstate = deflate_fast(flush);
break;
case SLOW:
bstate = deflate_slow(flush);
break;
default:
bstate = -1;
}
if (bstate == FINISH_STARTED || bstate == FINISH_DONE) {
status = FINISH_STATE;
}
if (bstate == NEED_MORE || bstate == FINISH_STARTED) {
if (avail_out == 0) {
last_flush = -1; // avoid BUF_ERROR next call, see above
}
return true;
// If flush != Z_NO_FLUSH && avail_out == 0, the next call
// of deflate should use the same flush parameter to make sure
// that the flush is complete. So we don't have to output an
// empty block here, this will be done at next call. This also
// ensures that for a very small output buffer, we emit at most
// one empty block.
}
if (bstate == BLOCK_DONE) {
if (flush == Z_PARTIAL_FLUSH) {
tr_align();
} else if (flush != Z_BLOCK) { // FULL_FLUSH or SYNC_FLUSH
tr_stored_block(0, 0, false);
// For a full flush, this empty block will be recognized
// as a special marker by inflate_sync().
if (flush == Z_FULL_FLUSH) {
for (int i = 0; i < hash_size; i += 1) { // forget history
head[i] = 0;
}
if (lookahead == 0) {
strstart = 0;
block_start = 0;
insert = 0;
}
}
}
flush_pending();
if (avail_out == 0) {
last_flush = -1; // avoid BUF_ERROR at next call, see above
return false;
}
}
}
assert avail_out > 0 : "bug2";
if (wrap <= 0) {
return false;
}
if (flush != Z_FINISH) {
return true;
}
// Write the trailer
if (wrap == 2) {
put_byte(adler);
put_byte(adler >>> 8);
put_byte(adler >>> 16);
put_byte(adler >>> 24);
put_byte((int)total_in);
put_byte((int)total_in >>> 8);
put_byte((int)total_in >>> 16);
put_byte((int)total_in >>> 24);
} else {
putShortMSB(adler >>> 16);
putShortMSB(adler & 0xFFFF);
}
flush_pending();
// If avail_out is zero, the application will call deflate again
// to flush the rest.
if (wrap > 0) {
wrap = -wrap; // write the trailer only once!
}
return false;
}
protected void deflateEnd() {
if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
throw new DeflateException(Z_STREAM_ERROR);
}
// Deallocate in reverse order of allocations:
pending_buf = null;
l_buf = null;
head = null;
prev = null;
window = null;
window_buffer = null;
if (status == BUSY_STATE) {
throw new DeflateException(Z_DATA_ERROR);
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
protected int read_buf(byte[] buf, int start, int size) {
window_buffer.index(start).limit(start + size).isPart(true);
input = input.pull(window_buffer);
int len = window_buffer.index() - start;
if (len == 0) {
return 0;
}
if (wrap == 1) {
adler = adler32(adler, buf, start, len);
} else if (wrap == 2) {
adler = crc32(adler, buf, start, len);
}
total_in += len;
return len;
}
// Initialize the "longest match" routines for a new zlib stream
final void lm_init() {
window_size = 2 * w_size;
for (int i = 0; i < hash_size; i += 1) {
head[i] = 0;
}
// Set the default configuration parameters:
max_lazy_match = configuration_table[level].max_lazy;
good_match = configuration_table[level].good_length;
nice_match = configuration_table[level].nice_length;
max_chain_length = configuration_table[level].max_chain;
strstart = 0;
block_start = 0;
lookahead = 0;
match_length = prev_length = MIN_MATCH - 1;
match_available = 0;
ins_h = 0;
}
// Set match_start to the longest match starting at the given string and
// return its length. Matches shorter or equal to prev_length are discarded,
// in which case the result is equal to prev_length and match_start is
// garbage.
// IN assertions: cur_match is the head of the hash chain for the current
// string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
// OUT assertion: the match length is not greater than s->lookahead.
final int longest_match(int cur_match) {
int chain_length = max_chain_length; // max hash chain length
int scan = strstart; // current string
int match; // matched string
int len; // length of current match
int best_len = prev_length; // best match length so far
int nice_match = this.nice_match; // stop if match long enough
final int limit = strstart > w_size - MIN_LOOKAHEAD ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
// Stop when cur_match becomes <= limit. To simplify the code,
// we prevent matches with the string of window index 0.
final int strend = strstart + MAX_MATCH;
byte scan_end1 = window[scan + best_len - 1];
byte scan_end = window[scan + best_len];
// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
// It is easy to get rid of this optimization if necessary.
assert hash_bits >= 8 && MAX_MATCH == 258 : "Code too clever";
// Do not waste too much time if we already have a good match:
if (prev_length >= good_match) {
chain_length >>>= 2;
}
// Do not look for matches beyond the end of the input. This is necessary
// to make deflate deterministic.
if (nice_match > lookahead) {
nice_match = lookahead;
}
assert strstart <= window_size - MIN_LOOKAHEAD : "need lookahead";
do {
assert cur_match < strstart : "no future";
match = cur_match;
// Skip to next match if the match length cannot increase
// or if the match length is less than 2.
if (window[match + best_len] != scan_end ||
window[match + best_len - 1] != scan_end1 ||
window[match] != window[scan] ||
window[++match] != window[scan + 1]) {
continue;
}
// The check at best_len-1 can be removed because it will be made
// again later. (This heuristic is not always a win.)
// It is not necessary to compare scan[2] and match[2] since they
// are always equal when the other bytes match, given that
// the hash keys are equal and that HASH_BITS >= 8.
scan += 2;
match++;
assert window[scan] == window[match] : "match[2]?";
// We check for insufficient lookahead only every 8th comparison;
// the 256th check will be made at strstart+258.
do {
} while (window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
window[++scan] == window[++match] &&
scan < strend);
assert scan <= window_size - 1 : "wild scan";
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = window[scan + best_len - 1];
scan_end = window[scan + best_len];
}
} while ((cur_match = (prev[cur_match & w_mask] & 0xFFFF)) > limit && --chain_length != 0);
if (best_len <= lookahead) {
return best_len;
}
return lookahead;
}
// Fill the window when the lookahead becomes insufficient.
// Updates strstart and lookahead.
//
// IN assertion: lookahead < MIN_LOOKAHEAD
// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
// At least one byte has been read, or avail_in == 0; reads are
// performed for at least two bytes (required for the zip translate_eol
// option -- not supported here).
protected void fill_window() {
int n, m;
int p;
int more; // Amount of free space at the end of the window.
assert lookahead < MIN_LOOKAHEAD : "already enough lookahead";
do {
more = window_size - lookahead - strstart;
// If the window is almost full and there is insufficient lookahead,
// move the upper half to the lower one to make room in the upper half.
if (strstart >= w_size + (w_size - MIN_LOOKAHEAD)) {
System.arraycopy(window, w_size, window, 0, w_size);
match_start -= w_size;
strstart -= w_size; // we now have strstart >= MAX_DIST
block_start -= w_size;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage). We slide even when level == 0
// to keep the hash table consistent if we switch back to level > 0
// later. (Using level 0 permanently is not an optimal usage of
// zlib, so we don't care about this pathological case.)
n = hash_size;
p = n;
do {
m = head[--p] & 0xFFFF;
head[p] = m >= w_size ? (short)(m - w_size) : 0;
} while (--n != 0);
n = w_size;
p = n;
do {
m = prev[--p] & 0xFFFF;
prev[p] = m >= w_size ? (short)( m - w_size) : 0;
// If n is not on any hash chain, prev[n] is garbage but
// its value will never be used.
}
while (--n != 0);
more += w_size;
}
if (input.isDone()) {
break;
}
// If there was no sliding:
// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
// more == window_size - lookahead - strstart
// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
// => more >= window_size - 2*WSIZE + 2
// In the BIG_MEM or MMAP case (not yet supported),
// window_size == input_size + MIN_LOOKAHEAD &&
// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
// Otherwise, window_size == 2*WSIZE so more >= 2.
// If there was sliding, more >= WSIZE. So in all cases, more >= 2.
assert more >= 2 : "more < 2";
n = read_buf(window, strstart + lookahead, more);
if (n == 0) {
break;
}
lookahead += n;
// Initialize the hash value now that we have some input:
if (lookahead + insert >= MIN_MATCH) {
int str = strstart - insert;
ins_h = window[str] & 0xFF;
ins_h = ((ins_h << hash_shift) ^ (window[str + 1] & 0xFF)) & hash_mask;
while (insert != 0) {
ins_h = ((ins_h << hash_shift) ^ (window[str + (MIN_MATCH - 1)] & 0xFF)) & hash_mask;
prev[str & w_mask] = head[ins_h];
head[ins_h] = (short)str;
str++;
insert--;
if (lookahead + insert < MIN_MATCH) {
break;
}
}
}
// If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
// but this is not important since only literal bytes will be emitted.
} while (lookahead < MIN_LOOKAHEAD && !input.isDone());
assert strstart <= window_size - MIN_LOOKAHEAD : "not enough room for search";
}
// Flush the current block, with given end-of-file flag.
// IN assertion: strstart is set to the end of the current match.
final void flush_block_only(boolean eof) {
tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
block_start = strstart;
flush_pending();
}
// Copy without compression as much as possible from the input stream, return
// the current block state.
// This function does not insert new strings in the dictionary since
// uncompressible data is probably not useful. This function is used
// only for the level=0 compression option.
// NOTE: this function should be optimized to avoid extra copying from
// window to pending_buf.
protected int deflate_stored(int flush) {
// Stored blocks are limited to 0xffff bytes, pending_buf is limited
// to pending_buf_size, and each stored block has a 5 byte header:
int max_block_size = 0xFFFF;
int max_start;
if (max_block_size > pending_buf.length - 5) {
max_block_size = pending_buf.length - 5;
}
// Copy as much as possible from input to output:
while (true) {
// Fill the window as much as possible:
if (lookahead <= 1) {
assert strstart < w_size + (w_size - MIN_LOOKAHEAD) || block_start >= w_size : "slide too late";
fill_window();
if (lookahead == 0 && flush == Z_NO_FLUSH) {
return NEED_MORE;
}
if (lookahead == 0) {
break; // flush the current block
}
}
assert block_start >= 0 : "block gone";
strstart += lookahead;
lookahead = 0;
// Emit a stored block if pending_buf will be full:
max_start = block_start + max_block_size;
if (strstart == 0 || strstart >= max_start) {
// strstart == 0 is possible when wraparound on 16-bit machine
lookahead = strstart - max_start;
strstart = max_start;
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
// Flush if we may have to slide, otherwise block_start may become
// negative and the data will be gone:
if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
}
insert = 0;
if (flush == Z_FINISH) {
flush_block_only(true);
if (avail_out == 0) {
return NEED_MORE;
}
return FINISH_DONE;
}
if (strstart > block_start) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
return BLOCK_DONE;
}
// Compress as much as possible from the input stream, return the current
// block state.
// This function does not perform lazy evaluation of matches and inserts
// new strings in the dictionary only for unmatched strings or for short
// matches. It is used only for the fast compression options.
protected int deflate_fast(int flush) {
int hash_head; // head of the hash chain
boolean bflush; // set if current block must be flushed
while (true) {
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NEED_MORE;
}
if (lookahead == 0) {
break; // flush the current block
}
}
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
hash_head = 0;
if (lookahead >= MIN_MATCH) {
ins_h = ((ins_h << hash_shift) ^ (window[strstart + (MIN_MATCH - 1)] & 0xFF)) & hash_mask;
prev[strstart & w_mask] = head[ins_h];
hash_head = head[ins_h] & 0xFFFF;
head[ins_h] = (short)strstart;
}
// Find the longest match, discarding those <= prev_length.
// At this point we have always match_length < MIN_MATCH
if (hash_head != 0 && ((strstart - hash_head) & 0xFFFF) <= w_size - MIN_LOOKAHEAD) {
// To simplify the code, we prevent matches with the string
// of window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
match_length = longest_match(hash_head);
}
if (match_length >= MIN_MATCH) {
//check_match(strstart, match_start, match_length);
bflush = tr_tally(strstart - match_start, match_length - MIN_MATCH);
lookahead -= match_length;
// Insert new strings in the hash table only if the match length
// is not too large. This saves time but degrades compression.
if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
match_length--; // string at strstart already in table
do {
strstart++;
ins_h = ((ins_h << hash_shift) ^ (window[strstart + (MIN_MATCH - 1)] & 0xFF)) & hash_mask;
prev[strstart & w_mask] = head[ins_h];
hash_head = head[ins_h] & 0xFFFF;
head[ins_h] = (short)strstart;
// strstart never exceeds WSIZE-MAX_MATCH, so there are
// always MIN_MATCH bytes ahead.
} while (--match_length != 0);
strstart++;
} else {
strstart += match_length;
match_length = 0;
ins_h = window[strstart] & 0xFF;
ins_h = ((ins_h << hash_shift) ^ (window[strstart + 1] & 0xFF)) & hash_mask;
// If lookahead < MIN_MATCH, ins_h is garbage, but it does not
// matter since it will be recomputed at next deflate call.
}
} else {
// No match, output a literal byte
bflush = tr_tally(0, window[strstart] & 0xFF);
lookahead--;
strstart++;
}
if (bflush) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
}
insert = strstart < MIN_MATCH - 1 ? strstart : MIN_MATCH - 1;
if (flush == Z_FINISH) {
flush_block_only(true);
if (avail_out == 0) {
return NEED_MORE;
}
return FINISH_DONE;
}
if (last_lit != 0) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
return BLOCK_DONE;
}
// Same as above, but achieves better compression. We use a lazy
// evaluation for matches: a match is finally adopted only if there is
// no better match at the next window position.
protected int deflate_slow(int flush) {
int hash_head; // head of hash chain
boolean bflush; // set if current block must be flushed
// Process the input block.
while (true) {
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NEED_MORE;
}
if (lookahead == 0) {
break; // flush the current block
}
}
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
hash_head = 0;
if (lookahead >= MIN_MATCH) {
ins_h = ((ins_h << hash_shift) ^ (window[strstart + (MIN_MATCH - 1)] & 0xFF)) & hash_mask;
prev[strstart & w_mask] = head[ins_h];
hash_head = head[ins_h] & 0xFFFF;
head[ins_h] = (short)strstart;
}
// Find the longest match, discarding those <= prev_length.
prev_length = match_length;
prev_match = match_start;
match_length = MIN_MATCH - 1;
if (hash_head != 0 && prev_length < max_lazy_match &&
((strstart - hash_head) & 0xFFFF) <= w_size - MIN_LOOKAHEAD) {
// To simplify the code, we prevent matches with the string
// of window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
match_length = longest_match(hash_head);
// longest_match() sets match_start
if (match_length <= 5 && (strategy == Z_FILTERED ||
(match_length == MIN_MATCH && strstart - match_start > TOO_FAR))) {
// If prev_match is also MIN_MATCH, match_start is garbage
// but we will ignore the current match anyway.
match_length = MIN_MATCH - 1;
}
}
// If there was a match at the previous step and the current
// match is not better, output the previous match:
if (prev_length >= MIN_MATCH && match_length <= prev_length) {
int max_insert = strstart + lookahead - MIN_MATCH;
// Do not insert strings in hash table beyond this.
//check_match(strstart - 1, prev_match, prev_length);
bflush = tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
// Insert in hash table all strings up to the end of the match.
// strstart-1 and strstart are already inserted. If there is not
// enough lookahead, the last two strings are not inserted in
// the hash table.
lookahead -= prev_length - 1;
prev_length -= 2;
do{
if (++strstart <= max_insert) {
ins_h = ((ins_h << hash_shift) ^ (window[strstart + (MIN_MATCH - 1)] & 0xFF)) & hash_mask;
prev[strstart & w_mask] = head[ins_h];
hash_head = head[ins_h] & 0xFFFF;
head[ins_h] = (short)strstart;
}
} while (--prev_length != 0);
match_available = 0;
match_length = MIN_MATCH - 1;
strstart++;
if (bflush) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
} else if (match_available != 0) {
// If there was no match at the previous position, output a
// single literal. If there was a match but the current match
// is longer, truncate the previous match to a single literal.
bflush = tr_tally(0, window[strstart - 1] & 0xFF);
if (bflush) {
flush_block_only(false);
}
strstart++;
lookahead--;
if (avail_out == 0) {
return NEED_MORE;
}
} else {
// There is no previous match to compare with, wait for
// the next step to decide.
match_available = 1;
strstart++;
lookahead--;
}
}
assert flush != Z_NO_FLUSH : "no flush?";
if (match_available != 0) {
bflush = tr_tally(0, window[strstart - 1] & 0xFF);
match_available = 0;
}
insert = strstart < MIN_MATCH - 1 ? strstart : MIN_MATCH - 1;
if (flush == Z_FINISH) {
flush_block_only(true);
if (avail_out == 0) {
return NEED_MORE;
}
return FINISH_DONE;
}
if (last_lit != 0) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
return BLOCK_DONE;
}
// For Z_RLE, simply look for runs of bytes, generate matches only of distance
// one. Do not maintain a hash table. (It will be regenerated if this run of
// deflate switches away from Z_RLE.)
protected int deflate_rle(int flush) {
boolean bflush; // set if current block must be flushed
int prev; // byte at distance one to match
int scan, strend; // scan goes up to strend for length of run
while (true) {
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the longest run, plus one for the unrolled loop.
if (lookahead <= MAX_MATCH) {
fill_window();
if (lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
return NEED_MORE;
}
if (lookahead == 0) {
break; // flush the current block
}
}
// See how many times the previous byte repeats
match_length = 0;
if (lookahead >= MIN_MATCH && strstart > 0) {
scan = strstart - 1;
prev = window[scan] & 0xFF;
if (prev == (window[++scan] & 0xFF) && prev == (window[++scan] & 0xFF) &&
prev == (window[++scan] & 0xFF)) {
strend = strstart + MAX_MATCH;
do {
} while (prev == (window[++scan] & 0xFF) && prev == (window[++scan] & 0xFF) &&
prev == (window[++scan] & 0xFF) && prev == (window[++scan] & 0xFF) &&
prev == (window[++scan] & 0xFF) && prev == (window[++scan] & 0xFF) &&
prev == (window[++scan] & 0xFF) && prev == (window[++scan] & 0xFF) &&
scan < strend);
match_length = MAX_MATCH - (strend - scan);
if (match_length > lookahead) {
match_length = lookahead;
}
}
assert scan <= window_size - 1 : "wild scan";
}
// Emit match if have run of MIN_MATCH or longer, else emit literal
if (match_length >= MIN_MATCH) {
//check_match(strstart, strstart - 1, match_length);
bflush = tr_tally(1, match_length - MIN_MATCH);
lookahead -= match_length;
strstart += match_length;
match_length = 0;
} else {
// No match, output a literal byte
bflush = tr_tally(0, window[strstart] & 0xFF);
lookahead--;
strstart++;
}
if (bflush) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
}
insert = 0;
if (flush == Z_FINISH) {
flush_block_only(true);
if (avail_out == 0) {
return NEED_MORE;
}
return FINISH_DONE;
}
if (last_lit != 0) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
return BLOCK_DONE;
}
// For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
// (It will be regenerated if this run of deflate switches away from Huffman.)
protected int deflate_huff(int flush) {
boolean bflush; // set if current block must be flushed
while (true) {
// Make sure that we have a literal to write.
if (lookahead == 0) {
fill_window();
if (lookahead == 0) {
if (flush == Z_NO_FLUSH) {
return NEED_MORE;
}
break; // flush the current block
}
}
// Output a literal byte
match_length = 0;
bflush = tr_tally(0, window[strstart] & 0xFF);
lookahead--;
strstart++;
if (bflush) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
}
insert = 0;
if (flush == Z_FINISH) {
flush_block_only(true);
if (avail_out == 0) {
return NEED_MORE;
}
return FINISH_DONE;
}
if (last_lit != 0) {
flush_block_only(false);
if (avail_out == 0) {
return NEED_MORE;
}
}
return BLOCK_DONE;
}
// Send a value on a given number of bits.
// IN assertion: length <= 16 and value fits in length bits.
final void send_bits(int value, int length) {
if (bi_valid > BUF_SIZE - length) {
bi_buf |= (value << bi_valid) & 0xFFFF;
put_short(bi_buf);
bi_buf = (short)(value >>> (BUF_SIZE - bi_valid));
bi_valid += length - BUF_SIZE;
} else {
bi_buf |= (value << bi_valid) & 0xFFFF;
bi_valid += length;
}
}
// Initialize the tree data structures for a new zlib stream.
final void tr_init() {
l_desc.dyn_tree = dyn_ltree;
l_desc.stat_desc = static_l_desc;
d_desc.dyn_tree = dyn_dtree;
d_desc.stat_desc = static_d_desc;
bl_desc.dyn_tree = bl_tree;
bl_desc.stat_desc = static_bl_desc;
bi_buf = 0;
bi_valid = 0;
//last_eob_len = 8; // enough lookahead for inflate
// Initialize the first block of the first file:
init_block();
}
// Initialize a new block.
final void init_block() {
int n; // iterates over tree elements
// Initialize the trees.
for (n = 0; n < L_CODES; n += 1) {
dyn_ltree[n * 2] = 0;
}
for (n = 0; n < D_CODES; n += 1) {
dyn_dtree[n * 2] = 0;
}
for (n = 0; n < BL_CODES; n += 1) {
bl_tree[n * 2] = 0;
}
dyn_ltree[END_BLOCK * 2] = 1;
opt_len = static_len = 0;
last_lit = matches = 0;
}
// Compares to subtrees, using the tree depth as tie breaker when
// the subtrees have equal frequency. This minimizes the worst case length.
static boolean smaller(short[] tree, int n, int m, byte[] depth) {
short nFreq = tree[n * 2];
short mFreq = tree[m * 2];
return nFreq < mFreq || nFreq == mFreq && depth[n] <= depth[m];
}
// Restore the heap property by moving down the tree starting at node k,
// exchanging a node with the smallest of its two sons if necessary, stopping
// when the heap property is re-established (each father smaller than its
// two sons).
final void pqdownheap(short[] tree, int k) {
int v = heap[k];
int j = k << 1; // left son of k
while (j <= heap_len) {
// Set j to the smallest of the two sons:
if (j < heap_len && smaller(tree, heap[j + 1], heap[j], depth)) {
j++;
}
// Exit if v is smaller than both sons
if (smaller(tree, v, heap[j], depth)) {
break;
}
// Exchange v with the smallest son
heap[k] = heap[j];
k = j;
// And continue down the tree, setting j to the left son of k
j <<= 1;
}
heap[k] = v;
}
// Scan a literal or distance tree to determine the frequencies of the codes
// in the bit length tree.
final void scan_tree(short[] tree, int max_code) {
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
int nextlen = tree[0*2+1]; // length of next code
int count = 0; // repeat count of the current code
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
if (nextlen == 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1] = (short)0xFFFF; // guard
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1];
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
bl_tree[curlen * 2] += count;
} else if (curlen != 0) {
if (curlen != prevlen) {
bl_tree[curlen * 2]++;
}
bl_tree[REP_3_6 * 2]++;
} else if (count <= 10) {
bl_tree[REPZ_3_10 * 2]++;
} else {
bl_tree[REPZ_11_138 * 2]++;
}
count = 0;
prevlen = curlen;
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else if (curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
// Send a literal or distance tree in compressed form, using the codes in
// bl_tree.
final void send_tree(short[] tree, int max_code) {
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
int nextlen = tree[0*2+1]; // length of next code
int count = 0; // repeat count of the current code
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
// tree[(max_code + 1) * 2 + 1] = -1; // guard already set
if (nextlen == 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[(n+1)*2+1];
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
do {
send_code(curlen, bl_tree);
} while (--count != 0);
} else if (curlen != 0) {
if (curlen != prevlen) {
send_code(curlen, bl_tree);
count--;
}
assert count >= 3 && count <= 6 : "3_6?";
send_code(REP_3_6, bl_tree);
send_bits(count - 3, 2);
} else if (count <= 10) {
send_code(REPZ_3_10, bl_tree);
send_bits(count - 3, 3);
} else {
send_code(REPZ_11_138, bl_tree);
send_bits(count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else if (curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
// Construct the Huffman tree for the bit lengths and return the index in
// bl_order of the last bit length code to send.
final int build_bl_tree() {
int max_blindex; // index of last bit length code of non zero freq
// Determine the bit length frequencies for literal and distance trees
scan_tree(dyn_ltree, l_desc.max_code);
scan_tree(dyn_dtree, d_desc.max_code);
// Build the bit length tree:
bl_desc.build_tree(this);
// opt_len now includes the length of the tree representations, except
// the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
// Determine the number of bit length codes to send. The pkzip format
// requires that at least 4 bit length codes be sent. (appnote.txt says
// 3 but the actual value used is 4.)
for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (bl_tree[bl_order[max_blindex] * 2 + 1] != 0) {
break;
}
}
// Update opt_len to include the bit length tree and counts
opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
return max_blindex;
}
// Send the header for a block using dynamic Huffman trees: the counts, the
// lengths of the bit length codes, the literal tree and the distance tree.
// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
final void send_all_trees(int lcodes, int dcodes, int blcodes) {
int rank; // index in bl_order
assert lcodes >= 257 && dcodes >= 1 && blcodes >= 4 : "not enough codes";
assert lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES : "too many codes";
send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
send_bits(dcodes - 1, 5);
send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
for (rank = 0; rank < blcodes; rank++) {
send_bits(bl_tree[bl_order[rank] * 2 + 1], 3);
}
send_tree(dyn_ltree, lcodes - 1); // literal tree
send_tree(dyn_dtree, dcodes - 1); // distance tree
}
// Send a stored block
final void tr_stored_block(int buf, int stored_len, boolean eof) {
send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
copy_block(buf, stored_len, true); // with header
}
// Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
final void tr_flush_bits() {
bi_flush();
}
// Send one empty static block to give enough lookahead for inflate.
// This takes 10 bits, of which 7 may remain in the bit buffer.
final void tr_align() {
send_bits(STATIC_TREES << 1, 3);
send_code(END_BLOCK, static_ltree);
bi_flush();
}
// Determine the best encoding for the current block: dynamic trees, static
// trees or store, and output the encoded block to the zip file.
final void tr_flush_block(int buf, int stored_len, boolean eof) {
int opt_lenb, static_lenb; // opt_len and static_len in bytes
int max_blindex = 0; // index of last bit length code of non zero freq
// Build the Huffman trees unless a stored block is forced
if (level > 0) {
// Check if the file is binary or text
if (data_type == Z_UNKNOWN) {
data_type = detect_data_type();
}
// Construct the literal and distance trees
l_desc.build_tree(this);
d_desc.build_tree(this);
// At this point, opt_len and static_len are the total bit lengths of
// the compressed block data, excluding the tree representations.
// Build the bit length tree for the above two trees, and get the index
// in bl_order of the last bit length code to send.
max_blindex = build_bl_tree();
// Determine the best encoding. Compute the block lengths in bytes.
opt_lenb = (opt_len + 3 + 7) >>> 3;
static_lenb = (static_len + 3 + 7) >>> 3;
if (static_lenb <= opt_lenb) {
opt_lenb = static_lenb;
}
} else {
opt_lenb = static_lenb = stored_len + 5; // force a stored block
}
if (stored_len + 4 <= opt_lenb && buf != -1) {
// 4: two words for the lengths
// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
// Otherwise we can't have processed more than WSIZE input bytes since
// the last block flush, because compression would have been
// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
// transform a block into a stored block.
tr_stored_block(buf, stored_len, eof);
} else if (strategy == Z_FIXED || static_lenb == opt_lenb) {
send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
compress_block(static_ltree, static_dtree);
} else {
send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
compress_block(dyn_ltree, dyn_dtree);
}
init_block();
if (eof) {
bi_windup();
}
}
// Save the match info and tally the frequency counts. Return true if
// the current block must be flushed.
final boolean tr_tally(int dist, int lc) {
pending_buf[d_buf + last_lit * 2] = (byte)(dist >>> 8);
pending_buf[d_buf + last_lit * 2 + 1] = (byte)dist;
l_buf[last_lit++] = (byte)lc;
if (dist == 0) {
// lc is the unmatched char
dyn_ltree[lc * 2]++;
} else {
matches++;
// Here, lc is the match length - MIN_MATCH
dist--; // dist = match distance - 1
assert dist < w_size - MIN_LOOKAHEAD &&
lc <= MAX_MATCH - MIN_MATCH &&
d_code(dist) < D_CODES : "tr_tally: bad match";
dyn_ltree[(length_code[lc] + LITERALS + 1) * 2]++;
dyn_dtree[d_code(dist) * 2]++;
}
return last_lit == lit_bufsize - 1;
// We avoid equality with lit_bufsize because of wraparound at 64K
// on 16 bit machines and because stored blocks are restricted to
// 64K-1 bytes.
}
// Send the block data compressed using the given Huffman trees
final void compress_block(short[] ltree, short[] dtree) {
int dist; // distance of matched string
int lc; // match length or unmatched char (if dist == 0)
int lx = 0; // running index in l_buf
int code; // the code to send
int extra; // number of extra bits to send
if (last_lit != 0) {
do {
dist = ((pending_buf[d_buf + lx * 2] & 0xFF) << 8) | (pending_buf[d_buf + lx * 2 + 1] & 0xFF);
lc = l_buf[lx++] & 0xFF;
if (dist == 0) {
send_code(lc, ltree); // send a literal byte
} else {
// Here, lc is the match length - MIN_MATCH
code = length_code[lc];
send_code(code + LITERALS + 1, ltree); // send the length code
extra = extra_lbits[code];
if (extra != 0) {
lc -= base_length[code];
send_bits(lc, extra); // send the extra length bits
}
dist--; // dist is now the match distance - 1
code = d_code(dist);
assert code < D_CODES : "bad d_code";
send_code(code, dtree); // send the distance code
extra = extra_dbits[code];
if (extra != 0) {
dist -= base_dist[code];
send_bits(dist, extra); // send the extra distance bits
}
} // literal or match pair ?
// Check that the overlay between pending_buf and d_buf+l_buf is ok:
assert pending < lit_bufsize + 2 * lx : "pendingBuf overflow";
} while (lx < last_lit);
}
send_code(END_BLOCK, ltree);
}
// Check if the data type is TEXT or BINARY, using the following algorithm:
// - TEXT if the two conditions below are satisfied:
// a) There are no non-portable control characters belonging to the
// "black list" (0..6, 14..25, 28..31).
// b) There is at least one printable character belonging to the
// "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
// - BINARY otherwise.
// - The following partially-portable control characters form a
// "gray list" that is ignored in this detection algorithm:
// (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
// IN assertion: the fields Freq of dyn_ltree are set.
final int detect_data_type() {
// black_mask is the bit mask of black-listed bytes
// set bits 0..6, 14..25, and 28..31
// 0xf3ffc07f = binary 11110011111111111100000001111111
int black_mask = 0xF3FFC07F;
int n;
// Check for non-textual ("black-listed") bytes.
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) != 0 && dyn_ltree[n * 2] != 0) {
return Z_BINARY;
}
}
// Check for textual ("white-listed") bytes.
if (dyn_ltree[9 * 2] != 0 || dyn_ltree[10 * 2] != 0 || dyn_ltree[13 * 2] != 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (dyn_ltree[n * 2] != 0) {
return Z_TEXT;
}
}
// There are no "black-listed" or "white-listed" bytes:
// this stream either is empty or has tolerated ("gray-listed") bytes only.
return Z_BINARY;
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
static int bi_reverse(int code, int len) {
int res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
// Flush the bit buffer, keeping at most 7 bits in it.
final void bi_flush() {
if (bi_valid == 16) {
put_short(bi_buf);
bi_buf = 0;
bi_valid = 0;
} else if (bi_valid >= 8) {
put_byte(bi_buf);
bi_buf >>>= 8;
bi_valid -= 8;
}
}
// Flush the bit buffer and align the output on a byte boundary
final void bi_windup() {
if (bi_valid > 8) {
put_short(bi_buf);
} else if (bi_valid > 0) {
put_byte(bi_buf);
}
bi_buf = 0;
bi_valid = 0;
}
// Copy a stored block, storing first the length and its
// one's complement if requested.
final void copy_block(int buf, int len, boolean header) {
bi_windup(); // align on byte boundary
if (header) {
put_short(len);
put_short(~len);
}
System.arraycopy(window, buf, pending_buf, pending, len);
pending += len;
}
// Send a code of the given tree.
final void send_code(int c, short[] tree) {
final int c2 = c * 2;
send_bits(tree[c2] & 0xFFFF, tree[c2 + 1] & 0xFFFF);
}
final void putShortMSB(int w) {
put_byte(w >>> 8);
put_byte(w);
}
final void put_short(int w) {
put_byte(w);
put_byte(w >>> 8);
}
final void put_byte(int b) {
pending_buf[pending++] = (byte)b;
}
static final class Tree implements Cloneable {
// the dynamic tree
short[] dyn_tree;
// largest code with non zero frequency
int max_code;
// the corresponding static tree
StaticTree stat_desc;
Tree() {}
Tree(Tree from) {
if (from.dyn_tree != null) {
dyn_tree = new short[from.dyn_tree.length];
System.arraycopy(from.dyn_tree, 0, dyn_tree, 0, dyn_tree.length);
}
max_code = from.max_code;
stat_desc = from.stat_desc;
}
@Override
public Tree clone() {
return new Tree(this);
}
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate<?> s) {
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n * 2 + 1] = (short)bits;
// We overwrite tree[n].Dad which is no longer needed
if (n > max_code) {
continue; // not a leaf node
}
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n - base];
}
f = tree[n * 2];
s.opt_len += f * (bits + xbits);
if (stree != null) {
s.static_len += f * (stree[n * 2 + 1] + xbits);
}
}
if (overflow == 0) {
return;
}
// Find the first bit length which could increase:
do {
bits = max_length - 1;
while (s.bl_count[bits] == 0) {
bits--;
}
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits + 1] += 2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
} while (overflow > 0);
// Now recompute all bit lengths, scanning in increasing frequency.
// h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
// lengths instead of fixing only the wrong ones. This idea is taken
// from 'ar' written by Haruhiko Okumura.)
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) {
continue;
}
if (tree[m * 2 + 1] != bits) {
s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
tree[m * 2 + 1] = (short)bits;
}
n--;
}
}
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
static void gen_codes(short[] tree, int max_code, short[] bl_count, short[] next_code) {
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
next_code[0] = 0;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits - 1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
assert ((code + bl_count[MAX_BITS] - 1) & 0xFFFF) == (1 << MAX_BITS) - 1 : "inconsistent bit counts";
for (n = 0; n <= max_code; n++) {
final int len = tree[n * 2 + 1];
if (len == 0) {
continue;
}
// Now reverse the bits
tree[n * 2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate<?> s) {
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int elems = stat_desc.elems;
int n, m; // iterate over heap elements
int max_code = -1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n * 2 + 1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
tree[node * 2] = 1;
s.depth[node] = 0;
s.opt_len--;
if (stree != null) {
s.static_len -= stree[node * 2 + 1];
}
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for (n = s.heap_len / 2; n >= 1; n--) {
s.pqdownheap(tree, n);
}
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node = elems; // next internal node of the tree
do {
n = s.heap[1]; // n = node of least frequency
s.heap[1] = s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m = s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node * 2] = (short)(tree[n * 2] + tree[m * 2]);
s.depth[node] = (byte)(Math.max(s.depth[n], s.depth[m]) + 1);
tree[n * 2 + 1] = tree[m * 2 + 1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count, s.next_code);
}
}
static final class StaticTree {
// static tree or null
final short[] static_tree;
// extra bits for each code or null
final int[] extra_bits;
// base index for extra_bits
final int extra_base;
// max number of elements in the tree
final int elems;
// max bit length for the codes
final int max_length;
StaticTree(short[] static_tree, int[] extra_bits, int extra_base, int elems, int max_length) {
this.static_tree = static_tree;
this.extra_bits = extra_bits;
this.extra_base = extra_base;
this.elems = elems;
this.max_length = max_length;
}
}
static final class Config {
// reduce lazy search above this match length
final int good_length;
// do not perform lazy search above this match length
final int max_lazy;
// quit search above this match length
final int nice_length;
final int max_chain;
final int func;
Config(int good_length, int max_lazy, int nice_length, int max_chain, int func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
}
// Allowed flush values
public static final int Z_NO_FLUSH = 0;
public static final int Z_PARTIAL_FLUSH = 1;
public static final int Z_SYNC_FLUSH = 2;
public static final int Z_FULL_FLUSH = 3;
public static final int Z_FINISH = 4;
public static final int Z_BLOCK = 5;
public static final int Z_TREES = 6;
// Return codes for the compression/decompression functions. Negative values
// are errors, positive values are used for special but normal events.
public static final int Z_OK = 0;
public static final int Z_STREAM_END = 1;
public static final int Z_NEED_DICT = 2;
public static final int Z_ERRNO = -1;
public static final int Z_STREAM_ERROR = -2;
public static final int Z_DATA_ERROR = -3;
public static final int Z_MEM_ERROR = -4;
public static final int Z_BUF_ERROR = -5;
public static final int Z_VERSION_ERROR = -6;
// Wrappers
public static final int Z_NO_WRAP = 0;
public static final int Z_WRAP_ZLIB = 1;
public static final int Z_WRAP_GZIP = 2;
// compression levels
public static final int Z_NO_COMPRESSION = 0;
public static final int Z_BEST_SPEED = 1;
public static final int Z_BEST_COMPRESSION = 9;
public static final int Z_DEFAULT_COMPRESSION = -1;
// compression strategy
public static final int Z_FILTERED = 1;
public static final int Z_HUFFMAN_ONLY = 2;
public static final int Z_RLE = 3;
public static final int Z_FIXED = 4;
public static final int Z_DEFAULT_STRATEGY = 0;
// Possible values of the data_type field
public static final int Z_BINARY = 0;
public static final int Z_TEXT = 1;
public static final int Z_UNKNOWN = 2;
// Maximum value for windowBits
public static final int MAX_WBITS = 15; // 32K LZ77 window
// Default memLevel
public static final int DEF_MEM_LEVEL = 8;
//public static final int OS_MSDOS = 0x00;
//public static final int OS_AMIGA = 0x01;
//public static final int OS_VMS = 0x02;
//public static final int OS_UNIX = 0x03;
//public static final int OS_VMCMS = 0x04;
//public static final int OS_ATARI = 0x05;
//public static final int OS_OS2 = 0x06;
//public static final int OS_MACOS = 0x07;
//public static final int OS_ZSYSTEM = 0x08;
//public static final int OS_CPM = 0x09;
//public static final int OS_TOPS20 = 0x0A;
//public static final int OS_WIN32 = 0x0B;
//public static final int OS_QDOS = 0x0C;
//public static final int OS_RISCOS = 0x0D;
public static final int OS_UNKNOWN = 0xFF;
public static final int OS_CODE = OS_UNKNOWN;
// The deflate compression method
static final int Z_DEFLATED = 8;
// number of length codes, not counting the special END_BLOCK code
static final int LENGTH_CODES = 29;
// number of literal bytes 0..255
static final int LITERALS = 256;
// number of Literal or Length codes, including the END_BLOCK code
static final int L_CODES = LITERALS + 1 + LENGTH_CODES;
// number of distance codes
static final int D_CODES = 30;
// number of codes used to transfer the bit lengths
static final int BL_CODES = 19;
// maximum heap size
static final int HEAP_SIZE = 2 * L_CODES + 1;
// All codes must not exceed MAX_BITS bits
static final int MAX_BITS = 15;
// end of block literal code
static final int END_BLOCK = 256;
// size of bit buffer in bi_buf
static final int BUF_SIZE = 16;
// Stream status
static final int INIT_STATE = 42;
static final int EXTRA_STATE = 69;
static final int NAME_STATE = 73;
static final int COMMENT_STATE = 91;
static final int HCRC_STATE = 103;
static final int BUSY_STATE = 113;
static final int FINISH_STATE = 666;
// The three kinds of block type
static final int STORED_BLOCK = 0;
static final int STATIC_TREES = 1;
static final int DYN_TREES = 2;
static final int MIN_MATCH = 3;
static final int MAX_MATCH = 258;
// Minimum amount of lookahead, except at the end of the input file.
static final int MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
// Matches of length 3 are discarded if their distance exceeds TOO_FAR
static final int TOO_FAR = 4096;
// Maximum value for memLevel in deflateInit
static final int MAX_MEM_LEVEL = 9;
// block not completed, need more input or more output
static final int NEED_MORE = 0;
// block flush performed
static final int BLOCK_DONE = 1;
// finish started, need only more output at next deflate
static final int FINISH_STARTED = 2;
// finish done, accept no more input or output
static final int FINISH_DONE = 3;
// preset dictionary flag in zlib header
static final int PRESET_DICT = 0x20;
// compress_func
static final int STORED = 0;
static final int FAST = 1;
static final int SLOW = 2;
static final Config[] configuration_table = {
new Config(0, 0, 0, 0, STORED),
new Config(4, 4, 8, 4, FAST),
new Config(4, 5, 16, 8, FAST),
new Config(4, 6, 32, 32, FAST),
new Config(4, 4, 16, 16, SLOW),
new Config(8, 16, 32, 32, SLOW),
new Config(8, 16, 128, 128, SLOW),
new Config(8, 32, 128, 256, SLOW),
new Config(32, 128, 258, 1024, SLOW),
new Config(32, 258, 258, 4096, SLOW)
};
static final String[] z_errmsg = {
"need dictionary", // Z_NEED_DICT 2
"stream end", // Z_STREAM_END 1
"", // Z_OK 0
"file error", // Z_ERRNO -1
"stream error", // Z_STREAM_ERROR -2
"data error", // Z_DATA_ERROR -3
"insufficient memory", // Z_MEM_ERROR -4
"buffer error", // Z_BUF_ERROR -5
"incompatible version",// Z_VERSION_ERROR -6
""
};
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS = 7;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138 = 18;
// extra bits for each length code
static final int[] extra_lbits = {
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits = {
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit length codes.
static final byte[] bl_order = {
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. dist_code[256] and dist_code[257] are never
// used.
static int d_code(int dist) {
return dist < 256 ? dist_code[dist] : dist_code[256 + (dist >>> 7)];
}
// see definition of array dist_code below
static final int DIST_CODE_LEN = 512;
// Distance codes. The first 256 values correspond to the distances
// 3 .. 258, the last 256 values correspond to the top 8 bits of
// the 15 bit distances.
static final byte[] dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
// length code for each normalized match length (0 == MIN_MATCH)
static final byte[] length_code = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
// First normalized length for each code (0 = MIN_MATCH)
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
// First normalized distance for each code (0 = distance of 1)
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// The static literal tree. Since the bit lengths are imposed, there is no
// need for the L_CODES extra codes used during heap construction. However
// The codes 286 and 287 are needed to build a canonical tree.
static final short[] static_ltree = {
12, 8, 140, 8, 76, 8, 204, 8, 44, 8,
172, 8, 108, 8, 236, 8, 28, 8, 156, 8,
92, 8, 220, 8, 60, 8, 188, 8, 124, 8,
252, 8, 2, 8, 130, 8, 66, 8, 194, 8,
34, 8, 162, 8, 98, 8, 226, 8, 18, 8,
146, 8, 82, 8, 210, 8, 50, 8, 178, 8,
114, 8, 242, 8, 10, 8, 138, 8, 74, 8,
202, 8, 42, 8, 170, 8, 106, 8, 234, 8,
26, 8, 154, 8, 90, 8, 218, 8, 58, 8,
186, 8, 122, 8, 250, 8, 6, 8, 134, 8,
70, 8, 198, 8, 38, 8, 166, 8, 102, 8,
230, 8, 22, 8, 150, 8, 86, 8, 214, 8,
54, 8, 182, 8, 118, 8, 246, 8, 14, 8,
142, 8, 78, 8, 206, 8, 46, 8, 174, 8,
110, 8, 238, 8, 30, 8, 158, 8, 94, 8,
222, 8, 62, 8, 190, 8, 126, 8, 254, 8,
1, 8, 129, 8, 65, 8, 193, 8, 33, 8,
161, 8, 97, 8, 225, 8, 17, 8, 145, 8,
81, 8, 209, 8, 49, 8, 177, 8, 113, 8,
241, 8, 9, 8, 137, 8, 73, 8, 201, 8,
41, 8, 169, 8, 105, 8, 233, 8, 25, 8,
153, 8, 89, 8, 217, 8, 57, 8, 185, 8,
121, 8, 249, 8, 5, 8, 133, 8, 69, 8,
197, 8, 37, 8, 165, 8, 101, 8, 229, 8,
21, 8, 149, 8, 85, 8, 213, 8, 53, 8,
181, 8, 117, 8, 245, 8, 13, 8, 141, 8,
77, 8, 205, 8, 45, 8, 173, 8, 109, 8,
237, 8, 29, 8, 157, 8, 93, 8, 221, 8,
61, 8, 189, 8, 125, 8, 253, 8, 19, 9,
275, 9, 147, 9, 403, 9, 83, 9, 339, 9,
211, 9, 467, 9, 51, 9, 307, 9, 179, 9,
435, 9, 115, 9, 371, 9, 243, 9, 499, 9,
11, 9, 267, 9, 139, 9, 395, 9, 75, 9,
331, 9, 203, 9, 459, 9, 43, 9, 299, 9,
171, 9, 427, 9, 107, 9, 363, 9, 235, 9,
491, 9, 27, 9, 283, 9, 155, 9, 411, 9,
91, 9, 347, 9, 219, 9, 475, 9, 59, 9,
315, 9, 187, 9, 443, 9, 123, 9, 379, 9,
251, 9, 507, 9, 7, 9, 263, 9, 135, 9,
391, 9, 71, 9, 327, 9, 199, 9, 455, 9,
39, 9, 295, 9, 167, 9, 423, 9, 103, 9,
359, 9, 231, 9, 487, 9, 23, 9, 279, 9,
151, 9, 407, 9, 87, 9, 343, 9, 215, 9,
471, 9, 55, 9, 311, 9, 183, 9, 439, 9,
119, 9, 375, 9, 247, 9, 503, 9, 15, 9,
271, 9, 143, 9, 399, 9, 79, 9, 335, 9,
207, 9, 463, 9, 47, 9, 303, 9, 175, 9,
431, 9, 111, 9, 367, 9, 239, 9, 495, 9,
31, 9, 287, 9, 159, 9, 415, 9, 95, 9,
351, 9, 223, 9, 479, 9, 63, 9, 319, 9,
191, 9, 447, 9, 127, 9, 383, 9, 255, 9,
511, 9, 0, 7, 64, 7, 32, 7, 96, 7,
16, 7, 80, 7, 48, 7, 112, 7, 8, 7,
72, 7, 40, 7, 104, 7, 24, 7, 88, 7,
56, 7, 120, 7, 4, 7, 68, 7, 36, 7,
100, 7, 20, 7, 84, 7, 52, 7, 116, 7,
3, 8, 131, 8, 67, 8, 195, 8, 35, 8,
163, 8, 99, 8, 227, 8
};
// The static distance tree. (Actually a trivial tree since all codes use
// 5 bits.)
static final short[] static_dtree = {
0, 5, 16, 5, 8, 5, 24, 5, 4, 5,
20, 5, 12, 5, 28, 5, 2, 5, 18, 5,
10, 5, 26, 5, 6, 5, 22, 5, 14, 5,
30, 5, 1, 5, 17, 5, 9, 5, 25, 5,
5, 5, 21, 5, 13, 5, 29, 5, 3, 5,
19, 5, 11, 5, 27, 5, 7, 5, 23, 5
};
static final StaticTree static_l_desc = new StaticTree(static_ltree, extra_lbits,
LITERALS + 1, L_CODES, MAX_BITS);
static final StaticTree static_d_desc = new StaticTree(static_dtree, extra_dbits,
0, D_CODES, MAX_BITS);
static final StaticTree static_bl_desc = new StaticTree(null, extra_blbits,
0, BL_CODES, MAX_BL_BITS);
}
|
0 | java-sources/ai/swim/swim-deflate/3.10.0/swim | java-sources/ai/swim/swim-deflate/3.10.0/swim/deflate/DeflateException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.deflate;
public class DeflateException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final int code;
public DeflateException(int code) {
super(Deflate.z_errmsg[Deflate.Z_NEED_DICT - code]);
this.code = code;
}
public DeflateException(String message) {
super(message);
this.code = -1;
}
public DeflateException() {
super();
this.code = -1;
}
public int code() {
return this.code;
}
}
|
0 | java-sources/ai/swim/swim-deflate/3.10.0/swim | java-sources/ai/swim/swim-deflate/3.10.0/swim/deflate/GzHeader.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.deflate;
@SuppressWarnings("checkstyle:all")
final class GzHeader implements Cloneable {
// true if compressed data believed to be text
boolean text;
// modification time
int time;
// extra flags (not used when writing a gzip file)
int xflags;
// operating system
int os;
// pointer to extra field or Z_NULL if none
byte[] extra;
// extra field length (valid if extra != Z_NULL)
int extra_len;
// pointer to zero-terminated file name or Z_NULL
byte[] name;
// pointer to zero-terminated comment or Z_NULL
byte[] comment;
// true if there was or will be a header crc
boolean hcrc;
// true when done reading gzip header (not used when writing a gzip file)
boolean done;
GzHeader() {
// nop
}
GzHeader(GzHeader from) {
text = from.text;
time = from.time;
xflags = from.xflags;
os = from.os;
extra = from.extra;
extra_len = from.extra_len;
name = from.name;
comment = from.comment;
hcrc = from.hcrc;
done = from.done;
}
@Override
public GzHeader clone() {
return new GzHeader(this);
}
}
|
0 | java-sources/ai/swim/swim-deflate/3.10.0/swim | java-sources/ai/swim/swim-deflate/3.10.0/swim/deflate/Inflate.java | // Based on zlib-1.2.8
// Copyright (c) 1995-2013 Jean-loup Gailly and Mark Adler
// Copyright (c) 2016-2018 Swim.it inc.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
package swim.deflate;
import swim.codec.Binary;
import swim.codec.Decoder;
import swim.codec.DecoderException;
import swim.codec.InputBuffer;
import static swim.deflate.Adler32.adler32;
import static swim.deflate.CRC32.crc32;
@SuppressWarnings("checkstyle:all")
public class Inflate<O> extends Decoder<O> implements Cloneable {
// inflated output sink
public Decoder<O> output;
// true if input will stop producing
public boolean is_last;
// flush mode for feed operations
public int flush;
// input buffer
public byte[] next_in;
// next input byte
public int next_in_index;
// number of bytes available at next_in_index
public int avail_in;
// total number of input bytes read so far
public long total_in;
// output buffer
public byte[] next_out;
// next output byte should be put there
public int next_out_index;
// remaining free space at next_out_index
public int avail_out;
// total number of bytes output so far
public long total_out;
// best guess about the data type: binary or text
int data_type;
// adler32 value of the uncompressed data
int adler;
// current inflate mode
int mode;
// true if processing last block
boolean last;
// bit 0 true for zlib, bit 1 true for gzip
int wrap;
// true if dictionary provided
boolean havedict;
// gzip header method and flags (0 if zlib)
int flags;
// zlib header max distance (INFLATE_STRICT)
int dmax;
// protected copy of check value
int check;
// protected copy of output count
long total;
// where to save gzip header information
GzHeader head;
// log base 2 of requested window size
int wbits;
// window size or zero if not using window
int wsize;
// valid bytes in the window
public int whave;
// window write index
public int wnext;
// allocated sliding window, if needed
public byte[] window;
// Output reads directly from sliding window through this buffer.
public InputBuffer window_buffer;
// input bit accumulator
int hold;
// number of bits in "in"
int bits;
// literal or length of data to copy
int length;
// distance back to copy string from
int offset;
// extra bits needed
int extra;
// starting table for length/literal codes
int lencode;
// starting table for distance codes
int distcode;
// index bits for lencode
int lenbits;
// index bits for distcode
int distbits;
// number of code length code lengths
int ncode;
// number of length code lengths
int nlen;
// number of distance code lengths
int ndist;
// number of code lengths in lens[]
int have;
// next available space in codes[]
int next;
// temporary storage for code lengths
short lens[] = new short[320];
// work area for code table building
short work[] = new short[288];
// space for code tables
int codes[] = new int[ENOUGH];
// if false, allow invalid distance too far
boolean sane;
// bits back of last unprocessed length/lit
int back;
// initial length of match
int was;
public Inflate(Decoder<O> output, int wrap, int windowBits) {
this.output = output;
inflateInit(wrap, windowBits);
}
public Inflate(Decoder<O> output, int wrap) {
this(output, wrap, DEF_WBITS);
}
public Inflate(Decoder<O> output) {
this(output, Z_NO_WRAP, DEF_WBITS);
}
public Inflate(int wrap, int windowBits) {
this(null, wrap, windowBits);
}
public Inflate(int wrap) {
this(null, wrap, DEF_WBITS);
}
public Inflate() {
this(null, Z_NO_WRAP, DEF_WBITS);
}
Inflate(Inflate<O> from) {
output = from.output;
is_last = from.is_last;
flush = from.flush;
next_in = from.next_in;
next_in_index = from.next_in_index;
avail_in = from.avail_in;
total_in = from.total_in;
next_out = from.next_out;
next_out_index = from.next_out_index;
avail_out = from.avail_out;
total_out = from.total_out;
data_type = from.data_type;
adler = from.adler;
mode = from.mode;
last = from.last;
wrap = from.wrap;
havedict = from.havedict;
flags = from.flags;
dmax = from.dmax;
check = from.check;
total = from.total;
if (head != null) {
head = from.head.clone();
}
wbits = from.wbits;
wsize = from.wsize;
whave = from.whave;
wnext = from.wnext;
if (from.window != null) {
window = new byte[from.window.length];
System.arraycopy(from.window, 0, window, 0, window.length);
window_buffer = Binary.inputBuffer(window);
}
hold = from.hold;
bits = from.bits;
length = from.length;
offset = from.offset;
extra = from.extra;
lencode = from.lencode;
distcode = from.distcode;
lenbits = from.lenbits;
distbits = from.distbits;
ncode = from.ncode;
nlen = from.nlen;
ndist = from.ndist;
have = from.have;
next = from.next;
System.arraycopy(from.lens, 0, lens, 0, lens.length);
System.arraycopy(from.work, 0, work, 0, work.length);
System.arraycopy(from.codes, 0, codes, 0, codes.length);
sane = from.sane;
back = from.back;
was = from.was;
}
public void inflateResetKeep() {
total_in = total_out = total = 0;
flush = Z_FINISH;
mode = HEAD;
last = false;
havedict = false;
dmax = 32768;
head = null;
hold = 0;
bits = 0;
lencode = distcode = next = 0;
sane = true;
back = -1;
}
public void inflateReset() {
wsize = 0;
whave = 0;
wnext = 0;
inflateResetKeep();
}
public void inflateReset(int wrap, int windowBits) {
// set number of window bits, free window if different
if (windowBits != 0 && (windowBits < 8 || windowBits > 15)) {
throw new DeflateException(Z_STREAM_ERROR);
}
if (window != null && wbits != windowBits) {
window = null;
window_buffer = null;
}
// update state and reset the rest of it
this.wrap = wrap;
wbits = windowBits;
inflateReset();
}
protected void inflateInit(int wrap, int windowBits) {
window = null;
window_buffer = null;
inflateReset(wrap, windowBits);
}
public void initWindow() {
if (window == null) {
wsize = 1 << wbits;
window = new byte[wsize * 2];
window_buffer = Binary.inputBuffer(window);
wnext = 0;
whave = 0;
}
}
@Override
public Inflate<O> clone() {
return new Inflate<O>(this);
}
// Set the current flush mode.
public Inflate<O> flush(int flush) {
this.flush = flush;
return this;
}
@Override
public Decoder<O> feed(InputBuffer input) {
is_last = !input.isPart();
next_in = input.array();
next_in_index = input.arrayOffset() + input.index();
avail_in = input.remaining();
initWindow();
next_out = window;
try {
boolean needsMore;
do {
next_out_index = wnext;
avail_out = window.length - wnext;
needsMore = inflate(flush);
} while (needsMore && avail_in > 0 && output.isCont());
if (output.isDone()) {
return output;
} else if (output.isError()) {
return output.asError();
} else if (!needsMore) {
return done();
} else if (input.isDone()) {
return error(new DecoderException("truncated"));
} else if (input.isError()) {
return error(input.trap());
} else {
return this;
}
} catch (DeflateException cause) {
return error(cause);
} finally {
input.index(next_in_index - input.arrayOffset());
next_out = null;
next_out_index = 0;
avail_out = 0;
next_in = null;
next_in_index = 0;
avail_in = 0;
}
}
@SuppressWarnings("fallthrough")
public boolean inflate(int flush) {
int in, out; // save starting available input and output
int copy; // number of stored or match bytes to copy
int from; // where to copy match bytes from
int here; // current decoding table entry
int hereOp;
int hereBits;
int hereVal;
int last; // parent table entry
int lastOp;
int lastBits;
int lastVal;
int len; // length to copy for repeats, bits to drop
int ret; // return code
String msg = null;
byte[] hbuf = wrap == 2 ? new byte[4] : null; // buffer for gzip header crc calculation
if (next_out == null || next_in == null && avail_in != 0) {
throw new DeflateException(Z_STREAM_ERROR);
}
if (mode == TYPE) {
mode = TYPEDO; // skip check
}
in = avail_in;
out = avail_out;
ret = Z_OK;
inf_leave: while (true) {
switch (mode) {
case HEAD:
if (wrap == 0) {
mode = TYPEDO;
break;
}
if (!NEEDBITS(16)) {
break inf_leave;
}
if ((wrap & 2) != 0 && hold == 0x8B1F) { // gzip header
check = crc32(0, null, 0, 0);
CRC2(check, hbuf, hold);
INITBITS();
mode = FLAGS;
break;
}
flags = 0; // expect zlib header
if (head != null) {
head.done = false;
}
if ((wrap & 1) == 0 || // check if zlib header allowed
((BITS(8) << 8) + (hold >>> 8)) % 31 != 0) {
throw new DeflateException("incorrect header check");
//msg = "incorrect header check";
//mode = BAD;
//break;
}
if (BITS(4) != Z_DEFLATED) {
throw new DeflateException("unknown compression method");
//msg = "unknown compression method";
//mode = BAD;
//break;
}
DROPBITS(4);
len = BITS(4) + 8;
if (wbits == 0) {
wbits = len;
} else if (len > wbits) {
throw new DeflateException("invalid window size");
//msg = "invalid window size";
//mode = BAD;
//break;
}
dmax = 1 << len;
adler = check = adler32(0, null, 0, 0);
mode = (hold & 0x200) != 0 ? DICTID : TYPE;
INITBITS();
break;
case FLAGS:
if (!NEEDBITS(16)) {
break inf_leave;
}
flags = hold;
if ((flags & 0xFF) != Z_DEFLATED) {
throw new DeflateException("unknown compression method");
//msg = "unknown compression method";
//mode = BAD;
//break;
}
if ((flags & 0xE000) != 0) {
throw new DeflateException("unknown header flags set");
//msg = "unknown header flags set";
//mode = BAD;
//break;
}
if (head != null) {
head.text = ((hold >>> 8) & 1) != 0;
}
if ((flags & 0x0200) != 0) {
CRC2(check, hbuf, hold);
}
INITBITS();
mode = TIME;
case TIME:
if (!NEEDBITS(32)) {
break inf_leave;
}
if (head != null) {
head.time = hold;
}
if ((flags & 0x0200) != 0) {
CRC4(check, hbuf, hold);
}
INITBITS();
mode = OS;
case OS:
if (!NEEDBITS(16)) {
break inf_leave;
}
if (head != null) {
head.xflags = hold & 0xFF;
head.os = hold >>> 8;
}
if ((flags & 0x0200) != 0) {
CRC2(check, hbuf, hold);
}
INITBITS();
mode = EXLEN;
case EXLEN:
if ((flags & 0x0400) != 0) {
if (!NEEDBITS(16)) {
break inf_leave;
}
length = hold;
if (head != null) {
head.extra_len = hold;
}
if ((flags & 0x0200) != 0) {
CRC2(check, hbuf, hold);
}
INITBITS();
} else if (head != null) {
head.extra = null;
}
mode = EXTRA;
case EXTRA:
if ((flags & 0x0400) != 0) {
copy = length;
if (copy > avail_in) {
copy = avail_in;
}
if (copy != 0) {
if (head != null) {
len = head.extra_len - length;
head.extra = new byte[copy];
System.arraycopy(next_in, next_in_index, head.extra, len, copy);
}
if ((flags & 0x0200) != 0) {
check = crc32(check, next_in, next_in_index, copy);
}
avail_in -= copy;
next_in_index += copy;
length -= copy;
}
if (length != 0) {
break inf_leave;
}
}
length = 0;
mode = NAME;
case NAME:
if ((flags & 0x0800) != 0) {
if (avail_in == 0) {
break inf_leave;
}
copy = 0;
do {
len = next_in[next_in_index + copy++];
if (head != null && head.name != null && length < head.name.length) {
head.name[length++] = (byte)len;
}
} while (len != 0 && copy < avail_in);
if ((flags & 0x0200) != 0) {
check = crc32(check, next_in, next_in_index, copy);
}
avail_in -= copy;
next_in_index += copy;
if (len != 0) {
break inf_leave;
}
} else if (head != null) {
head.name = null;
}
length = 0;
mode = COMMENT;
case COMMENT:
if ((flags & 0x1000) != 0) {
if (avail_in == 0) {
break inf_leave;
}
copy = 0;
do {
len = next_in[next_in_index + copy++];
if (head != null && head.comment != null && length < head.comment.length) {
head.comment[length++] = (byte)len;
}
} while (len != 0 && copy < avail_in);
if ((flags & 0x0200) != 0) {
check = crc32(check, next_in, next_in_index, copy);
}
avail_in -= copy;
next_in_index += copy;
if (len != 0) {
break inf_leave;
}
} else if (head != null) {
head.comment = null;
}
mode = HCRC;
case HCRC:
if ((flags & 0x0200) != 0) {
if (!NEEDBITS(16)) {
break inf_leave;
}
if (hold != (check & 0xFFFF)) {
throw new DeflateException("header crc mismatch");
//msg = "header crc mismatch";
//mode = BAD;
//break;
}
INITBITS();
}
if (head != null) {
head.hcrc = ((flags >>> 9) & 1) != 0;
head.done = true;
}
adler = check = crc32(0, null, 0, 0);
mode = TYPE;
break;
case DICTID:
if (!NEEDBITS(32)) {
break inf_leave;
}
adler = check = Integer.reverseBytes(hold);
INITBITS();
mode = DICT;
case DICT:
if (!havedict) {
throw new DeflateException(Z_NEED_DICT);
}
adler = check = adler32(0, null, 0, 0);
mode = TYPE;
case TYPE:
if (flush == Z_BLOCK || flush == Z_TREES) {
break inf_leave;
}
case TYPEDO:
if (this.last) {
BYTEBITS();
mode = CHECK;
break;
}
if (!NEEDBITS(3)) {
break inf_leave;
}
this.last = BITS(1) != 0;
DROPBITS(1);
switch (BITS(2)) {
case 0: // stored block
mode = STORED;
break;
case 1: // fixed block
fixedtables();
mode = LEN_; // decode codes
if (flush == Z_TREES) {
DROPBITS(2);
break inf_leave;
}
break;
case 2: // dynamic block
mode = TABLE;
break;
case 3:
throw new DeflateException("invalid block type");
//msg = "invalid block type";
//mode = BAD;
}
DROPBITS(2);
break;
case STORED:
BYTEBITS(); // go to byte boundary
if (!NEEDBITS(32)) {
break inf_leave;
}
if ((hold & 0xFFFF) != ((hold >>> 16) ^ 0xFFFF)) {
throw new DeflateException("invalid stored block lengths");
//msg = "invalid stored block lengths";
//mode = BAD;
//break;
}
length = hold & 0xFFFF;
INITBITS();
mode = COPY_;
if (flush == Z_TREES) {
break inf_leave;
}
case COPY_:
mode = COPY;
case COPY:
copy = length;
if (copy != 0) {
if (copy > avail_in) {
copy = avail_in;
}
if (copy > avail_out) {
copy = avail_out;
}
if (copy == 0) {
break inf_leave;
}
System.arraycopy(next_in, next_in_index, next_out, next_out_index, copy);
avail_in -= copy;
next_in_index += copy;
avail_out -= copy;
next_out_index += copy;
length -= copy;
break;
}
mode = TYPE;
break;
case TABLE:
if (!NEEDBITS(14)) {
break inf_leave;
}
nlen = BITS(5) + 257;
DROPBITS(5);
ndist = BITS(5) + 1;
DROPBITS(5);
ncode = BITS(4) + 4;
DROPBITS(4);
if (nlen > 286 || ndist > 30) { // PKZIP_BUG_WORKAROUND
throw new DeflateException("too many length or distance symbols");
//msg = "too many length or distance symbols";
//mode = BAD;
//break;
}
have = 0;
mode = LENLENS;
case LENLENS:
while (have < ncode) {
if (!NEEDBITS(3)) {
break inf_leave;
}
lens[order[have++]] = (short)BITS(3);
DROPBITS(3);
}
while (have < 19) {
lens[order[have++]] = 0;
}
next = 0;
lencode = next;
lenbits = 7;
ret = inflate_table(CODES, 0, 19);
if (ret != 0) {
throw new DeflateException("invalid code lengths set");
//msg = "invalid code lengths set";
//mode = BAD;
//break;
}
have = 0;
mode = CODELENS;
case CODELENS:
while (have < nlen + ndist) {
while (true) {
here = codes[lencode + BITS(lenbits)];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
if (hereBits <= bits) {
break;
}
if (!PULLBYTE()) {
break inf_leave;
}
}
if (hereVal < 16) {
DROPBITS(hereBits);
lens[have++] = (short)hereVal;
} else {
if (hereVal == 16) {
if (!NEEDBITS(hereBits + 2)) {
break inf_leave;
}
DROPBITS(hereBits);
if (have == 0) {
throw new DeflateException("invalid bit length repeat");
//msg = "invalid bit length repeat";
//mode = BAD;
//break;
}
len = lens[have - 1];
copy = 3 + BITS(2);
DROPBITS(2);
} else if (hereVal == 17) {
if (!NEEDBITS(hereBits + 3)) {
break inf_leave;
}
DROPBITS(hereBits);
len = 0;
copy = 3 + BITS(3);
DROPBITS(3);
} else {
if (!NEEDBITS(hereBits + 7)) {
break inf_leave;
}
DROPBITS(hereBits);
len = 0;
copy = 11 + BITS(7);
DROPBITS(7);
}
if (have + copy > nlen + ndist) {
throw new DeflateException("invalid bit length repeat");
//msg = "invalid bit length repeat";
//mode = BAD;
//break;
}
while (copy-- != 0) {
lens[have++] = (short)len;
}
}
}
// handle error breaks in while
if (mode == BAD) {
break;
}
// check for end-of-block code (better have one)
if (lens[256] == 0) {
throw new DeflateException("invalid code -- missing end-of-block");
//msg = "invalid code -- missing end-of-block";
//mode = BAD;
//break;
}
// build code tables -- note: do not change the lenbits or distbits
// values here (9 and 6) without reading the comments in inftrees.h
// concerning the ENOUGH constants, which depend on those values
next = 0;
lencode = next;
lenbits = 9;
ret = inflate_table(LENS, 0, nlen);
if (ret != 0) {
throw new DeflateException("invalid literal/lengths set");
//msg = "invalid literal/lengths set";
//mode = BAD;
//break;
}
distcode = next;
distbits = 6;
ret = inflate_table(DISTS, nlen, ndist);
if (ret != 0) {
throw new DeflateException("invalid distances set");
//msg = "invalid distances set";
//mode = BAD;
//break;
}
mode = LEN_;
if (flush == Z_TREES) {
break inf_leave;
}
case LEN_:
mode = LEN;
case LEN:
if (avail_in >= 6 && avail_out >= 258) {
inflate_fast(out);
if (mode == TYPE) {
back = -1;
}
break;
}
back = 0;
while (true) {
here = codes[lencode + BITS(lenbits)];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
if (hereBits <= bits) {
break;
}
if (!PULLBYTE()) {
break inf_leave;
}
}
if (hereOp != 0 && (hereOp & 0xF0) == 0) {
last = here;
lastOp = hereOp;
lastBits = hereBits;
lastVal = hereVal;
while (true) {
here = codes[lencode + lastVal + (BITS(lastBits + lastOp) >>> lastBits)];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
if (lastBits + hereBits <= bits) {
break;
}
if (!PULLBYTE()) {
break inf_leave;
}
}
DROPBITS(lastBits);
back += lastBits;
}
DROPBITS(hereBits);
back += hereBits;
length = hereVal;
if (hereOp == 0) {
mode = LIT;
break;
}
if ((hereOp & 32) != 0) {
back = -1;
mode = TYPE;
break;
}
if ((hereOp & 64) != 0) {
throw new DeflateException("invalid literal/length code");
//msg = "invalid literal/length code";
//mode = BAD;
//break;
}
extra = hereOp & 15;
mode = LENEXT;
case LENEXT:
if (extra != 0) {
if (!NEEDBITS(extra)) {
break inf_leave;
}
length += BITS(extra);
DROPBITS(extra);
back += extra;
}
was = length;
mode = DIST;
case DIST:
while (true) {
here = codes[distcode + BITS(distbits)];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
if (hereBits <= bits) {
break;
}
if (!PULLBYTE()) {
break inf_leave;
}
}
if ((hereOp & 0xF0) == 0) {
last = here;
lastOp = hereOp;
lastBits = hereBits;
lastVal = hereVal;
while (true) {
here = codes[distcode + lastVal + (BITS(lastBits + lastOp) >>> lastBits)];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
if (lastBits + hereBits <= bits) {
break;
}
if (!PULLBYTE()) {
break inf_leave;
}
}
DROPBITS(lastBits);
back += lastBits;
}
DROPBITS(hereBits);
back += hereBits;
if ((hereOp & 64) != 0) {
throw new DeflateException("invalid distance code");
//msg = "invalid distance code";
//mode = BAD;
//break;
}
offset = hereVal;
extra = hereOp & 15;
mode = DISTEXT;
case DISTEXT:
if (extra != 0) {
if (!NEEDBITS(extra)) {
break inf_leave;
}
offset += BITS(extra);
DROPBITS(extra);
back += extra;
}
// INFLATE_STRICT
//if (offset > dmax) {
// throw new DeflateException("invalid distance too far back");
// //msg = "invalid distance too far back";
// //mode = BAD;
// //break;
//}
mode = MATCH;
case MATCH:
if (avail_out == 0) {
break inf_leave;
}
copy = out - avail_out;
if (offset > copy) { // copy from window
copy = offset - copy;
if (copy > whave) {
if (sane) {
throw new DeflateException("invalid distance too far back");
//msg = "invalid distance too far back";
//mode = BAD;
//break;
}
// INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
//copy -= whave;
//if (copy > length) {
// copy = length;
//}
//if (copy > avail_out) {
// copy = avail_out;
//}
//avail_out -= copy;
//length -= copy;
//do {
// next_out[next_out_index++] = 0;
//} while (--copy != 0);
//if (length == 0) {
// mode = LEN;
//}
//break;
}
if (copy > wnext) {
copy -= wnext;
from = wsize - copy;
} else {
from = wnext - copy;
}
if (copy > length) {
copy = length;
}
if (copy > avail_out) {
copy = avail_out;
}
avail_out -= copy;
length -= copy;
do {
next_out[next_out_index++] = window[from++];
} while (--copy != 0);
from += copy;
next_out_index += copy;
} else { // copy from output
from = next_out_index - offset;
copy = length;
if (copy > avail_out) {
copy = avail_out;
}
avail_out -= copy;
length -= copy;
do {
next_out[next_out_index++] = next_out[from++];
} while (--copy != 0);
from += copy;
next_out_index += copy;
}
copy = 0;
if (length == 0) {
mode = LEN;
}
break;
case LIT:
if (avail_out == 0) {
break inf_leave;
}
next_out[next_out_index++] = (byte)length;
avail_out--;
mode = LEN;
break;
case CHECK:
if (wrap != 0) {
if (!NEEDBITS(32)) {
break inf_leave;
}
out -= avail_out;
total_out += out;
total += out;
if (out != 0) {
adler = check = UPDATE(check, next_out, next_out_index - out, out);
}
if ((flags != 0 ? hold : Integer.reverseBytes(hold)) != check) {
throw new DeflateException("incorrect data check");
//msg = "incorrect data check";
//mode = BAD;
//break;
}
if (output != null) {
window_buffer = window_buffer.index(next_out_index - out)
.limit(next_out_index).isPart(!is_last);
output = output.feed(window_buffer);
if (window_buffer.isCont()) {
throw new DecoderException("truncated");
}
}
out = avail_out;
INITBITS();
}
mode = LENGTH;
case LENGTH:
if (wrap != 0 && flags != 0) {
if (!NEEDBITS(32)) {
break inf_leave;
}
if (hold != total) {
throw new DeflateException("incorrect length check");
//msg = "incorrect length check";
//mode = BAD;
//break;
}
INITBITS();
}
mode = DONE;
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
throw new DeflateException(Z_MEM_ERROR);
case SYNC:
default:
throw new DeflateException(Z_STREAM_ERROR);
}
}
// Return from inflate(), updating the total counts and the check value.
// If there was no progress during the inflate() call, return a buffer
// error. Call updatewindow() to create and/or update the window state.
in -= avail_in;
out -= avail_out;
total_in += in;
total_out += out;
total += out;
if (wrap != 0 && out != 0) {
adler = check = UPDATE(check, next_out, next_out_index - out, out);
}
if (wsize != 0 || (out != 0 && mode < BAD && (mode < CHECK || flush != Z_FINISH))) {
if (output != null) {
window_buffer.index(next_out_index - out).limit(next_out_index)
.isPart(avail_in != 0 || !is_last);
output = output.feed(window_buffer);
if (window_buffer.isCont()) {
throw new DecoderException("truncated");
}
compactwindow(next_out_index, out);
} else {
updatewindow(next_out, next_out_index, out);
}
}
data_type = bits + (this.last ? 64 : 0) +
(mode == TYPE ? 128 : 0) +
(mode == LEN_ || mode == COPY_ ? 256 : 0);
if ((in == 0 && out == 0 || flush == Z_FINISH) && ret == Z_OK) {
return true; // Z_BUF_ERROR;
}
if (mode == BAD) {
throw new DeflateException(msg);
}
return false;
}
final void inflate_fast(int start) {
int in; // local next_in_index
int last; // have enough input while in < last
int out; // local next_out_index
int beg; // inflate()'s initial next_out
int end; // while out < end, enough space available
int dmax; // maximum distance from zlib header
int wsize; // window size or zero if not using window
int whave; // valid bytes in the window
int wnext; // window write index
byte[] window; // allocated sliding window, if wsize != 0
int hold; // local hold
int bits; // local bits
int lcode; // local lencode
int dcode; // local distcode
int lmask; // mask for first level of length codes
int dmask; // mask for first level of distance codes
int here; // retrieved table entry
int hereOp;
int hereBits;
int hereVal;
int op; // code bits, operation, extra bits, or window position, window bytes to copy
int len; // match length, unused bytes
int dist; // match distance
int from; // where to copy match from
// copy state to local variables
in = next_in_index;
last = in + (avail_in - 5);
out = next_out_index;
beg = out - (start - avail_out);
end = out + (avail_out - 257);
dmax = this.dmax;
wsize = this.wsize;
whave = this.whave;
wnext = this.wnext;
window = this.window;
hold = this.hold;
bits = this.bits;
lcode = lencode;
dcode = distcode;
lmask = (1 << lenbits) - 1;
dmask = (1 << distbits) - 1;
// decode literals and length/distances until end-of-block or not enough
// input data or output space
decode: do {
if (bits < 15) {
hold += (next_in[in++] & 0xFF) << bits;
bits += 8;
hold += (next_in[in++] & 0xFF) << bits;
bits += 8;
}
here = codes[lcode + (hold & lmask)];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
dolen: do {
op = hereBits;
hold >>>= op;
bits -= op;
op = hereOp;
if (op == 0) { // literal
next_out[out++] = (byte)hereVal;
continue decode;
} else if ((op & 16) != 0) { // length base
len = hereVal;
op &= 15; // number of extra bits
if (op != 0) {
if (bits < op) {
hold += (next_in[in++] & 0xFF) << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
if (bits < 15) {
hold += (next_in[in++] & 0xFF) << bits;
bits += 8;
hold += (next_in[in++] & 0xFF) << bits;
bits += 8;
}
here = codes[dcode + (hold & dmask)];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
dodist: do {
op = hereBits;
hold >>>= op;
bits -= op;
op = hereOp;
if ((op & 16) != 0) { // distance base
dist = hereVal;
op &= 15; // number of extra bits
if (bits < op) {
hold += (next_in[in++] & 0xFF) << bits;
bits += 8;
if (bits < op) {
hold += (next_in[in++] & 0xFF) << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
// INFLATE_STRICT
//if (dist > dmax) {
// throw new DeflateException("invalid distance too far back");
// //msg = "invalid distance too far back";
// //mode = BAD;
// //break decode;
//}
hold >>>= op;
bits -= op;
op = out - beg; // max distance in output
if (dist > op) { // see if copy from window
op = dist - op; // distance back in window
if (op > whave) {
if (sane) {
throw new DeflateException("invalid distance too far back");
//msg = "invalid distance too far back";
//mode = BAD;
//break decode;
}
// INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
//if (len <= op - whave) {
// do {
// next_out[out++] = 0;
// } while (--len != 0);
// continue decode;
//}
//len -= op - whave;
//do {
// next_out[out++] = 0;
//} while (--op > whave);
//if (op == 0) {
// from = out - dist;
// do {
// next_out[out++] = window[from++];
// } while (--len != 0);
// continue decode;
//}
}
from = 0;
if (wnext == 0) { // very common case
from += wsize - op;
if (op < len) { // some from window
len -= op;
do {
next_out[out++] = window[from++];
} while (--op != 0);
from = out - dist; // rest from output
}
} else if (wnext < op) { // wrap around window
from += wsize + wnext - op;
op -= wnext;
if (op < len) { // some from end of window
len -= op;
do {
next_out[out++] = window[from++];
} while (--op != 0);
from = 0;
if (wnext < len) { // some from start of window
op = wnext;
len -= op;
do {
next_out[out++] = window[from++];
} while (--op != 0);
from = out - dist; // rest from output
}
}
} else { // contiguous in window
from += wnext - op;
if (op < len) { // some from window
len -= op;
do {
next_out[out++] = window[from++];
} while (--op != 0);
from = out - dist; // rest from output
}
}
while (len > 2) {
next_out[out++] = next_out[from++];
next_out[out++] = next_out[from++];
next_out[out++] = next_out[from++];
len -= 3;
}
if (len != 0) {
next_out[out++] = next_out[from++];
if (len > 1)
next_out[out++] = next_out[from++];
}
} else {
from = out - dist; // copy direct from output
do { // minimum length is three
next_out[out++] = next_out[from++];
next_out[out++] = next_out[from++];
next_out[out++] = next_out[from++];
len -= 3;
} while (len > 2);
if (len != 0) {
next_out[out++] = next_out[from++];
if (len > 1) {
next_out[out++] = next_out[from++];
}
}
}
continue decode;
} else if ((op & 64) == 0) { // 2nd level distance code
here = codes[dcode + hereVal + (hold & ((1 << op) - 1))];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
continue dodist;
} else {
throw new DeflateException("invalid distance code");
//msg = "invalid distance code";
//mode = BAD;
//break decode;
}
} while (true);
} else if ((op & 64) == 0) { // 2nd level length code
here = codes[lcode + hereVal + (hold & ((1 << op) - 1))];
hereOp = (here >>> 24) & 0xFF;
hereBits = (here >>> 16) & 0xFF;
hereVal = here & 0xFFFF;
continue dolen;
} else if ((op & 32) != 0) { // end-of-block
mode = TYPE;
break decode;
} else {
throw new DeflateException("invalid literal/length code");
//msg = "invalid literal/length code";
//mode = BAD;
//break decode;
}
} while (true);
} while (in < last && out < end);
// return unused bytes (on entry, bits < 8, so in won't go too far back)
len = bits >>> 3;
in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
// update state and return
next_in_index = in;
next_out_index = out;
avail_in = in < last ? 5 + (last - in) : 5 - (in - last);
avail_out = out < end ? 257 + (end - out) : 257 - (out - end);
this.hold = hold;
this.bits = bits;
}
// Return state with length and distance decoding tables and index sizes set to
// fixed code decoding.
final void fixedtables() {
codes = fixed;
lencode = lenfix;
lenbits = 9;
distcode = distfix;
distbits = 5;
}
// Build a set of tables to decode the provided canonical Huffman code.
final int inflate_table(int type, int offset, int length) {
int len; // a code's length in bits
int sym; // index of code symbols
int min, max; // minimum and maximum code lengths
int root; // number of index bits for root table
int curr; // number of index bits for current table
int drop; // code bits to drop for sub-table
int left; // number of prefix codes available
int used; // code entries in table used
int huff; // Huffman code
int incr; // for incrementing code, index
int fill; // index for replicating entries
int low; // low bits for current root entry
int mask; // mask for low root bits
int here; // table entry for duplication
int hereOp;
int hereBits;
int hereVal;
int next; // next available space in codes table
short[] base; // base value table to use
int base_index;
short[] extra; // extra bits table to use
int extra_index;
int end; // use base and extra for symbol > end
short[] count = new short[MAXBITS + 1]; // number of codes of each length
short[] offs = new short[MAXBITS + 1]; // offsets in table for each length
// Process a set of code lengths to create a canonical Huffman code. The
// code lengths are lens[0..length-1]. Each length corresponds to the
// symbols 0..length-1. The Huffman code is generated by first sorting the
// symbols by length from short to long, and retaining the symbol order
// for codes with equal lengths. Then the code starts with all zero bits
// for the first code of the shortest length, and the codes are integer
// increments for the same length, and zeros are appended as the length
// increases. For the deflate format, these bits are stored backwards
// from their more natural integer increment ordering, and so when the
// decoding tables are built in the large loop below, the integer codes
// are incremented backwards.
//
// This routine assumes, but does not check, that all of the entries in
// lens[] are in the range 0..MAXBITS. The caller must assure this.
// 1..MAXBITS is interpreted as that code length. zero means that that
// symbol does not occur in this code.
//
// The codes are sorted by computing a count of codes for each length,
// creating from that a table of starting indices for each length in the
// sorted table, and then entering the symbols in order in the sorted
// table. The sorted table is work[], with that space being provided by
// the caller.
//
// The length counts are used for other purposes as well, i.e. finding
// the minimum and maximum length codes, determining if there are any
// codes at all, checking for a valid set of lengths, and looking ahead
// at length counts to determine sub-table sizes when building the
// decoding tables.
// accumulate lengths for codes (assumes lens[] all in 0..MAXBITS)
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < length; sym++) {
count[lens[offset + sym]]++;
}
// bound code lengths, force root to be within code lengths
root = type == DISTS ? distbits : lenbits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] != 0) {
break;
}
}
if (root > max) {
root = max;
}
if (max == 0) { // no symbols to code at all
hereOp = 64; // invalid code marker
hereBits = 1;
hereVal = 0;
here = code(hereOp, hereBits, hereVal);
codes[this.next++] = here; // make a table to force an error
codes[this.next++] = here;
if (type == DISTS) {
distbits = 1;
} else {
lenbits = 1;
}
return 0; // no symbols, but wait for decoding to report error
}
for (min = 1; min < max; min++) {
if (count[min] != 0) {
break;
}
}
if (root < min) {
root = min;
}
// check for an over-subscribed or incomplete set of lengths
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1; // over-subscribed
}
}
if (left > 0 && (type == CODES || max != 1)) {
return -1; // incomplete set
}
// generate offsets into symbol table for each length for sorting
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = (short)(offs[len] + count[len]);
}
// sort symbols by length, by symbol order within each length
for (sym = 0; sym < length; sym++) {
if (lens[offset + sym] != 0) {
work[offs[lens[offset + sym]]++] = (short)sym;
}
}
// Create and fill in decoding tables. In this loop, the table being
// filled is at next and has curr index bits. The code being used is huff
// with length len. That code is converted to an index by dropping drop
// bits off of the bottom. For codes where len is less than drop + curr,
// those top drop + curr - len bits are incremented through all values to
// fill the table with replicated entries.
//
// root is the number of index bits for the root table. When len exceeds
// root, sub-tables are created pointed to by the root entry with an index
// of the low root bits of huff. This is saved in low to check for when a
// new sub-table should be started. drop is zero when the root table is
// being filled, and drop is root when sub-tables are being filled.
//
// When a new sub-table is needed, it is necessary to look ahead in the
// code lengths to determine what size sub-table is needed. The length
// counts are used for this, and so count[] is decremented as codes are
// entered in the tables.
//
// used keeps track of how many table entries have been allocated from the
// provided *table space. It is checked for LENS and DIST tables against
// the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
// the initial root table size constants. See the comments in inftrees.h
// for more information.
//
// sym increments through all symbols, and the loop terminates when
// all codes of length max, i.e. all codes, have been processed. This
// routine permits incomplete codes, so another loop after this one fills
// in the rest of the decoding tables with invalid code markers.
// set up for code type
switch (type) {
case CODES:
base = extra = work; // dummy value--not used
base_index = extra_index = 0;
end = 19;
break;
case LENS:
base = lbase;
base_index = -257;
extra = lext;
extra_index = -257;
end = 256;
break;
default: // DISTS
base = dbase;
base_index = 0;
extra = dext;
extra_index = 0;
end = -1;
}
// initialize state for loop
huff = 0; // starting code
sym = 0; // starting code symbol
len = min; // starting code length
next = this.next; // current table to fill in
curr = root; // current table index bits
drop = 0; // current bits to drop from code for index
low = -1; // trigger new sub-table when len > root
used = 1 << root; // use root table entries
mask = used - 1; // mask for comparing low
// check available table space
if (type == LENS && used > ENOUGH_LENS || type == DISTS && used > ENOUGH_DISTS) {
return 1;
}
// process all codes and make table entries
while (true) {
// create table entry
hereBits = len - drop;
if (work[sym] < end) {
hereOp = 0;
hereVal = work[sym];
} else if (work[sym] > end) {
hereOp = extra[extra_index + work[sym]];
hereVal = base[base_index + work[sym]];
} else {
hereOp = 32 + 64; // end of block
hereVal = 0;
}
here = code(hereOp, hereBits, hereVal);
// replicate for those indices with low len bits equal to huff
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; // save offset to next table
do {
fill -= incr;
codes[next + (huff >>> drop) + fill] = here;
} while (fill != 0);
// backwards increment the len-bit code huff
incr = 1 << (len - 1);
while ((huff & incr) != 0) {
incr >>>= 1;
}
if (incr != 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
// go to next symbol, update count, len
sym++;
if (--count[len] == 0) {
if (len == max) {
break;
}
len = lens[offset + work[sym]];
}
// create new sub-table if needed
if (len > root && (huff & mask) != low) {
// if first time, transition to sub-tables
if (drop == 0) {
drop = root;
}
// increment past last table
next += min; // here min is 1 << curr
// determine length of next table
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) {
break;
}
curr++;
left <<= 1;
}
// check for enough space
used += 1 << curr;
if (type == LENS && used > ENOUGH_LENS || type == DISTS && used > ENOUGH_DISTS) {
return 1;
}
// point entry in root table to sub-table
low = huff & mask;
codes[this.next + low] = code(curr, root, next - this.next);
}
}
// fill in remaining table entry if code is incomplete (guaranteed to have
// at most one remaining entry, since if the code is incomplete, the
// maximum code length that was allowed to get this far is one bit)
if (huff != 0) {
hereOp = 64; // invalid code marker
hereBits = len - drop;
hereVal = 0;
here = code(hereOp, hereBits, hereVal);
codes[next + huff] = here;
}
// set return parameters
this.next += used;
if (type == DISTS) {
distbits = root;
} else {
lenbits = root;
}
return 0;
}
final void compactwindow(int end, int copy) {
if (end > wsize) {
System.arraycopy(window, end - wsize, window, 0, wsize);
wnext = wsize;
} else {
wnext = end;
}
whave = wnext;
}
// Update the window with the last wsize (normally 32K) bytes written before
// returning. If window does not exist yet, create it. This is only called
// when a window is already in use, or when output has been written during this
// inflate call, but the end of the deflate stream has not been reached yet.
// It is also called to create a window for dictionary data when a dictionary
// is loaded.
//
// Providing output buffers larger than 32K to inflate() should provide a speed
// advantage, since only the last 32K of output is copied to the sliding window
// upon return from inflate(), and since all distances after the first 32K of
// output will fall in the output data, making match copies simpler and faster.
// The advantage may be dependent on the size of the processor's data caches.
final void updatewindow(byte[] output, int end, int copy) {
int dist;
// if it hasn't been done already, allocate space for the window
if (window == null) {
window = new byte[1 << wbits];
window_buffer = Binary.inputBuffer(window);
}
// if window not in use yet, initialize
if (wsize == 0) {
wsize = 1 << wbits;
wnext = 0;
whave = 0;
}
// copy wsize or less output bytes into the circular window
if (copy >= wsize) {
System.arraycopy(output, end - wsize, window, 0, wsize);
wnext = 0;
whave = wsize;
} else {
dist = wsize - wnext;
if (dist > copy) {
dist = copy;
}
System.arraycopy(output, end - copy, window, wnext, dist);
copy -= dist;
if (copy != 0) {
System.arraycopy(output, end - copy, window, 0, copy);
wnext = copy;
whave = wsize;
} else {
wnext += dist;
if (wnext == wsize) {
wnext = 0;
}
if (whave < wsize) {
whave += dist;
}
}
}
}
// Clear the input bit accumulator
final void INITBITS() {
hold = 0;
bits = 0;
}
// Get a byte of input into the bit accumulator, or return false
// if there is no input available.
final boolean PULLBYTE() {
if (avail_in == 0) {
return false;
}
avail_in--;
hold += (next_in[next_in_index++] & 0xFF) << bits;
bits += 8;
return true;
}
// Assure that there are at least n bits in the bit accumulator. If there is
// not enough available input to do that, then return false.
final boolean NEEDBITS(int n) {
while (bits < n) {
if (!PULLBYTE()) {
return false;
}
}
return true;
}
// Return the low n bits of the bit accumulator (n < 16)
final int BITS(int n) {
return hold & ((1 << n) - 1);
}
// Remove n bits from the bit accumulator
final void DROPBITS(int n) {
hold >>>= n;
bits -= n;
}
// Remove zero to seven bits as needed to go to a byte boundary
final void BYTEBITS() {
hold >>>= bits & 7;
bits -= bits & 7;
}
// check function to use adler32() for zlib or crc32() for gzip
final int UPDATE(int check, byte[] buf, int off, int len) {
if (wrap == 1) {
return adler32(check, buf, off, len);
} else if (wrap == 2) {
return crc32(check, buf, off, len);
} else {
return check;
}
}
// check for header crc
final void CRC2(int check, byte[] hbuf, int word) {
hbuf[0] = (byte)word;
hbuf[1] = (byte)(word >>> 8);
check = crc32(check, hbuf, 0, 2);
}
final void CRC4(int check, byte[] hbuf, int word) {
hbuf[0] = (byte)word;
hbuf[1] = (byte)(word >> 8);
hbuf[2] = (byte)(word >> 16);
hbuf[3] = (byte)(word >> 24);
check = crc32(check, hbuf, 0, 4);
}
static int code(int op, int bits, int val) {
return ((op & 0xFF) << 24) | ((bits & 0xFF) << 16) | (val & 0xFFFF);
}
// Allowed flush values
public static final int Z_NO_FLUSH = 0;
public static final int Z_PARTIAL_FLUSH = 1;
public static final int Z_SYNC_FLUSH = 2;
public static final int Z_FULL_FLUSH = 3;
public static final int Z_FINISH = 4;
public static final int Z_BLOCK = 5;
public static final int Z_TREES = 6;
// Return codes for the compression/decompression functions. Negative values
// are errors, positive values are used for special but normal events.
public static final int Z_OK = 0;
public static final int Z_STREAM_END = 1;
public static final int Z_NEED_DICT = 2;
public static final int Z_ERRNO = -1;
public static final int Z_STREAM_ERROR = -2;
public static final int Z_DATA_ERROR = -3;
public static final int Z_MEM_ERROR = -4;
public static final int Z_BUF_ERROR = -5;
public static final int Z_VERSION_ERROR = -6;
// Wrappers
public static final int Z_NO_WRAP = 0;
public static final int Z_WRAP_ZLIB = 1;
public static final int Z_WRAP_GZIP = 2;
// Default windowBits for decompression
public static final int DEF_WBITS = 15;
// The deflate compression method
static final int Z_DEFLATED = 8;
// Maximum size of the dynamic table. The maximum number of code structures is
// 1444, which is the sum of 852 for literal/length codes and 592 for distance
// codes. These values were found by exhaustive searches using the program
// examples/enough.c found in the zlib distribtution. The arguments to that
// program are the number of symbols, the initial root table size, and the
// maximum bit length of a code. "enough 286 9 15" for literal/length codes
// returns returns 852, and "enough 30 6 15" for distance codes returns 592.
// The initial root table size (9 or 6) is found in the fifth argument of the
// inflate_table() calls in inflate.c and infback.c. If the root table size is
// changed, then these maximum sizes would be need to be recalculated and
// updated.
static final int ENOUGH_LENS = 852;
static final int ENOUGH_DISTS = 592;
static final int ENOUGH = ENOUGH_LENS + ENOUGH_DISTS;
static final int HEAD = 0; // i: waiting for magic header
static final int FLAGS = 1; // i: waiting for method and flags (gzip)
static final int TIME = 2; // i: waiting for modification time (gzip)
static final int OS = 3; // i: waiting for extra flags and operating system (gzip)
static final int EXLEN = 4; // i: waiting for extra length (gzip)
static final int EXTRA = 5; // i: waiting for extra bytes (gzip)
static final int NAME = 6; // i: waiting for end of file name (gzip)
static final int COMMENT = 7; // i: waiting for end of comment (gzip)
static final int HCRC = 8; // i: waiting for header crc (gzip)
static final int DICTID = 9; // i: waiting for dictionary check value
static final int DICT = 10; // waiting for inflateSetDictionary() call
static final int TYPE = 11; // i: waiting for type bits, including last-flag bit
static final int TYPEDO = 12; // i: same, but skip check to exit inflate on new block
static final int STORED = 13; // i: waiting for stored size (length and complement)
static final int COPY_ = 14; // i/o: same as COPY below, but only first time in
static final int COPY = 15; // i/o: waiting for input or output to copy stored block
static final int TABLE = 16; // i: waiting for dynamic block table lengths
static final int LENLENS = 17; // i: waiting for code length code lengths
static final int CODELENS = 18; // i: waiting for length/lit and distance code lengths
static final int LEN_ = 19; // i: same as LEN below, but only first time in
static final int LEN = 20; // i: waiting for length/lit/eob code
static final int LENEXT = 21; // i: waiting for length extra bits
static final int DIST = 22; // i: waiting for distance code
static final int DISTEXT = 23; // i: waiting for distance extra bits
static final int MATCH = 24; // o: waiting for output space to copy string
static final int LIT = 25; // o: waiting for output space to write literal
static final int CHECK = 26; // i: waiting for 32-bit check value
static final int LENGTH = 27; // i: waiting for 32-bit length (gzip)
static final int DONE = 28; // finished check, done -- remain here until reset
static final int BAD = 29; // got a data error -- remain here until reset
static final int MEM = 30; // got an inflate() memory error -- remain here until reset
static final int SYNC = 31; // looking for synchronization bytes to restart inflate()
// Type of code to build for inflate_table()
static final int CODES = 0;
static final int LENS = 1;
static final int DISTS = 2;
static final int MAXBITS = 15;
// permutation of code lengths
static final short[] order = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
};
// Length codes 257..285 base
static final short[] lbase = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
};
// Length codes 257..285 extra
static final short[] lext = {
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
};
// Distance codes 0..29 base
static final short[] dbase = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
};
// Distance codes 0..29 extra
static final short[] dext = {
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
};
static final int lenfix = 0;
static final int distfix = 512;
static final int[] fixed = {
// 512 lencodes
code(96,7,0), code(0,8,80), code(0,8,16), code(20,8,115),
code(18,7,31), code(0,8,112), code(0,8,48), code(0,9,192),
code(16,7,10), code(0,8,96), code(0,8,32), code(0,9,160),
code(0,8,0), code(0,8,128), code(0,8,64), code(0,9,224),
code(16,7,6), code(0,8,88), code(0,8,24), code(0,9,144),
code(19,7,59), code(0,8,120), code(0,8,56), code(0,9,208),
code(17,7,17), code(0,8,104), code(0,8,40), code(0,9,176),
code(0,8,8), code(0,8,136), code(0,8,72), code(0,9,240),
code(16,7,4), code(0,8,84), code(0,8,20), code(21,8,227),
code(19,7,43), code(0,8,116), code(0,8,52), code(0,9,200),
code(17,7,13), code(0,8,100), code(0,8,36), code(0,9,168),
code(0,8,4), code(0,8,132), code(0,8,68), code(0,9,232),
code(16,7,8), code(0,8,92), code(0,8,28), code(0,9,152),
code(20,7,83), code(0,8,124), code(0,8,60), code(0,9,216),
code(18,7,23), code(0,8,108), code(0,8,44), code(0,9,184),
code(0,8,12), code(0,8,140), code(0,8,76), code(0,9,248),
code(16,7,3), code(0,8,82), code(0,8,18), code(21,8,163),
code(19,7,35), code(0,8,114), code(0,8,50), code(0,9,196),
code(17,7,11), code(0,8,98), code(0,8,34), code(0,9,164),
code(0,8,2), code(0,8,130), code(0,8,66), code(0,9,228),
code(16,7,7), code(0,8,90), code(0,8,26), code(0,9,148),
code(20,7,67), code(0,8,122), code(0,8,58), code(0,9,212),
code(18,7,19), code(0,8,106), code(0,8,42), code(0,9,180),
code(0,8,10), code(0,8,138), code(0,8,74), code(0,9,244),
code(16,7,5), code(0,8,86), code(0,8,22), code(64,8,0),
code(19,7,51), code(0,8,118), code(0,8,54), code(0,9,204),
code(17,7,15), code(0,8,102), code(0,8,38), code(0,9,172),
code(0,8,6), code(0,8,134), code(0,8,70), code(0,9,236),
code(16,7,9), code(0,8,94), code(0,8,30), code(0,9,156),
code(20,7,99), code(0,8,126), code(0,8,62), code(0,9,220),
code(18,7,27), code(0,8,110), code(0,8,46), code(0,9,188),
code(0,8,14), code(0,8,142), code(0,8,78), code(0,9,252),
code(96,7,0), code(0,8,81), code(0,8,17), code(21,8,131),
code(18,7,31), code(0,8,113), code(0,8,49), code(0,9,194),
code(16,7,10), code(0,8,97), code(0,8,33), code(0,9,162),
code(0,8,1), code(0,8,129), code(0,8,65), code(0,9,226),
code(16,7,6), code(0,8,89), code(0,8,25), code(0,9,146),
code(19,7,59), code(0,8,121), code(0,8,57), code(0,9,210),
code(17,7,17), code(0,8,105), code(0,8,41), code(0,9,178),
code(0,8,9), code(0,8,137), code(0,8,73), code(0,9,242),
code(16,7,4), code(0,8,85), code(0,8,21), code(16,8,258),
code(19,7,43), code(0,8,117), code(0,8,53), code(0,9,202),
code(17,7,13), code(0,8,101), code(0,8,37), code(0,9,170),
code(0,8,5), code(0,8,133), code(0,8,69), code(0,9,234),
code(16,7,8), code(0,8,93), code(0,8,29), code(0,9,154),
code(20,7,83), code(0,8,125), code(0,8,61), code(0,9,218),
code(18,7,23), code(0,8,109), code(0,8,45), code(0,9,186),
code(0,8,13), code(0,8,141), code(0,8,77), code(0,9,250),
code(16,7,3), code(0,8,83), code(0,8,19), code(21,8,195),
code(19,7,35), code(0,8,115), code(0,8,51), code(0,9,198),
code(17,7,11), code(0,8,99), code(0,8,35), code(0,9,166),
code(0,8,3), code(0,8,131), code(0,8,67), code(0,9,230),
code(16,7,7), code(0,8,91), code(0,8,27), code(0,9,150),
code(20,7,67), code(0,8,123), code(0,8,59), code(0,9,214),
code(18,7,19), code(0,8,107), code(0,8,43), code(0,9,182),
code(0,8,11), code(0,8,139), code(0,8,75), code(0,9,246),
code(16,7,5), code(0,8,87), code(0,8,23), code(64,8,0),
code(19,7,51), code(0,8,119), code(0,8,55), code(0,9,206),
code(17,7,15), code(0,8,103), code(0,8,39), code(0,9,174),
code(0,8,7), code(0,8,135), code(0,8,71), code(0,9,238),
code(16,7,9), code(0,8,95), code(0,8,31), code(0,9,158),
code(20,7,99), code(0,8,127), code(0,8,63), code(0,9,222),
code(18,7,27), code(0,8,111), code(0,8,47), code(0,9,190),
code(0,8,15), code(0,8,143), code(0,8,79), code(0,9,254),
code(96,7,0), code(0,8,80), code(0,8,16), code(20,8,115),
code(18,7,31), code(0,8,112), code(0,8,48), code(0,9,193),
code(16,7,10), code(0,8,96), code(0,8,32), code(0,9,161),
code(0,8,0), code(0,8,128), code(0,8,64), code(0,9,225),
code(16,7,6), code(0,8,88), code(0,8,24), code(0,9,145),
code(19,7,59), code(0,8,120), code(0,8,56), code(0,9,209),
code(17,7,17), code(0,8,104), code(0,8,40), code(0,9,177),
code(0,8,8), code(0,8,136), code(0,8,72), code(0,9,241),
code(16,7,4), code(0,8,84), code(0,8,20), code(21,8,227),
code(19,7,43), code(0,8,116), code(0,8,52), code(0,9,201),
code(17,7,13), code(0,8,100), code(0,8,36), code(0,9,169),
code(0,8,4), code(0,8,132), code(0,8,68), code(0,9,233),
code(16,7,8), code(0,8,92), code(0,8,28), code(0,9,153),
code(20,7,83), code(0,8,124), code(0,8,60), code(0,9,217),
code(18,7,23), code(0,8,108), code(0,8,44), code(0,9,185),
code(0,8,12), code(0,8,140), code(0,8,76), code(0,9,249),
code(16,7,3), code(0,8,82), code(0,8,18), code(21,8,163),
code(19,7,35), code(0,8,114), code(0,8,50), code(0,9,197),
code(17,7,11), code(0,8,98), code(0,8,34), code(0,9,165),
code(0,8,2), code(0,8,130), code(0,8,66), code(0,9,229),
code(16,7,7), code(0,8,90), code(0,8,26), code(0,9,149),
code(20,7,67), code(0,8,122), code(0,8,58), code(0,9,213),
code(18,7,19), code(0,8,106), code(0,8,42), code(0,9,181),
code(0,8,10), code(0,8,138), code(0,8,74), code(0,9,245),
code(16,7,5), code(0,8,86), code(0,8,22), code(64,8,0),
code(19,7,51), code(0,8,118), code(0,8,54), code(0,9,205),
code(17,7,15), code(0,8,102), code(0,8,38), code(0,9,173),
code(0,8,6), code(0,8,134), code(0,8,70), code(0,9,237),
code(16,7,9), code(0,8,94), code(0,8,30), code(0,9,157),
code(20,7,99), code(0,8,126), code(0,8,62), code(0,9,221),
code(18,7,27), code(0,8,110), code(0,8,46), code(0,9,189),
code(0,8,14), code(0,8,142), code(0,8,78), code(0,9,253),
code(96,7,0), code(0,8,81), code(0,8,17), code(21,8,131),
code(18,7,31), code(0,8,113), code(0,8,49), code(0,9,195),
code(16,7,10), code(0,8,97), code(0,8,33), code(0,9,163),
code(0,8,1), code(0,8,129), code(0,8,65), code(0,9,227),
code(16,7,6), code(0,8,89), code(0,8,25), code(0,9,147),
code(19,7,59), code(0,8,121), code(0,8,57), code(0,9,211),
code(17,7,17), code(0,8,105), code(0,8,41), code(0,9,179),
code(0,8,9), code(0,8,137), code(0,8,73), code(0,9,243),
code(16,7,4), code(0,8,85), code(0,8,21), code(16,8,258),
code(19,7,43), code(0,8,117), code(0,8,53), code(0,9,203),
code(17,7,13), code(0,8,101), code(0,8,37), code(0,9,171),
code(0,8,5), code(0,8,133), code(0,8,69), code(0,9,235),
code(16,7,8), code(0,8,93), code(0,8,29), code(0,9,155),
code(20,7,83), code(0,8,125), code(0,8,61), code(0,9,219),
code(18,7,23), code(0,8,109), code(0,8,45), code(0,9,187),
code(0,8,13), code(0,8,141), code(0,8,77), code(0,9,251),
code(16,7,3), code(0,8,83), code(0,8,19), code(21,8,195),
code(19,7,35), code(0,8,115), code(0,8,51), code(0,9,199),
code(17,7,11), code(0,8,99), code(0,8,35), code(0,9,167),
code(0,8,3), code(0,8,131), code(0,8,67), code(0,9,231),
code(16,7,7), code(0,8,91), code(0,8,27), code(0,9,151),
code(20,7,67), code(0,8,123), code(0,8,59), code(0,9,215),
code(18,7,19), code(0,8,107), code(0,8,43), code(0,9,183),
code(0,8,11), code(0,8,139), code(0,8,75), code(0,9,247),
code(16,7,5), code(0,8,87), code(0,8,23), code(64,8,0),
code(19,7,51), code(0,8,119), code(0,8,55), code(0,9,207),
code(17,7,15), code(0,8,103), code(0,8,39), code(0,9,175),
code(0,8,7), code(0,8,135), code(0,8,71), code(0,9,239),
code(16,7,9), code(0,8,95), code(0,8,31), code(0,9,159),
code(20,7,99), code(0,8,127), code(0,8,63), code(0,9,223),
code(18,7,27), code(0,8,111), code(0,8,47), code(0,9,191),
code(0,8,15), code(0,8,143), code(0,8,79), code(0,9,255),
// 32 distcodes
code(16,5,1), code(23,5,257), code(19,5,17), code(27,5,4097),
code(17,5,5), code(25,5,1025), code(21,5,65), code(29,5,16385),
code(16,5,3), code(24,5,513), code(20,5,33), code(28,5,8193),
code(18,5,9), code(26,5,2049), code(22,5,129), code(64,5,0),
code(16,5,2), code(23,5,385), code(19,5,25), code(27,5,6145),
code(17,5,7), code(25,5,1537), code(21,5,97), code(29,5,24577),
code(16,5,4), code(24,5,769), code(20,5,49), code(28,5,12289),
code(18,5,13), code(26,5,3073), code(22,5,193), code(64,5,0)
};
}
|
0 | java-sources/ai/swim/swim-deflate/3.10.0/swim | java-sources/ai/swim/swim-deflate/3.10.0/swim/deflate/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* DEFLATE compression codec.
*/
package swim.deflate;
|
0 | java-sources/ai/swim/swim-dynamic | java-sources/ai/swim/swim-dynamic/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Language binding interfaces.
*/
module swim.dynamic {
requires swim.collections;
exports swim.dynamic;
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/AbstractHostObjectType.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
import java.util.Collection;
import java.util.List;
import swim.collections.HashTrieMap;
public abstract class AbstractHostObjectType<T> extends AbstractHostType<T> implements HostObjectType<T> {
@Override
public abstract HostMember<? super T> getOwnMember(Bridge bridge, T self, String key);
@Override
public abstract Collection<HostMember<? super T>> ownMembers(Bridge bridge, T self);
@Override
public HostMember<? super T> getMember(Bridge bridge, T self, String key) {
HostMember<? super T> member = getOwnMember(bridge, self, key);
if (member == null) {
final List<HostType<? super T>> baseTypes = baseTypes();
for (int i = baseTypes.size() - 1; i >= 0; i -= 1) {
final HostType<? super T> baseType = baseTypes.get(i);
if (baseType instanceof HostObjectType<?>) {
member = ((HostObjectType<? super T>) baseType).getOwnMember(bridge, self, key);
if (member != null) {
break;
}
}
}
}
return member;
}
@Override
public Collection<HostMember<? super T>> members(Bridge bridge, T self) {
HashTrieMap<String, HostMember<? super T>> members = HashTrieMap.empty();
final List<HostType<? super T>> baseTypes = baseTypes();
for (int i = 0, n = baseTypes.size(); i < n; i += 1) {
final HostType<? super T> baseType = baseTypes.get(i);
if (baseType instanceof HostObjectType<?>) {
for (HostMember<? super T> baseMember : ((HostObjectType<? super T>) baseType).ownMembers(bridge, self)) {
members = members.updated(baseMember.key(), baseMember);
}
}
}
for (HostMember<? super T> member : ownMembers(bridge, self)) {
members = members.updated(member.key(), member);
}
return members.values();
}
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/AbstractHostType.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
import java.util.Collection;
import java.util.List;
import swim.collections.HashTrieMap;
public abstract class AbstractHostType<T> implements HostType<T> {
@Override
public String typeName() {
return hostClass().getSimpleName();
}
@Override
public abstract Class<?> hostClass();
@Override
public boolean isBuiltin() {
return false;
}
@Override
public abstract HostType<? super T> superType();
@Override
public abstract List<HostType<? super T>> baseTypes();
@Override
public boolean inheritsType(HostType<?> superType) {
if (superType == this) {
return true;
} else {
final List<HostType<? super T>> baseTypes = baseTypes();
for (int i = baseTypes.size() - 1; i >= 0; i -= 1) {
final HostType<? super T> baseType = baseTypes.get(i);
if (superType == baseType) {
return true;
}
}
}
return false;
}
@Override
public abstract HostStaticMember getOwnStaticMember(Bridge bridge, String key);
@Override
public abstract Collection<HostStaticMember> ownStaticMembers(Bridge bridge);
@Override
public HostStaticMember getStaticMember(Bridge bridge, String key) {
HostStaticMember staticMember = getOwnStaticMember(bridge, key);
if (staticMember == null) {
final List<HostType<? super T>> baseTypes = baseTypes();
for (int i = baseTypes.size() - 1; i >= 0; i -= 1) {
final HostType<? super T> baseType = baseTypes.get(i);
staticMember = baseType.getOwnStaticMember(bridge, key);
if (staticMember != null) {
break;
}
}
}
return staticMember;
}
@Override
public Collection<HostStaticMember> staticMembers(Bridge bridge) {
HashTrieMap<String, HostStaticMember> staticMembers = HashTrieMap.empty();
final List<HostType<? super T>> baseTypes = baseTypes();
for (int i = 0, n = baseTypes.size(); i < n; i += 1) {
final HostType<? super T> baseType = baseTypes.get(i);
for (HostStaticMember baseStaticMember : baseType.ownStaticMembers(bridge)) {
staticMembers = staticMembers.updated(baseStaticMember.key(), baseStaticMember);
}
}
for (HostStaticMember staticMember : ownStaticMembers(bridge)) {
staticMembers = staticMembers.updated(staticMember.key(), staticMember);
}
return staticMembers.values();
}
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/Bridge.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
import java.util.Collection;
/**
* Interface between a guest language execution environment and a host runtime.
*/
public abstract class Bridge {
public abstract HostRuntime hostRuntime();
public abstract String guestLanguage();
public abstract HostLibrary getHostLibrary(String libraryName);
public abstract Collection<HostLibrary> hostLibraries();
public abstract HostPackage getHostPackage(String packageName);
public abstract Collection<HostPackage> hostPackages();
public abstract HostType<?> getHostType(Class<?> typeClass);
public abstract Collection<HostType<?>> hostTypes();
public abstract <T> HostType<? super T> hostType(T hostValue);
public abstract Object hostToGuest(Object hostValue);
public abstract Object guestToHost(Object guestValue);
public abstract boolean guestCanExecute(Object guestFunction);
public abstract Object guestExecute(Object guestFunction, Object... arguments);
public abstract void guestExecuteVoid(Object guestFunction, Object... arguments);
public abstract boolean guestCanInvokeMember(Object guestObject, String member);
public abstract Object guestInvokeMember(Object guestObject, String member, Object... arguments);
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/BridgeException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
public class BridgeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public BridgeException(String message, Throwable cause) {
super(message, cause);
}
public BridgeException(String message) {
super(message);
}
public BridgeException(Throwable cause) {
super(cause);
}
public BridgeException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/BridgeGuest.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
/**
* A host object that wraps a guest value and its dynamic bridge. Used as a
* base class for strongly typed host objects that wrap guest values, such as
* host functional interface implementations that invoke guest functions.
*/
public class BridgeGuest implements GuestWrapper {
protected final Bridge bridge;
protected final Object guest;
public BridgeGuest(Bridge bridge, Object guest) {
this.bridge = bridge;
this.guest = guest;
}
public final Bridge bridge() {
return this.bridge;
}
@Override
public final Object unwrap() {
return this.guest;
}
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/GuestWrapper.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
/**
* A host object that wraps a guest value.
*/
public interface GuestWrapper {
/**
* Returns the guest value that this host object wraps.
*/
Object unwrap();
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/HostArray.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
/**
* A host object that has a dynamic array type descriptor.
*/
public interface HostArray extends HostValue {
HostArrayType<? extends Object> dynamicType();
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/HostArrayType.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
/**
* A dynamic array type descriptor for a host type.
*/
public interface HostArrayType<T> extends HostType<T> {
long elementCount(Bridge bridge, T self);
Object getElement(Bridge bridge, T self, long index);
void setElement(Bridge bridge, T self, long index, Object value);
boolean removeElement(Bridge bridge, T self, long index);
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/HostClassType.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
/**
* A dynamic object type descriptor for an instantiable host type.
*/
public interface HostClassType<T> extends HostObjectType<T> {
HostConstructor constructor(Bridge bridge);
}
|
0 | java-sources/ai/swim/swim-dynamic/3.10.0/swim | java-sources/ai/swim/swim-dynamic/3.10.0/swim/dynamic/HostConstructor.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.dynamic;
/**
* A dynamically typed constructor descriptor for a host type.
*/
public interface HostConstructor {
Object newInstance(Bridge bridge, Object... arguments);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.