index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/swim/swim-auth/3.10.0/swim | java-sources/ai/swim/swim-auth/3.10.0/swim/auth/AuthenticatorKernel.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.auth;
import swim.api.auth.Authenticator;
import swim.api.auth.AuthenticatorDef;
import swim.kernel.KernelProxy;
import swim.structure.Item;
import swim.structure.Value;
public class AuthenticatorKernel extends KernelProxy {
final double kernelPriority;
public AuthenticatorKernel(double kernelPriority) {
this.kernelPriority = kernelPriority;
}
public AuthenticatorKernel() {
this(KERNEL_PRIORITY);
}
@Override
public final double kernelPriority() {
return this.kernelPriority;
}
@Override
public AuthenticatorDef defineAuthenticator(Item authenticatorConfig) {
AuthenticatorDef authenticatorDef = GoogleIdAuthenticatorDef.form().cast(authenticatorConfig);
if (authenticatorDef == null) {
authenticatorDef = OpenIdAuthenticatorDef.form().cast(authenticatorConfig);
}
return authenticatorDef != null ? authenticatorDef : super.defineAuthenticator(authenticatorConfig);
}
@Override
public Authenticator createAuthenticator(AuthenticatorDef authenticatorDef, ClassLoader classLoader) {
if (authenticatorDef instanceof GoogleIdAuthenticatorDef) {
return new GoogleIdAuthenticator((GoogleIdAuthenticatorDef) authenticatorDef);
} else if (authenticatorDef instanceof OpenIdAuthenticatorDef) {
return new OpenIdAuthenticator((OpenIdAuthenticatorDef) authenticatorDef);
} else {
return super.createAuthenticator(authenticatorDef, classLoader);
}
}
private static final double KERNEL_PRIORITY = 0.9;
public static AuthenticatorKernel fromValue(Value moduleConfig) {
final Value header = moduleConfig.getAttr("kernel");
final String kernelClassName = header.get("class").stringValue(null);
if (kernelClassName == null || AuthenticatorKernel.class.getName().equals(kernelClassName)) {
final double kernelPriority = header.get("priority").doubleValue(KERNEL_PRIORITY);
return new AuthenticatorKernel(kernelPriority);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-auth/3.10.0/swim | java-sources/ai/swim/swim-auth/3.10.0/swim/auth/GoogleIdAuthenticator.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.auth;
import swim.api.auth.AbstractAuthenticator;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.policy.PolicyDirective;
import swim.collections.FingerTrieSeq;
import swim.collections.HashTrieSet;
import swim.concurrent.AbstractTimer;
import swim.concurrent.TimerFunction;
import swim.concurrent.TimerRef;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.http.header.Host;
import swim.io.http.AbstractHttpClient;
import swim.io.http.AbstractHttpRequester;
import swim.io.http.HttpInterface;
import swim.io.http.HttpSettings;
import swim.security.GoogleIdToken;
import swim.security.JsonWebKey;
import swim.security.PublicKeyDef;
import swim.structure.Item;
import swim.structure.Value;
import swim.uri.Uri;
import swim.uri.UriAuthority;
public class GoogleIdAuthenticator extends AbstractAuthenticator implements HttpInterface {
protected final FingerTrieSeq<String> audiences;
protected HashTrieSet<String> emails;
protected final Uri publicKeyUri;
protected final HttpSettings httpSettings;
FingerTrieSeq<PublicKeyDef> publicKeyDefs;
TimerRef publicKeyRefreshTimer;
public GoogleIdAuthenticator(FingerTrieSeq<String> audiences, HashTrieSet<String> emails,
Uri publicKeyUri, HttpSettings httpSettings) {
this.audiences = audiences;
this.emails = emails;
this.publicKeyUri = publicKeyUri;
this.httpSettings = httpSettings;
this.publicKeyDefs = FingerTrieSeq.empty();
}
public GoogleIdAuthenticator(GoogleIdAuthenticatorDef authenticatorDef) {
this(authenticatorDef.audiences, authenticatorDef.emails,
authenticatorDef.publicKeyUri, authenticatorDef.httpSettings);
}
public final FingerTrieSeq<String> audiences() {
return this.audiences;
}
public final HashTrieSet<String> emails() {
return this.emails;
}
public void addEmail(String email) {
this.emails = emails.added(email);
}
public void removeEmail(String email) {
this.emails = emails.removed(email);
}
public final Uri publicKeyUri() {
return this.publicKeyUri;
}
@Override
public final HttpSettings httpSettings() {
return this.httpSettings;
}
@Override
public PolicyDirective<Identity> authenticate(Credentials credentials) {
String compactJws = credentials.claims().get("idToken").stringValue(null);
if (compactJws == null) {
compactJws = credentials.claims().get("googleIdToken").stringValue(null);
}
if (compactJws != null) {
final GoogleIdToken idToken = GoogleIdToken.verify(compactJws, this.publicKeyDefs);
if (idToken != null) {
if (this.emails .isEmpty() || this.emails .contains(idToken.email())) {
return PolicyDirective.<Identity>allow(new Authenticated(
credentials.requestUri(), credentials.fromUri(), idToken.toValue()));
}
}
}
return null;
}
public final FingerTrieSeq<PublicKeyDef> publicKeyDefs() {
return this.publicKeyDefs;
}
public void setPublicKeyDefs(FingerTrieSeq<PublicKeyDef> publicKeyDefs) {
this.publicKeyDefs = publicKeyDefs;
}
public void refreshPublicKeys() {
final UriAuthority authority = this.publicKeyUri.authority();
final String address = authority.hostAddress();
int port = authority.portNumber();
if (port == 0) {
port = 443;
}
connectHttps(address, port, new GoogleIdAuthenticatorPublicKeyClient(this), this.httpSettings);
}
@Override
public void didStart() {
refreshPublicKeys();
final TimerRef publicKeyRefreshTimer = this.publicKeyRefreshTimer;
if (publicKeyRefreshTimer != null) {
publicKeyRefreshTimer.cancel();
}
this.publicKeyRefreshTimer = schedule().setTimer(PUBLIC_KEY_REFRESH_INTERVAL,
new GoogleIdAuthenticatorPublicKeyRefreshTimer(this));
}
@Override
public void willStop() {
final TimerRef publicKeyRefreshTimer = this.publicKeyRefreshTimer;
if (publicKeyRefreshTimer != null) {
publicKeyRefreshTimer.cancel();
this.publicKeyRefreshTimer = null;
}
}
static final long PUBLIC_KEY_REFRESH_INTERVAL;
static {
long publicKeyRefreshInterval;
try {
publicKeyRefreshInterval = Long.parseLong(System.getProperty("swim.auth.google.public.key.refresh.interval"));
} catch (NumberFormatException error) {
publicKeyRefreshInterval = (long) (60 * 60 * 1000);
}
PUBLIC_KEY_REFRESH_INTERVAL = publicKeyRefreshInterval;
}
}
final class GoogleIdAuthenticatorPublicKeyRefreshTimer extends AbstractTimer implements TimerFunction {
final GoogleIdAuthenticator authenticator;
GoogleIdAuthenticatorPublicKeyRefreshTimer(GoogleIdAuthenticator authenticator) {
this.authenticator = authenticator;
}
@Override
public void runTimer() {
this.authenticator.refreshPublicKeys();
this.reschedule(GoogleIdAuthenticator.PUBLIC_KEY_REFRESH_INTERVAL);
}
}
final class GoogleIdAuthenticatorPublicKeyClient extends AbstractHttpClient {
final GoogleIdAuthenticator authenticator;
GoogleIdAuthenticatorPublicKeyClient(GoogleIdAuthenticator authenticator) {
this.authenticator = authenticator;
}
@Override
public void didConnect() {
super.didConnect();
doRequest(new GoogleIdAuthenticatorPublicKeyRequester(this.authenticator));
}
}
final class GoogleIdAuthenticatorPublicKeyRequester extends AbstractHttpRequester<Value> {
final GoogleIdAuthenticator authenticator;
GoogleIdAuthenticatorPublicKeyRequester(GoogleIdAuthenticator authenticator) {
this.authenticator = authenticator;
}
@Override
public void doRequest() {
final Uri publicKeyUri = this.authenticator.publicKeyUri;
final Uri requestUri = Uri.from(publicKeyUri.path());
final HttpRequest<?> request = HttpRequest.get(requestUri, Host.from(publicKeyUri.authority()));
writeRequest(request);
}
@Override
public void didRespond(HttpResponse<Value> response) {
FingerTrieSeq<PublicKeyDef> publicKeyDefs = FingerTrieSeq.empty();
try {
for (Item item : response.entity().get().get("keys")) {
final PublicKeyDef publicKeyDef = JsonWebKey.from(item.toValue()).publicKeyDef();
if (publicKeyDef != null) {
publicKeyDefs = publicKeyDefs.appended(publicKeyDef);
}
}
this.authenticator.setPublicKeyDefs(publicKeyDefs);
} finally {
close();
}
}
}
|
0 | java-sources/ai/swim/swim-auth/3.10.0/swim | java-sources/ai/swim/swim-auth/3.10.0/swim/auth/GoogleIdAuthenticatorDef.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.auth;
import swim.api.auth.AuthenticatorDef;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.codec.ParserException;
import swim.collections.FingerTrieSeq;
import swim.collections.HashTrieSet;
import swim.io.http.HttpSettings;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.util.Builder;
import swim.util.Murmur3;
public class GoogleIdAuthenticatorDef implements AuthenticatorDef, Debug {
final String authenticatorName;
final FingerTrieSeq<String> audiences;
final HashTrieSet<String> emails;
final Uri publicKeyUri;
final HttpSettings httpSettings;
public GoogleIdAuthenticatorDef(String authenticatorName, FingerTrieSeq<String> audiences,
HashTrieSet<String> emails, Uri publicKeyUri,
HttpSettings httpSettings) {
this.authenticatorName = authenticatorName;
this.audiences = audiences;
this.emails = emails;
this.publicKeyUri = publicKeyUri;
this.httpSettings = httpSettings;
}
@Override
public final String authenticatorName() {
return this.authenticatorName;
}
public final FingerTrieSeq<String> audiences() {
return this.audiences;
}
public final HashTrieSet<String> emails() {
return this.emails;
}
public final Uri publicKeyUri() {
return this.publicKeyUri;
}
public final HttpSettings httpSettings() {
return this.httpSettings;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof GoogleIdAuthenticatorDef) {
final GoogleIdAuthenticatorDef that = (GoogleIdAuthenticatorDef) other;
return (this.authenticatorName == null ? that.authenticatorName == null : this.authenticatorName.equals(that.authenticatorName))
&& this.audiences.equals(that.audiences) && this.emails.equals(that.emails)
&& this.publicKeyUri.equals(that.publicKeyUri) && this.httpSettings.equals(that.httpSettings);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(GoogleIdAuthenticatorDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.authenticatorName)), this.audiences.hashCode()),
this.emails.hashCode()), this.publicKeyUri.hashCode()), this.httpSettings.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("GoogleIdAuthenticatorDef").write('(')
.debug(this.authenticatorName).write(", ").debug(this.audiences).write(", ")
.debug(this.emails).write(", ").debug(this.publicKeyUri).write(", ")
.debug(this.httpSettings).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
static final Uri PUBLIC_KEY_URI;
private static int hashSeed;
private static Form<GoogleIdAuthenticatorDef> form;
@Kind
public static Form<GoogleIdAuthenticatorDef> form() {
if (form == null) {
form = new GoogleIdAuthenticatorForm();
}
return form;
}
static {
Uri publicKeyUri;
try {
publicKeyUri = Uri.parse(System.getProperty("swim.auth.google.public.key.uri"));
} catch (NullPointerException | ParserException error) {
publicKeyUri = Uri.parse("https://www.googleapis.com/oauth2/v3/certs");
}
PUBLIC_KEY_URI = publicKeyUri;
}
}
final class GoogleIdAuthenticatorForm extends Form<GoogleIdAuthenticatorDef> {
@Override
public String tag() {
return "googleId";
}
@Override
public Class<?> type() {
return GoogleIdAuthenticatorDef.class;
}
@Override
public Item mold(GoogleIdAuthenticatorDef authenticatorDef) {
if (authenticatorDef != null) {
final Record record = Record.create().attr(tag());
for (String audience : authenticatorDef.audiences) {
record.add(Record.create(1).attr("audience", audience));
}
for (String email : authenticatorDef.emails) {
record.add(Record.create(1).attr("email", email));
}
return record.concat(authenticatorDef.httpSettings.toValue());
} else {
return Item.extant();
}
}
@Override
public GoogleIdAuthenticatorDef cast(Item item) {
final Value value = item.toValue();
final Value headers = value.getAttr(tag());
if (headers.isDefined()) {
final String authenticatorName = item.key().stringValue(null);
final Builder<String, FingerTrieSeq<String>> audiences = FingerTrieSeq.builder();
HashTrieSet<String> emails = HashTrieSet.empty();
for (Item member : value) {
final String tag = member.tag();
if ("audience".equals(tag)) {
audiences.add(member.get("audience").stringValue());
} else if ("email".equals(tag)) {
emails = emails.added(member.get("email").stringValue());
}
}
Uri publicKeyUri = null;
try {
publicKeyUri = Uri.parse(value.get("publicKeyUri").stringValue(null));
} catch (NullPointerException | ParserException error) {
// continue
}
if (publicKeyUri == null || !publicKeyUri.isDefined()) {
publicKeyUri = GoogleIdAuthenticatorDef.PUBLIC_KEY_URI;
}
final HttpSettings httpSettings = HttpSettings.form().cast(value);
return new GoogleIdAuthenticatorDef(authenticatorName, audiences.bind(),
emails, publicKeyUri, httpSettings);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-auth/3.10.0/swim | java-sources/ai/swim/swim-auth/3.10.0/swim/auth/OpenIdAuthenticator.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.auth;
import swim.api.auth.AbstractAuthenticator;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.policy.PolicyDirective;
import swim.collections.FingerTrieSeq;
import swim.security.JsonWebSignature;
import swim.security.OpenIdToken;
import swim.security.PublicKeyDef;
import swim.structure.Value;
import swim.uri.Uri;
public class OpenIdAuthenticator extends AbstractAuthenticator {
protected final FingerTrieSeq<String> issuers;
protected final FingerTrieSeq<String> audiences;
protected final FingerTrieSeq<PublicKeyDef> publicKeyDefs;
public OpenIdAuthenticator(FingerTrieSeq<String> issuers, FingerTrieSeq<String> audiences,
FingerTrieSeq<PublicKeyDef> publicKeyDefs) {
this.issuers = issuers;
this.audiences = audiences;
this.publicKeyDefs = publicKeyDefs;
}
public OpenIdAuthenticator(OpenIdAuthenticatorDef authenticatorDef) {
this(authenticatorDef.issuers, authenticatorDef.audiences, authenticatorDef.publicKeyDefs);
}
public final FingerTrieSeq<String> issuers() {
return this.issuers;
}
public final FingerTrieSeq<String> audiences() {
return this.audiences;
}
public final FingerTrieSeq<PublicKeyDef> publicKeyDefs() {
return this.publicKeyDefs;
}
@Override
public PolicyDirective<Identity> authenticate(Credentials credentials) {
String compactJws = credentials.claims().get("idToken").stringValue(null);
if (compactJws == null) {
compactJws = credentials.claims().get("openIdToken").stringValue(null);
}
if (compactJws != null) {
final JsonWebSignature jws = JsonWebSignature.parse(compactJws);
if (jws != null) {
return authenticate(credentials.requestUri(), credentials.fromUri(), jws);
}
}
return null;
}
public PolicyDirective<Identity> authenticate(Uri requestUri, Uri fromUri, JsonWebSignature jws) {
final Value payloadValue = jws.payload();
if (payloadValue.isDefined()) {
final OpenIdToken idToken = new OpenIdToken(payloadValue);
// TODO: check payload
for (int i = 0, n = this.publicKeyDefs.size(); i < n; i += 1) {
if (jws.verifySignature(this.publicKeyDefs.get(i).publicKey())) {
return PolicyDirective.<Identity>allow(new Authenticated(requestUri, fromUri, idToken.toValue()));
}
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-auth/3.10.0/swim | java-sources/ai/swim/swim-auth/3.10.0/swim/auth/OpenIdAuthenticatorDef.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.auth;
import swim.api.auth.AuthenticatorDef;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.collections.FingerTrieSeq;
import swim.security.PublicKeyDef;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Builder;
import swim.util.Murmur3;
public class OpenIdAuthenticatorDef implements AuthenticatorDef, Debug {
final String authenticatorName;
final FingerTrieSeq<String> issuers;
final FingerTrieSeq<String> audiences;
final FingerTrieSeq<PublicKeyDef> publicKeyDefs;
public OpenIdAuthenticatorDef(String authenticatorName, FingerTrieSeq<String> issuers,
FingerTrieSeq<String> audiences,
FingerTrieSeq<PublicKeyDef> publicKeyDefs) {
this.authenticatorName = authenticatorName;
this.issuers = issuers;
this.audiences = audiences;
this.publicKeyDefs = publicKeyDefs;
}
@Override
public final String authenticatorName() {
return this.authenticatorName;
}
public final FingerTrieSeq<String> issuers() {
return this.issuers;
}
public final FingerTrieSeq<String> audiences() {
return this.audiences;
}
public final FingerTrieSeq<PublicKeyDef> publicKeyDefs() {
return this.publicKeyDefs;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof OpenIdAuthenticatorDef) {
final OpenIdAuthenticatorDef that = (OpenIdAuthenticatorDef) other;
return (this.authenticatorName == null ? that.authenticatorName == null : this.authenticatorName.equals(that.authenticatorName))
&& this.issuers.equals(that.issuers) && this.audiences.equals(that.audiences)
&& this.publicKeyDefs.equals(that.publicKeyDefs);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(OpenIdAuthenticatorDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.authenticatorName)), this.issuers.hashCode()),
this.audiences.hashCode()), this.publicKeyDefs.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("OpenIdAuthenticatorDef").write('(')
.debug(this.authenticatorName).write(", ").debug(this.issuers).write(", ")
.debug(this.audiences).write(", ").debug(this.publicKeyDefs).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Form<OpenIdAuthenticatorDef> form;
@Kind
public static Form<OpenIdAuthenticatorDef> form() {
if (form == null) {
form = new OpenIdAuthenticatorForm();
}
return form;
}
}
final class OpenIdAuthenticatorForm extends Form<OpenIdAuthenticatorDef> {
@Override
public String tag() {
return "openId";
}
@Override
public Class<?> type() {
return OpenIdAuthenticatorDef.class;
}
@Override
public Item mold(OpenIdAuthenticatorDef authenticatorDef) {
if (authenticatorDef != null) {
final Record record = Record.create().attr(tag());
Value issuers = Value.absent();
for (String issuer : authenticatorDef.issuers) {
issuers = issuers.appended(issuer);
}
if (issuers.isDefined()) {
record.slot("issuers", issuers);
}
Value audiences = Value.absent();
for (String audience : authenticatorDef.audiences) {
audiences = audiences.appended(audience);
}
if (audiences.isDefined()) {
record.slot("audiences", audiences);
}
for (PublicKeyDef publicKeyDef : authenticatorDef.publicKeyDefs) {
record.add(publicKeyDef.toValue());
}
return record;
} else {
return Item.extant();
}
}
@Override
public OpenIdAuthenticatorDef cast(Item item) {
final Value value = item.toValue();
final Value headers = value.getAttr(tag());
if (headers.isDefined()) {
final String authenticatorName = item.key().stringValue(null);
final Builder<String, FingerTrieSeq<String>> issuers = FingerTrieSeq.builder();
final Builder<String, FingerTrieSeq<String>> audiences = FingerTrieSeq.builder();
final Builder<PublicKeyDef, FingerTrieSeq<PublicKeyDef>> publicKeyDefs = FingerTrieSeq.builder();
for (Item member : value) {
final String tag = member.tag();
if ("issuer".equals(tag)) {
issuers.add(member.get("issuer").stringValue());
} else if ("audience".equals(tag)) {
audiences.add(member.get("audience").stringValue());
} else {
final PublicKeyDef publicKeyDef = PublicKeyDef.publicKeyForm().cast(member.toValue());
if (publicKeyDef != null) {
publicKeyDefs.add(publicKeyDef);
}
}
}
return new OpenIdAuthenticatorDef(authenticatorName, issuers.bind(),
audiences.bind(), publicKeyDefs.bind());
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-auth/3.10.0/swim | java-sources/ai/swim/swim-auth/3.10.0/swim/auth/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.
/**
* Swim Authenticator runtime.
*/
package swim.auth;
|
0 | java-sources/ai/swim/swim-cli | java-sources/ai/swim/swim-cli/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.
/**
* Swim Command Line Interface.
*/
module swim.cli {
requires transitive swim.args;
requires transitive swim.recon;
requires transitive swim.json;
requires transitive swim.client;
exports swim.cli;
}
|
0 | java-sources/ai/swim/swim-cli/3.10.0/swim | java-sources/ai/swim/swim-cli/3.10.0/swim/cli/CliClient.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.cli;
import swim.api.ref.SwimRef;
import swim.api.warp.WarpDownlink;
import swim.args.Arg;
import swim.args.Cmd;
import swim.args.Opt;
import swim.uri.Uri;
public class CliClient {
protected final SwimRef swim;
public CliClient(SwimRef swim) {
this.swim = swim;
}
public final SwimRef swim() {
return this.swim;
}
public String name() {
return "swim-cli";
}
public Cmd mainCmd() {
return Cmd.of(name())
.cmd(linkCmd())
.cmd(syncCmd())
.cmd(getCmd())
.cmd(reflectCmd())
.helpCmd();
}
public Cmd linkCmd() {
return Cmd.of("link")
.desc("stream changes to a lane of a remote node")
.opt(Opt.of("host").flag('h').arg("hostUri").desc("remote host to link"))
.opt(Opt.of("node").flag('n').arg("nodeUri").desc("remote node to link"))
.opt(Opt.of("lane").flag('l').arg("laneUri").desc("lane to link"))
.opt(Opt.of("format").flag('f').arg("json|recon").desc("event output format"))
.helpCmd()
.exec(this::runLinkCmd);
}
public Cmd syncCmd() {
return Cmd.of("sync")
.desc("stream the current state and changes to a lane of a remote node")
.opt(Opt.of("host").flag('h').arg("hostUri").desc("remote host to link"))
.opt(Opt.of("node").flag('n').arg("nodeUri").desc("remote node to link"))
.opt(Opt.of("lane").flag('l').arg("laneUri").desc("lane to link"))
.opt(Opt.of("format").flag('f').arg("json|recon").desc("event output format"))
.helpCmd()
.exec(this::runSyncCmd);
}
public Cmd getCmd() {
return Cmd.of("get")
.desc("fetch the current state of a lane of a remote node")
.opt(Opt.of("host").flag('h').arg("hostUri").desc("remote host to link"))
.opt(Opt.of("node").flag('n').arg("nodeUri").desc("remote node to link"))
.opt(Opt.of("lane").flag('l').arg("laneUri").desc("lane to link"))
.opt(Opt.of("format").flag('f').arg("json|recon").desc("event output format"))
.helpCmd()
.exec(this::runGetCmd);
}
public Cmd reflectCmd() {
return Cmd.of("reflect")
.desc("stream introspection metadata")
.opt(Opt.of("edge").flag('e').arg("edgeUri").desc("endpoint to introspect"))
.opt(Opt.of("mesh").flag('m').arg(Arg.of("meshUri").optional(true)).desc("introspect default or specified mesh"))
.opt(Opt.of("part").flag('p').arg(Arg.of("partKey").optional(true)).desc("introspect default or specified partition"))
.opt(Opt.of("host").flag('h').arg(Arg.of("hostUri").optional(true)).desc("introspect default or specified host"))
.opt(Opt.of("node").flag('n').arg("nodeUri").desc("introspect specified node"))
.opt(Opt.of("lane").flag('l').arg("laneUri").desc("introspect specified lane"))
.opt(Opt.of("link").flag('k').desc("introspect link behavior"))
.opt(Opt.of("router").flag('r').desc("introspect router behavior"))
.opt(Opt.of("data").desc("introspect data behavior"))
.opt(Opt.of("system").desc("introspect system behavior"))
.opt(Opt.of("process").desc("introspect process behavior"))
.opt(Opt.of("stats").flag('s').desc("stream introspection statistics"))
.opt(Opt.of("format").flag('f').arg("json|recon").desc("event output format"))
.cmd(reflectLogCmd())
.helpCmd()
.exec(this::runReflectCmd);
}
public Cmd reflectLogCmd() {
return Cmd.of("log")
.desc("stream log events")
.opt(Opt.of("trace").flag('t').desc("stream trace log messages"))
.opt(Opt.of("debug").flag('d').desc("stream debug log messages"))
.opt(Opt.of("info").flag('i').desc("stream info log messages"))
.opt(Opt.of("warn").flag('w').desc("stream warning log messages"))
.opt(Opt.of("error").flag('e').desc("stream error log messages"))
.helpCmd()
.exec(this::runReflectLogCmd);
}
public void runLinkCmd(Cmd cmd) {
final WarpDownlink downlink = downlink(cmd).keepSynced(false);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
}
public void runSyncCmd(Cmd cmd) {
final WarpDownlink downlink = downlink(cmd).keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
}
public void runGetCmd(Cmd cmd) {
final WarpDownlink downlink = downlink(cmd).keepSynced(true);
final DownlinkGetter downlinkGetter = downlinkGetter(downlink, cmd);
downlinkGetter.open();
}
public void runReflectCmd(Cmd cmd) {
final String edgeUri = cmd.getOpt("edge").getValue();
if (edgeUri != null) {
final String meshUri = cmd.getOpt("mesh").getValue();
final String hostUri = cmd.getOpt("host").getValue();
final String nodeUri = cmd.getOpt("node").getValue();
final String laneUri = cmd.getOpt("lane").getValue();
if (nodeUri != null) {
Uri metaNodeUri;
if (meshUri != null) {
metaNodeUri = Uri.parse("swim:meta:mesh").appendedPath(meshUri, "node", nodeUri);
} else if (hostUri != null) {
metaNodeUri = Uri.parse("swim:meta:host").appendedPath(hostUri, "node", nodeUri);
} else {
metaNodeUri = Uri.parse("swim:meta:node").appendedPath(nodeUri);
}
if (laneUri != null) {
metaNodeUri = metaNodeUri.appendedPath("lane", laneUri);
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("linkStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else {
if (cmd.getOpt("link").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("linkStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("routerStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
}
}
} else if (hostUri != null) {
Uri metaNodeUri;
if (meshUri != null) {
metaNodeUri = Uri.parse("swim:meta:mesh").appendedPath(meshUri);
if (hostUri != null) {
metaNodeUri = metaNodeUri.appendedPath("host", hostUri);
}
} else {
metaNodeUri = Uri.parse("swim:meta:host");
if (hostUri != null) {
metaNodeUri = metaNodeUri.appendedPath(hostUri);
}
}
if (cmd.getOpt("process").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("processStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("system").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("systemStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("data").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("dataStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("router").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("routerStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("link").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("linkStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("hostStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
}
} else if (meshUri != null) {
Uri metaNodeUri = Uri.parse("swim:meta:mesh");
if (meshUri != null) {
metaNodeUri = metaNodeUri.appendedPath(meshUri);
}
if (cmd.getOpt("process").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("processStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("system").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("systemStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("data").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("dataStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("router").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("routerStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("link").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("linkStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri(metaNodeUri)
.laneUri("meshStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
}
} else {
if (cmd.getOpt("process").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri("swim:meta:edge")
.laneUri("processStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("system").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri("swim:meta:edge")
.laneUri("systemStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("data").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri("swim:meta:edge")
.laneUri("dataStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else if (cmd.getOpt("link").isDefined()) {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri("swim:meta:edge")
.laneUri("linkStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
} else {
final WarpDownlink downlink = this.swim.downlink()
.hostUri(edgeUri)
.nodeUri("swim:meta:edge")
.laneUri("routerStats")
.keepSynced(true);
final DownlinkLogger downlinkLogger = downlinkLogger(downlink, cmd);
downlinkLogger.open();
}
}
}
}
public void runReflectLogCmd(Cmd cmd) {
// TODO
}
protected WarpDownlink downlink(Cmd cmd) {
return this.swim.downlink()
.hostUri(cmd.getOpt("host").getValue())
.nodeUri(cmd.getOpt("node").getValue())
.laneUri(cmd.getOpt("lane").getValue());
}
protected DownlinkLogger downlinkLogger(WarpDownlink downlink, Cmd cmd) {
final String format = cmd.getOpt("format").getValue();
return new DownlinkLogger(downlink, format);
}
protected DownlinkGetter downlinkGetter(WarpDownlink downlink, Cmd cmd) {
final String format = cmd.getOpt("format").getValue();
return new DownlinkGetter(downlink, format);
}
}
|
0 | java-sources/ai/swim/swim-cli/3.10.0/swim | java-sources/ai/swim/swim-cli/3.10.0/swim/cli/DownlinkGetter.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.cli;
import swim.api.warp.WarpDownlink;
public class DownlinkGetter extends DownlinkLogger {
public DownlinkGetter(WarpDownlink downlink, String format) {
super(downlink, format);
}
@Override
public void didSync() {
System.exit(0);
}
}
|
0 | java-sources/ai/swim/swim-cli/3.10.0/swim | java-sources/ai/swim/swim-cli/3.10.0/swim/cli/DownlinkLogger.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.cli;
import swim.api.function.DidClose;
import swim.api.warp.WarpDownlink;
import swim.api.warp.function.DidSync;
import swim.api.warp.function.DidUnlink;
import swim.api.warp.function.OnEvent;
import swim.json.Json;
import swim.recon.Recon;
import swim.structure.Value;
public class DownlinkLogger implements OnEvent<Value>, DidSync, DidUnlink, DidClose {
final WarpDownlink downlink;
final String format;
public DownlinkLogger(WarpDownlink downlink, String format) {
this.downlink = downlink.observe(this);
this.format = format;
}
public void open() {
this.downlink.open();
}
public void close() {
this.downlink.close();
}
protected void log(String string) {
System.out.println(string);
}
@Override
public void onEvent(Value value) {
if ("json".equals(this.format)) {
log(Json.toString(value));
} else {
log(Recon.toString(value));
}
}
@Override
public void didSync() {
// stub
}
@Override
public void didUnlink() {
System.exit(1);
}
@Override
public void didClose() {
System.exit(0);
}
}
|
0 | java-sources/ai/swim/swim-cli/3.10.0/swim | java-sources/ai/swim/swim-cli/3.10.0/swim/cli/Main.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.cli;
import swim.args.Cmd;
import swim.client.ClientRuntime;
public final class Main {
private Main() {
// stub
}
public static void main(String[] args) {
final ClientRuntime swim = new ClientRuntime();
final CliClient cli = new CliClient(swim);
swim.start();
final Cmd cmd = cli.mainCmd().parse(args, 0);
cmd.run();
}
}
|
0 | java-sources/ai/swim/swim-cli/3.10.0/swim | java-sources/ai/swim/swim-cli/3.10.0/swim/cli/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.
/**
* Swim Command Line Interface.
*/
package swim.cli;
|
0 | java-sources/ai/swim/swim-client | java-sources/ai/swim/swim-client/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.
/**
* Web Agent client runtime.
*/
module swim.client {
requires transitive swim.runtime;
requires transitive swim.remote;
exports swim.client;
provides swim.api.client.Client with swim.client.ClientRuntime;
}
|
0 | java-sources/ai/swim/swim-client/3.10.0/swim | java-sources/ai/swim/swim-client/3.10.0/swim/client/ClientRuntime.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.client;
import swim.api.Downlink;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.client.Client;
import swim.api.policy.Policy;
import swim.api.policy.PolicyDirective;
import swim.concurrent.MainStage;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.concurrent.Theater;
import swim.io.TlsSettings;
import swim.io.http.HttpEndpoint;
import swim.io.http.HttpSettings;
import swim.remote.RemoteHostClient;
import swim.runtime.AbstractSwimRef;
import swim.runtime.EdgeBinding;
import swim.runtime.EdgeContext;
import swim.runtime.HostBinding;
import swim.runtime.LaneBinding;
import swim.runtime.LaneDef;
import swim.runtime.LinkBinding;
import swim.runtime.MeshBinding;
import swim.runtime.NodeBinding;
import swim.runtime.PartBinding;
import swim.runtime.PushRequest;
import swim.runtime.router.EdgeTable;
import swim.runtime.router.MeshTable;
import swim.runtime.router.PartTable;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class ClientRuntime extends AbstractSwimRef implements Client, EdgeContext {
final Stage stage;
final HttpEndpoint endpoint;
final EdgeBinding edge;
StoreBinding store;
public ClientRuntime(Stage stage, HttpSettings settings) {
this.stage = stage;
this.endpoint = new HttpEndpoint(stage, settings);
this.edge = new EdgeTable();
this.edge.setEdgeContext(this);
}
public ClientRuntime(Stage stage) {
this(stage, HttpSettings.standard().tlsSettings(TlsSettings.standard()));
}
public ClientRuntime() {
this(new Theater());
}
@Override
public void start() {
if (this.stage instanceof MainStage) {
((MainStage) this.stage).start();
}
this.endpoint.start();
this.edge.start();
}
@Override
public void stop() {
this.endpoint.stop();
if (this.stage instanceof MainStage) {
((MainStage) this.stage).stop();
}
}
@Override
public final EdgeBinding edgeWrapper() {
return this.edge.edgeWrapper();
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapEdge(Class<T> edgeClass) {
if (edgeClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public Uri meshUri() {
return Uri.empty();
}
@Override
public Policy policy() {
return null; // TODO
}
@Override
public Schedule schedule() {
return this.stage;
}
@Override
public final Stage stage() {
return this.stage;
}
@Override
public final StoreBinding store() {
return this.store;
}
public final HttpEndpoint endpoint() {
return this.endpoint;
}
@Override
public MeshBinding createMesh(Uri meshUri) {
return new MeshTable();
}
@Override
public MeshBinding injectMesh(Uri meshUri, MeshBinding mesh) {
return mesh;
}
@Override
public PartBinding createPart(Uri meshUri, Value partKey) {
return new PartTable();
}
@Override
public PartBinding injectPart(Uri meshUri, Value partKey, PartBinding part) {
return part;
}
@Override
public HostBinding createHost(Uri meshUri, Value partKey, Uri hostUri) {
return new RemoteHostClient(hostUri, this.endpoint);
}
@Override
public HostBinding injectHost(Uri meshUri, Value partKey, Uri hostUri, HostBinding host) {
return host;
}
@Override
public NodeBinding createNode(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri) {
return null;
}
@Override
public NodeBinding injectNode(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
return node;
}
@Override
public LaneBinding createLane(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return null;
}
@Override
public LaneBinding createLane(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri) {
return null;
}
@Override
public LaneBinding injectLane(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri, LaneBinding lane) {
return lane;
}
@Override
public void openLanes(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
// nop
}
@Override
public AgentFactory<?> createAgentFactory(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, AgentDef agentDef) {
return null;
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri,
Class<? extends A> agentClass) {
return null;
}
@Override
public void openAgents(Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
// nop
}
@Override
public PolicyDirective<Identity> authenticate(Credentials credentials) {
return null; // TODO
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.edge.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.edge.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void pushDown(PushRequest pushRequest) {
this.edge.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
// TODO
}
@Override
public void debug(Object message) {
// TODO
}
@Override
public void info(Object message) {
// TODO
}
@Override
public void warn(Object message) {
// TODO
}
@Override
public void error(Object message) {
// TODO
}
@Override
public void close() {
// TODO
}
@Override
public void willOpen() {
// nop
}
@Override
public void didOpen() {
// nop
}
@Override
public void willLoad() {
// nop
}
@Override
public void didLoad() {
// nop
}
@Override
public void willStart() {
// nop
}
@Override
public void didStart() {
// nop
}
@Override
public void willStop() {
// nop
}
@Override
public void didStop() {
// nop
}
@Override
public void willUnload() {
// nop
}
@Override
public void didUnload() {
// nop
}
@Override
public void willClose() {
// nop
}
}
|
0 | java-sources/ai/swim/swim-client/3.10.0/swim | java-sources/ai/swim/swim-client/3.10.0/swim/client/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.
/**
* Web Agent client runtime.
*/
package swim.client;
|
0 | java-sources/ai/swim/swim-codec | java-sources/ai/swim/swim-codec/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.
/**
* Incremental parsers, writers, decoders, and encoders.
*/
module swim.codec {
requires transitive swim.util;
exports swim.codec;
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base10.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.codec;
/**
* Base-10 (decimal) encoding {@link Parser}/{@link Writer} factory.
*/
public final class Base10 {
private Base10() {
// nop
}
/**
* Returns {@code true} if the Unicode code point {@code c} is a valid
* base-10 digit.
*/
public static boolean isDigit(int c) {
return c >= '0' && c <= '9';
}
/**
* Returns the decimal quantity between {@code 0} (inclusive) and {@code 10}
* (exclusive) represented by the base-10 digit {@code c}.
*
* @throws IllegalArgumentException if {@code c} is not a valid base-10 digit.
*/
public static int decodeDigit(int c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else {
final Output<String> message = Unicode.stringOutput();
message.write("Invalid base-10 digit: ");
Format.debugChar(c, message);
throw new IllegalArgumentException(message.bind());
}
}
/**
* Returns the Unicode code point of the base-10 digit that encodes the given
* decimal quantity between {@code 0} (inclusive) and {@code 10} (exclusive).
*/
public static int encodeDigit(int b) {
if (b >= 0 && b <= 9) {
return '0' + b;
} else {
throw new IllegalArgumentException(Integer.toString(b));
}
}
/**
* Returns the number of decimal digits in the given absolute {@code value}.
*/
public static int countDigits(int value) {
int size = 0;
do {
size += 1;
value /= 10;
} while (value != 0);
return size;
}
/**
* Returns the number of decimal digits in the given absolute {@code value}.
*/
public static int countDigits(long value) {
int size = 0;
do {
size += 1;
value /= 10L;
} while (value != 0L);
return size;
}
/**
* Returns a {@code Writer} that, when fed an input {@code Integer} value,
* returns a continuation that writes the base-10 (decimal) encoding of the
* input value.
*/
@SuppressWarnings("unchecked")
public static Writer<Integer, ?> intWriter() {
return (Writer<Integer, ?>) (Writer<?, ?>) new Base10IntegerWriter();
}
/**
* Returns a {@code Writer} continuation that writes the base-10 (decimal)
* encoding of the {@code input} value.
*/
@SuppressWarnings("unchecked")
public static Writer<?, Integer> intWriter(int input) {
return (Writer<?, Integer>) (Writer<?, ?>) new Base10IntegerWriter(null, (long) input);
}
/**
* Returns a {@code Writer} that, when fed an input {@code Long} value,
* returns a continuation that writes the base-10 (decimal) encoding of the
* input value.
*/
@SuppressWarnings("unchecked")
public static Writer<Long, ?> longWriter() {
return (Writer<Long, ?>) (Writer<?, ?>) new Base10IntegerWriter();
}
/**
* Returns a {@code Writer} continuation that writes the base-10 (decimal)
* encoding of the {@code input} value.
*/
@SuppressWarnings("unchecked")
public static Writer<?, Long> longWriter(long input) {
return (Writer<?, Long>) (Writer<?, ?>) new Base10IntegerWriter(null, input);
}
/**
* Returns a {@code Writer} continuation that writes the base-10 (decimal)
* encoding of the {@code input} value.
*/
@SuppressWarnings("unchecked")
public static Writer<?, Float> floatWriter(long input) {
return (Writer<?, Float>) (Writer<?, ?>) new StringWriter(null, input);
}
/**
* Returns a {@code Writer} continuation that writes the base-10 (decimal)
* encoding of the {@code input} value.
*/
@SuppressWarnings("unchecked")
public static Writer<?, Double> doubleWriter(long input) {
return (Writer<?, Double>) (Writer<?, ?>) new StringWriter(null, input);
}
/**
* Writes the base-10 (decimal) encoding of the {@code input} value to the
* {@code output}, returning a {@code Writer} continuation that knows
* how to write any remaining output that couldn't be immediately generated.
*/
public static Writer<?, ?> writeInt(int input, Output<?> output) {
return Base10IntegerWriter.write(output, null, (long) input);
}
/**
* Writes the base-10 (decimal) encoding of the {@code input} value to the
* {@code output}, returning a {@code Writer} continuation that knows
* how to write any remaining output that couldn't be immediately generated.
*/
public static Writer<?, ?> writeLong(long input, Output<?> output) {
return Base10IntegerWriter.write(output, null, input);
}
/**
* Writes the base-10 (decimal) encoding of the {@code input} value to the
* {@code output}, returning a {@code Writer} continuation that knows
* how to write any remaining output that couldn't be immediately generated.
*/
public static Writer<?, ?> writeFloat(float input, Output<?> output) {
return StringWriter.write(output, null, input);
}
/**
* Writes the base-10 (decimal) encoding of the {@code input} value to the
* {@code output}, returning a {@code Writer} continuation that knows
* how to write any remaining output that couldn't be immediately generated.
*/
public static Writer<?, ?> writeDouble(double input, Output<?> output) {
return StringWriter.write(output, null, input);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base10IntegerWriter.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.codec;
final class Base10IntegerWriter extends Writer<Object, Object> {
final Object value;
final long input;
final int index;
final int step;
Base10IntegerWriter(Object value, long input, int index, int step) {
this.value = value;
this.input = input;
this.index = index;
this.step = step;
}
Base10IntegerWriter(Object value, long input) {
this(value, input, 0, 1);
}
Base10IntegerWriter() {
this(null, 0L, 0, 0);
}
@Override
public Writer<Object, Object> feed(Object input) {
if (input instanceof Integer) {
return new Base10IntegerWriter(input, ((Integer) input).longValue());
} else if (input instanceof Long) {
return new Base10IntegerWriter(input, ((Long) input).longValue());
} else {
return new StringWriter(input, input);
}
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.value, this.input, this.index, this.step);
}
static Writer<Object, Object> write(Output<?> output, Object value, long input, int index, int step) {
if (step == 0) {
return done();
}
if (step == 1) {
if (input < 0L) {
if (output.isCont()) {
output = output.write('-');
step = 2;
}
} else {
step = 2;
}
}
if (step == 2) {
if (input > -10L && input < 10L) {
if (output.isCont()) {
output = output.write(Base10.encodeDigit(Math.abs((int) input)));
return done(value);
}
} else {
int i = 18;
final int[] digits = new int[19];
long x = input;
while (x != 0L) {
digits[i] = Math.abs((int) (x % 10L));
x /= 10L;
i -= 1;
}
i += 1 + index;
while (i < 19 && output.isCont()) {
output = output.write(Base10.encodeDigit(digits[i]));
index += 1;
i += 1;
}
if (i == 19) {
return done(value);
}
}
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new Base10IntegerWriter(value, input, index, step);
}
static Writer<Object, Object> write(Output<?> output, Object value, long input) {
return write(output, value, input, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base16.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.codec;
import java.nio.ByteBuffer;
/**
* Base-16 (hexadecimal) encoding {@link Parser}/{@link Writer} factory.
*/
public final class Base16 {
final String alphabet;
Base16(String alphabet) {
this.alphabet = alphabet;
}
/**
* Returns a 16 character string, where the character at index {@code i} is
* the encoding of the base-16 digit {@code i}.
*/
public String alphabet() {
return this.alphabet;
}
/**
* Returns the Unicode code point of the base-16 digit that encodes the given
* 4-bit quantity.
*/
public char encodeDigit(int b) {
return this.alphabet.charAt(b);
}
/**
* Returns a {@code Writer} that, when fed an input {@code byte[]} array,
* returns a continuation that writes the base-16 (hexadecimal) encoding of
* the input byte array.
*/
@SuppressWarnings("unchecked")
public Writer<byte[], ?> byteArrayWriter() {
return (Writer<byte[], ?>) (Writer<?, ?>) new Base16Writer(this);
}
/**
* Returns a {@code Writer} continuation that writes the base-16 (hexadecimal)
* encoding of the {@code input} byte array.
*/
@SuppressWarnings("unchecked")
public Writer<?, byte[]> byteArrayWriter(byte[] input) {
return (Writer<?, byte[]>) (Writer<?, ?>) new Base16Writer(input, input, this);
}
/**
* Returns a {@code Writer} that, when fed an input {@code ByteBuffer},
* returns a continuation that writes the base-16 (hexadecimal) encoding of
* the input byte buffer.
*/
@SuppressWarnings("unchecked")
public Writer<ByteBuffer, ?> byteBufferWriter() {
return (Writer<ByteBuffer, ?>) (Writer<?, ?>) new Base16Writer(this);
}
/**
* Returns a {@code Writer} continuation that writes the base-16 (hexadecimal)
* encoding of the {@code input} byte buffer.
*/
@SuppressWarnings("unchecked")
public Writer<?, ByteBuffer> byteBufferWriter(ByteBuffer input) {
return (Writer<?, ByteBuffer>) (Writer<?, ?>) new Base16Writer(input, input, this);
}
/**
* Writes the base-16 (hexadecimal) encoding of the {@code input} byte array
* to the {@code output}, returning a {@code Writer} continuation that knows
* how to write any remaining output that couldn't be immediately generated.
*/
public Writer<?, ?> writeByteArray(byte[] input, Output<?> output) {
return Base16Writer.write(output, input, this);
}
/**
* Writes the base-16 (hexadecimal) encoding of the {@code input} byte buffer
* to the {@code output}, returning a {@code Writer} continuation that knows
* how to write any remaining output that couldn't be immediately generated.
*/
public Writer<?, ?> writeByteBuffer(ByteBuffer input, Output<?> output) {
return Base16Writer.write(output, input, this);
}
public Writer<?, ?> writeInt(int input, Output<?> output, int width) {
return Base16IntegerWriter.write(output, null, input, width, this, false);
}
public Writer<?, ?> writeInt(int input, Output<?> output) {
return Base16IntegerWriter.write(output, null, input, 0, this, false);
}
public Writer<?, ?> writeLong(long input, Output<?> output, int width) {
return Base16IntegerWriter.write(output, null, input, width, this, false);
}
public Writer<?, ?> writeLong(long input, Output<?> output) {
return Base16IntegerWriter.write(output, null, input, 0, this, false);
}
public Writer<?, ?> writeIntLiteral(int input, Output<?> output, int width) {
return Base16IntegerWriter.write(output, null, input, width, this, true);
}
public Writer<?, ?> writeIntLiteral(int input, Output<?> output) {
return Base16IntegerWriter.write(output, null, input, 0, this, true);
}
public Writer<?, ?> writeLongLiteral(long input, Output<?> output, int width) {
return Base16IntegerWriter.write(output, null, input, width, this, true);
}
public Writer<?, ?> writeLongLiteral(long input, Output<?> output) {
return Base16IntegerWriter.write(output, null, input, 0, this, true);
}
private static Base16 lowercase;
private static Base16 uppercase;
/**
* Returns the {@code Base16} encoding with lowercase alphanumeric digits.
*/
public static Base16 lowercase() {
if (lowercase == null) {
lowercase = new Base16("0123456789abcdef");
}
return lowercase;
}
/**
* Returns the {@code Base16} encoding with uppercase alphanumeric digits.
*/
public static Base16 uppercase() {
if (uppercase == null) {
uppercase = new Base16("0123456789ABCDEF");
}
return uppercase;
}
/**
* Returns {@code true} if the Unicode code point {@code c} is a valid
* base-16 digit.
*/
public static boolean isDigit(int c) {
return c >= '0' && c <= '9'
|| c >= 'A' && c <= 'F'
|| c >= 'a' && c <= 'f';
}
/**
* Returns the 4-bit quantity represented by the base-16 digit {@code c}.
*
* @throws IllegalArgumentException if {@code c} is not a valid base-16 digit.
*/
public static int decodeDigit(int c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return 10 + (c - 'A');
} else if (c >= 'a' && c <= 'f') {
return 10 + (c - 'a');
} else {
final Output<String> message = Unicode.stringOutput();
message.write("Invalid base-16 digit: ");
Format.debugChar(c, message);
throw new IllegalArgumentException(message.bind());
}
}
/**
* Decodes the base-16 digits {@code c1} and {@code c2}, and writes the 8-bit
* quantity they represent to the given {@code output}.
*/
public static void writeQuantum(int c1, int c2, Output<?> output) {
final int x = Base16.decodeDigit(c1);
final int y = Base16.decodeDigit(c2);
output.write(x << 4 | y);
}
/**
* Returns a {@code Parser} that decodes base-16 (hexadecimal) encoded input,
* and writes the decoded bytes to {@code output}.
*/
public static <O> Parser<O> parser(Output<O> output) {
return new Base16Parser<O>(output);
}
/**
* Parses the base-16 (hexadecimal) encoded {@code input}, and writes the
* decoded bytes to {@code output}, returning a {@code Parser} continuation
* that knows how to parse any additional input.
*/
public static <O> Parser<O> parse(Input input, Output<O> output) {
return Base16Parser.parse(input, output);
}
/**
* Parses the base-16 (hexadecimal) encoded {@code input}, and writes the
* decoded bytes to a growable array, returning a {@code Parser} continuation
* that knows how to parse any additional input. The returned {@code Parser}
* {@link Parser#bind() binds} a {@code byte[]} array containing all parsed
* base-16 data.
*/
public static Parser<byte[]> parseByteArray(Input input) {
return Base16Parser.parse(input, Binary.byteArrayOutput());
}
/**
* Parses the base-16 (hexadecimal) encoded {@code input}, and writes the
* decoded bytes to a growable buffer, returning a {@code Parser} continuation
* that knows how to parse any additional input. The returned {@code Parser}
* {@link Parser#bind() binds} a {@code ByteBuffer} containing all parsed
* base-16 data.
*/
public static Parser<ByteBuffer> parseByteBuffer(Input input) {
return Base16Parser.parse(input, Binary.byteBufferOutput());
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base16IntegerWriter.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.codec;
final class Base16IntegerWriter extends Writer<Object, Object> {
final Object value;
final long input;
final int width;
final Base16 base16;
final int index;
final int step;
Base16IntegerWriter(Object value, long input, int width, Base16 base16, int index, int step) {
this.value = value;
this.input = input;
this.width = width;
this.base16 = base16;
this.index = index;
this.step = step;
}
Base16IntegerWriter(Object value, int input, int width, Base16 base16, boolean literal) {
this(value, input & 0xffffffffL, width, base16, 0, literal ? 1 : 3);
}
Base16IntegerWriter(Object value, long input, int width, Base16 base16, boolean literal) {
this(value, input, width, base16, 0, literal ? 1 : 3);
}
Base16IntegerWriter(Object value, float input, int width, Base16 base16, boolean literal) {
this(value, Float.floatToIntBits(input) & 0xffffffffL, width, base16, 0, literal ? 1 : 3);
}
Base16IntegerWriter(Object value, double input, int width, Base16 base16, boolean literal) {
this(value, Double.doubleToLongBits(input), width, base16, 0, literal ? 1 : 3);
}
Base16IntegerWriter(int width, Base16 base16, boolean literal) {
this(null, 0L, width, base16, 0, literal ? -1 : -3);
}
@Override
public Writer<Object, Object> feed(Object input) {
if (input instanceof Integer) {
return new Base16IntegerWriter(input, (Integer) input, this.width, this.base16, this.step == -1);
} else if (input instanceof Long) {
return new Base16IntegerWriter(input, (Long) input, this.width, this.base16, this.step == -1);
} else if (input instanceof Float) {
return new Base16IntegerWriter(input, (Float) input, this.width, this.base16, this.step == -1);
} else if (input instanceof Double) {
return new Base16IntegerWriter(input, (Double) input, this.width, this.base16, this.step == -1);
} else {
return new StringWriter(input, input);
}
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.value, this.input, this.width, this.base16, this.index, this.step);
}
static Writer<Object, Object> write(Output<?> output, Object value, long input, int width,
Base16 base16, int index, int step) {
if (step <= 0) {
return done();
}
if (step == 1 && output.isCont()) {
output = output.write('0');
step = 2;
}
if (step == 2 && output.isCont()) {
output = output.write('x');
step = 3;
}
if (step == 3) {
if (input >= 0L && input < 16L && width <= 1) {
if (output.isCont()) {
output = output.write(base16.encodeDigit((int) input));
return done(value);
}
} else {
int i = 15;
final int[] digits = new int[16];
long x = input;
while (x != 0L || i >= 16 - width) {
digits[i] = (int) x & 0xf;
x >>>= 4;
i -= 1;
}
i += 1 + index;
while (i < 16 && output.isCont()) {
output = output.write(base16.encodeDigit(digits[i]));
index += 1;
i += 1;
}
if (i == 16) {
return done(value);
}
}
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new Base16IntegerWriter(value, input, width, base16, index, step);
}
static Writer<Object, Object> write(Output<?> output, Object value, int input,
int width, Base16 base16, boolean literal) {
return write(output, null, input & 0xffffffffL, width, base16, 0, literal ? 1 : 3);
}
static Writer<Object, Object> write(Output<?> output, Object value, long input,
int width, Base16 base16, boolean literal) {
return write(output, null, input, width, base16, 0, literal ? 1 : 3);
}
static Writer<Object, Object> write(Output<?> output, Object value, float input,
int width, Base16 base16, boolean literal) {
return write(output, null, Float.floatToIntBits(input) & 0xffffffffL, width, base16, 0, literal ? 1 : 3);
}
static Writer<Object, Object> write(Output<?> output, Object value, double input,
int width, Base16 base16, boolean literal) {
return write(output, null, Double.doubleToLongBits(input), width, base16, 0, literal ? 1 : 3);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base16Parser.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.codec;
final class Base16Parser<O> extends Parser<O> {
final Output<O> output;
final int p;
final int step;
Base16Parser(Output<O> output, int p, int step) {
this.output = output;
this.p = p;
this.step = step;
}
Base16Parser(Output<O> output) {
this(output, 0, 1);
}
@Override
public Parser<O> feed(Input input) {
return parse(input, this.output.clone(), this.p, this.step);
}
static <O> Parser<O> parse(Input input, Output<O> output, int p, int step) {
int c = 0;
while (!input.isEmpty()) {
if (step == 1) {
if (input.isCont()) {
c = input.head();
if (Base16.isDigit(c)) {
input = input.step();
p = c;
step = 2;
} else {
return done(output.bind());
}
} else if (input.isDone()) {
return done(output.bind());
}
}
if (step == 2) {
if (input.isCont()) {
c = input.head();
if (Base16.isDigit(c)) {
input = input.step();
Base16.writeQuantum(p, c, output);
p = 0;
step = 1;
} else {
return error(Diagnostic.expected("base16 digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("base16 digit", input));
}
}
}
if (input.isError()) {
return error(input.trap());
}
return new Base16Parser<O>(output, p, step);
}
static <O> Parser<O> parse(Input input, Output<O> output) {
return parse(input, output, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base16Writer.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.codec;
import java.nio.ByteBuffer;
final class Base16Writer extends Writer<Object, Object> {
final Object value;
final ByteBuffer input;
final Base16 base16;
final int index;
final int limit;
final int step;
Base16Writer(Object value, ByteBuffer input, Base16 base16, int index, int limit, int step) {
this.value = value;
this.input = input;
this.base16 = base16;
this.index = index;
this.limit = limit;
this.step = step;
}
Base16Writer(Object value, ByteBuffer input, Base16 base16) {
this(value, input, base16, input.position(), input.limit(), 1);
}
Base16Writer(ByteBuffer input, Base16 base16) {
this(null, input, base16);
}
Base16Writer(Object value, byte[] input, Base16 base16) {
this(value, ByteBuffer.wrap(input), base16);
}
Base16Writer(byte[] input, Base16 base16) {
this(null, ByteBuffer.wrap(input), base16);
}
Base16Writer(Base16 base16) {
this(null, null, base16, 0, 0, 1);
}
@Override
public Writer<Object, Object> feed(Object value) {
if (value instanceof ByteBuffer) {
return new Base16Writer((ByteBuffer) value, this.base16);
} else if (value instanceof byte[]) {
return new Base16Writer((byte[]) value, this.base16);
} else {
throw new IllegalArgumentException(value.toString());
}
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.value, this.input, this.base16, this.index, this.limit, this.step);
}
static Writer<Object, Object> write(Output<?> output, Object value, ByteBuffer input,
Base16 base16, int index, int limit, int step) {
while (index < limit) {
final int x = input.get(index) & 0xff;
if (step == 1 && output.isCont()) {
output = output.write(base16.encodeDigit(x >>> 4));
step = 2;
}
if (step == 2 && output.isCont()) {
output = output.write(base16.encodeDigit(x & 0x0f));
index += 1;
step = 1;
}
}
if (index == limit) {
return done(value);
} else if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new Base16Writer(value, input, base16, index, limit, step);
}
static Writer<?, ?> write(Output<?> output, Object value, ByteBuffer input, Base16 base16) {
return write(output, value, input, base16, input.position(), input.limit(), 1);
}
static Writer<?, ?> write(Output<?> output, ByteBuffer input, Base16 base16) {
return write(output, null, input, base16);
}
static Writer<?, ?> write(Output<?> output, Object value, byte[] input, Base16 base16) {
return write(output, value, ByteBuffer.wrap(input), base16);
}
static Writer<?, ?> write(Output<?> output, byte[] input, Base16 base16) {
return write(output, null, ByteBuffer.wrap(input), base16);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base64.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.codec;
import java.nio.ByteBuffer;
/**
* Base-64 (7-bit ASCII) encoding {@link Parser}/{@link Writer} factory.
*/
public abstract class Base64 {
Base64() {
// stub
}
/**
* Returns a 64 character string, where the character at index {@code i} is
* the encoding of the base-64 digit {@code i}.
*/
public abstract String alphabet();
/**
* Returns {@code true} if this base-64 encoding requires padding.
*/
public abstract boolean isPadded();
/**
* Returns this {@code Base64} encoding with required padding, if {@code
* isPadded} is {@code true}.
*/
public abstract Base64 isPadded(boolean isPadded);
/**
* Returns {@code true} if the Unicode code point {@code c} is a valid
* base-64 digit.
*/
public abstract boolean isDigit(int c);
/**
* Returns the 7-bit quantity represented by the base-64 digit {@code c}.
*
* @throws IllegalArgumentException if {@code c} is not a valid base-64 digit.
*/
public int decodeDigit(int c) {
if (c >= 'A' && c <= 'Z') {
return c - 'A';
} else if (c >= 'a' && c <= 'z') {
return c + (26 - 'a');
} else if (c >= '0' && c <= '9') {
return c + (52 - '0');
} else if (c == '+' || c == '-') {
return 62;
} else if (c == '/' || c == '_') {
return 63;
} else {
final Output<String> message = Unicode.stringOutput();
message.write("Invalid base-64 digit: ");
Format.debugChar(c, message);
throw new IllegalArgumentException(message.bind());
}
}
/**
* Returns the Unicode code point of the base-64 digit that encodes the given
* 7-bit quantity.
*/
public char encodeDigit(int b) {
return alphabet().charAt(b);
}
/**
* Decodes the base-64 digits {@code c1}, {@code c2}, {@code c3}, and {@code
* c4}, and writes the 8 to 24 bit quantity they represent to the given
* {@code output}.
*/
public void writeQuantum(int c1, int c2, int c3, int c4, Output<?> output) {
final int x = decodeDigit(c1);
final int y = decodeDigit(c2);
if (c3 != '=') {
final int z = decodeDigit(c3);
if (c4 != '=') {
final int w = decodeDigit(c4);
output.write((x << 2) | (y >>> 4));
output.write((y << 4) | (z >>> 2));
output.write((z << 6) | w);
} else {
output.write((x << 2) | (y >>> 4));
output.write((y << 4) | (z >>> 2));
}
} else {
if (c4 != '=') {
throw new IllegalArgumentException("Improperly padded base-64");
}
output.write((x << 2) | (y >>> 4));
}
}
/**
* Returns a {@code Parser} that decodes base-64 (7-bit ASCII) encoded input,
* and writes the decoded bytes to {@code output}.
*/
public <O> Parser<O> parser(Output<O> output) {
return new Base64Parser<O>(output, this);
}
/**
* Parses the base-64 (7-bit ASCII) encoded {@code input}, and writes the
* decoded bytes to {@code output}, returning a {@code Parser} continuation
* that knows how to parse any additional input.
*/
public <O> Parser<O> parse(Input input, Output<O> output) {
return Base64Parser.parse(input, output, this);
}
/**
* Parses the base-64 (7-bit ASCII) encoded {@code input}, and writes the
* decoded bytes to a growable array, returning a {@code Parser} continuation
* that knows how to parse any additional input. The returned {@code Parser}
* {@link Parser#bind() binds} a {@code byte[]} array containing all parsed
* base-64 data.
*/
public Parser<byte[]> parseByteArray(Input input) {
return Base64Parser.parse(input, Binary.byteArrayOutput(), this);
}
/**
* Parses the base-64 (t-bit ASCII) encoded {@code input}, and writes the
* decoded bytes to a growable buffer, returning a {@code Parser} continuation
* that knows how to parse any additional input. The returned {@code Parser}
* {@link Parser#bind() binds} a {@code ByteBuffer} containing all parsed
* base-64 data.
*/
public Parser<ByteBuffer> parseByteBuffer(Input input) {
return Base64Parser.parse(input, Binary.byteBufferOutput(), this);
}
/**
* Returns a {@code Writer} that, when fed an input {@code byte[]} array,
* returns a continuation that writes the base-64 (7-bit ASCII) encoding of
* the input byte array.
*/
@SuppressWarnings("unchecked")
public Writer<byte[], ?> byteArrayWriter() {
return (Writer<byte[], ?>) (Writer<?, ?>) new Base64Writer(this);
}
/**
* Returns a {@code Writer} continuation that writes the base-64 (7-bit ASCII)
* encoding of the {@code input} byte array.
*/
@SuppressWarnings("unchecked")
public Writer<?, byte[]> byteArrayWriter(byte[] input) {
return (Writer<?, byte[]>) (Writer<?, ?>) new Base64Writer(input, input, this);
}
/**
* Returns a {@code Writer} that, when fed an input {@code ByteBuffer},
* returns a continuation that writes the base-64 (7-bit ASCII) encoding of
* the input byte buffer.
*/
@SuppressWarnings("unchecked")
public Writer<ByteBuffer, ?> byteBufferWriter() {
return (Writer<ByteBuffer, ?>) (Writer<?, ?>) new Base64Writer(this);
}
/**
* Returns a {@code Writer} continuation that writes the base-64 (7-bit ASCII)
* encoding of the {@code input} byte buffer.
*/
@SuppressWarnings("unchecked")
public Writer<?, ByteBuffer> byteBufferWriter(ByteBuffer input) {
return (Writer<?, ByteBuffer>) (Writer<?, ?>) new Base64Writer(input, input, this);
}
/**
* Writes the base-64 (7-bit ASCII) encoding of the {@code input} byte array
* to the {@code output}, returning a {@code Writer} continuation that knows
* how to write any remaining output that couldn't be immediately generated.
*/
public Writer<?, ?> writeByteArray(byte[] input, Output<?> output) {
return Base64Writer.write(output, input, this);
}
/**
* Writes the base-64 (7-bit ASCII) encoding of the {@code input} byte buffer
* to the {@code output}, returning a {@code Writer} continuation that knows
* how to write any remaining output that couldn't be immediately generated.
*/
public Writer<?, ?> writeByteBuffer(ByteBuffer input, Output<?> output) {
return Base64Writer.write(output, input, this);
}
private static Base64 standard;
private static Base64 standardUnpadded;
private static Base64 url;
private static Base64 urlUnpadded;
/**
* Returns the {@code Base64} encoding with the standard alphabet.
*/
public static Base64 standard() {
if (standard == null) {
standard = new Base64Standard(true);
}
return standard;
}
static Base64 standardUnpadded() {
if (standardUnpadded == null) {
standardUnpadded = new Base64Standard(false);
}
return standardUnpadded;
}
/**
* Returns the {@code Base64} encoding with the standard alphabet, and
* required padding, if {@code isPadded} is {@code true}.
*/
public static Base64 standard(boolean isPadded) {
if (isPadded) {
return standard();
} else {
return standardUnpadded();
}
}
/**
* Returns the {@code Base64} encoding with the url and filename safe
* alphabet.
*/
public static Base64 url() {
if (url == null) {
url = new Base64Url(true);
}
return url;
}
public static Base64 urlUnpadded() {
if (urlUnpadded == null) {
urlUnpadded = new Base64Url(false);
}
return urlUnpadded;
}
/**
* Returns the {@code Base64} encoding with the url and filename safe
* alphabet, and required padding, if {@code isPadded} is {@code true}.
*/
public static Base64 url(boolean isPadded) {
if (isPadded) {
return url();
} else {
return urlUnpadded();
}
}
}
final class Base64Standard extends Base64 {
final boolean isPadded;
Base64Standard(boolean isPadded) {
this.isPadded = isPadded;
}
@Override
public String alphabet() {
return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
}
@Override
public boolean isPadded() {
return this.isPadded;
}
public Base64 isPadded(boolean isPadded) {
if (isPadded == this.isPadded) {
return this;
} else {
return Base64.standard(isPadded);
}
}
@Override
public boolean isDigit(int c) {
return c >= '0' && c <= '9'
|| c >= 'A' && c <= 'Z'
|| c >= 'a' && c <= 'z'
|| c == '+' || c == '/';
}
}
final class Base64Url extends Base64 {
final boolean isPadded;
Base64Url(boolean isPadded) {
this.isPadded = isPadded;
}
@Override
public String alphabet() {
return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
}
@Override
public boolean isPadded() {
return this.isPadded;
}
public Base64 isPadded(boolean isPadded) {
if (isPadded == this.isPadded) {
return this;
} else {
return Base64.url(isPadded);
}
}
@Override
public boolean isDigit(int c) {
return c >= '0' && c <= '9'
|| c >= 'A' && c <= 'Z'
|| c >= 'a' && c <= 'z'
|| c == '-' || c == '_';
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base64Parser.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.codec;
final class Base64Parser<O> extends Parser<O> {
final Output<O> output;
final Base64 base64;
final int p;
final int q;
final int r;
final int step;
Base64Parser(Output<O> output, Base64 base64, int p, int q, int r, int step) {
this.output = output;
this.base64 = base64;
this.p = p;
this.q = q;
this.r = r;
this.step = step;
}
Base64Parser(Output<O> output, Base64 base64) {
this(output, base64, 0, 0, 0, 1);
}
@Override
public Parser<O> feed(Input input) {
return parse(input, this.output.clone(), this.base64, this.p, this.q, this.r, this.step);
}
static <O> Parser<O> parse(Input input, Output<O> output, Base64 base64, int p, int q, int r, int step) {
int c = 0;
while (!input.isEmpty()) {
if (step == 1) {
if (input.isCont()) {
c = input.head();
if (base64.isDigit(c)) {
input = input.step();
p = c;
step = 2;
} else {
return done(output.bind());
}
} else if (input.isDone()) {
return done(output.bind());
}
}
if (step == 2) {
if (input.isCont()) {
c = input.head();
if (base64.isDigit(c)) {
input = input.step();
q = c;
step = 3;
} else {
return error(Diagnostic.expected("base64 digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("base64 digit", input));
}
}
if (step == 3) {
if (input.isCont()) {
c = input.head();
if (base64.isDigit(c) || c == '=') {
input = input.step();
r = c;
if (c != '=') {
step = 4;
} else {
step = 5;
}
} else if (!base64.isPadded()) {
base64.writeQuantum(p, q, '=', '=', output);
return done(output.bind());
} else {
return error(Diagnostic.expected("base64 digit", input));
}
} else if (input.isDone()) {
if (!base64.isPadded()) {
base64.writeQuantum(p, q, '=', '=', output);
return done(output.bind());
} else {
return error(Diagnostic.expected("base64 digit", input));
}
}
}
if (step == 4) {
if (input.isCont()) {
c = input.head();
if (base64.isDigit(c) || c == '=') {
input = input.step();
base64.writeQuantum(p, q, r, c, output);
r = 0;
q = 0;
p = 0;
if (c != '=') {
step = 1;
} else {
return done(output.bind());
}
} else if (!base64.isPadded()) {
base64.writeQuantum(p, q, r, '=', output);
return done(output.bind());
} else {
return error(Diagnostic.expected("base64 digit", input));
}
} else if (input.isDone()) {
if (!base64.isPadded()) {
base64.writeQuantum(p, q, r, '=', output);
return done(output.bind());
} else {
return error(Diagnostic.expected("base64 digit", input));
}
}
} else if (step == 5) {
if (input.isCont()) {
c = input.head();
if (c == '=') {
input = input.step();
base64.writeQuantum(p, q, r, c, output);
r = 0;
q = 0;
p = 0;
return done(output.bind());
} else {
return error(Diagnostic.expected('=', input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected('=', input));
}
}
}
if (input.isError()) {
return error(input.trap());
}
return new Base64Parser<O>(output, base64, p, q, r, step);
}
static <O> Parser<O> parse(Input input, Output<O> output, Base64 base64) {
return parse(input, output, base64, 0, 0, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Base64Writer.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.codec;
import java.nio.ByteBuffer;
final class Base64Writer extends Writer<Object, Object> {
final Object value;
final ByteBuffer input;
final Base64 base64;
final int index;
final int limit;
final int step;
Base64Writer(Object value, ByteBuffer input, Base64 base64, int index, int limit, int step) {
this.value = value;
this.input = input;
this.base64 = base64;
this.index = index;
this.limit = limit;
this.step = step;
}
Base64Writer(Object value, ByteBuffer input, Base64 base64) {
this(value, input, base64, input.position(), input.limit(), 1);
}
Base64Writer(ByteBuffer input, Base64 base64) {
this(null, input, base64);
}
Base64Writer(Object value, byte[] input, Base64 base64) {
this(value, ByteBuffer.wrap(input), base64);
}
Base64Writer(byte[] input, Base64 base64) {
this(null, input, base64);
}
Base64Writer(Base64 base64) {
this(null, null, base64, 0, 0, 0);
}
@Override
public Writer<Object, Object> feed(Object value) {
if (value instanceof ByteBuffer) {
return new Base64Writer((ByteBuffer) value, this.base64);
} else if (value instanceof byte[]) {
return new Base64Writer((byte[]) value, this.base64);
} else {
throw new IllegalArgumentException(value.toString());
}
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.value, this.input, this.base64, this.index, this.limit, this.step);
}
static Writer<Object, Object> write(Output<?> output, Object value, ByteBuffer input,
Base64 base64, int index, int limit, int step) {
while (index + 2 < limit && output.isCont()) {
final int x = input.get(index) & 0xff;
final int y = input.get(index + 1) & 0xff;
final int z = input.get(index + 2) & 0xff;
if (step == 1 && output.isCont()) {
output = output.write(base64.encodeDigit(x >>> 2));
step = 2;
}
if (step == 2 && output.isCont()) {
output = output.write(base64.encodeDigit(((x << 4) | (y >>> 4)) & 0x3f));
step = 3;
}
if (step == 3 && output.isCont()) {
output = output.write(base64.encodeDigit(((y << 2) | (z >>> 6)) & 0x3f));
step = 4;
}
if (step == 4 && output.isCont()) {
output = output.write(base64.encodeDigit(z & 0x3f));
index += 3;
step = 1;
}
}
if (index + 1 < limit && output.isCont()) {
final int x = input.get(index) & 0xff;
final int y = input.get(index + 1) & 0xff;
if (step == 1 && output.isCont()) {
output = output.write(base64.encodeDigit(x >>> 2));
step = 2;
}
if (step == 2 && output.isCont()) {
output = output.write(base64.encodeDigit(((x << 4) | (y >>> 4)) & 0x3f));
step = 3;
}
if (step == 3 && output.isCont()) {
output = output.write(base64.encodeDigit((y << 2) & 0x3f));
step = 4;
}
if (step == 4) {
if (!base64.isPadded()) {
index += 2;
} else if (output.isCont()) {
output = output.write('=');
index += 2;
}
}
} else if (index < limit && output.isCont()) {
final int x = input.get(index) & 0xff;
if (step == 1 && output.isCont()) {
output = output.write(base64.encodeDigit(x >>> 2));
step = 2;
}
if (step == 2 && output.isCont()) {
output = output.write(base64.encodeDigit((x << 4) & 0x3f));
step = 3;
}
if (step == 3) {
if (!base64.isPadded()) {
index += 1;
} else if (output.isCont()) {
output = output.write('=');
step = 4;
}
}
if (step == 4 && output.isCont()) {
output = output.write('=');
index += 1;
}
}
if (index == limit) {
return done(value);
} else if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new Base64Writer(value, input, base64, index, limit, step);
}
static Writer<?, ?> write(Output<?> output, Object value, ByteBuffer input, Base64 base64) {
return write(output, value, input, base64, input.position(), input.limit(), 1);
}
static Writer<?, ?> write(Output<?> output, ByteBuffer input, Base64 base64) {
return write(output, null, input, base64);
}
static Writer<?, ?> write(Output<?> output, Object value, byte[] input, Base64 base64) {
return write(output, value, ByteBuffer.wrap(input), base64);
}
static Writer<?, ?> write(Output<?> output, byte[] input, Base64 base64) {
return write(output, null, input, base64);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Binary.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.codec;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
/**
* Byte {@link Input}/{@link Output} factory.
*
* <p>The {@code Binary.byteArrayOutput(...)} family of functions return an
* {@code Output} that writes bytes to a growable array, and {@link
* Output#bind() bind} a {@code byte[]} array containing all written bytes.</p>
*
* <p>The {@code Binary.byteBufferOutput(...)} family of functions return an
* {@code Output} that writes bytes to a growable array, and {@link
* Output#bind() bind} a {@code ByteBuffer} containing all written bytes.</p>
*/
public final class Binary {
private Binary() {
// nop
}
public static InputBuffer input(byte... bytes) {
return new ByteArrayInput(bytes, 0, bytes.length);
}
public static InputBuffer inputBuffer(byte[] array, int offset, int length) {
return new ByteArrayInput(array, offset, length);
}
public static InputBuffer inputBuffer(byte[] array) {
return new ByteArrayInput(array, 0, array.length);
}
public static InputBuffer inputBuffer(ByteBuffer buffer) {
return new ByteBufferInput(buffer);
}
public static OutputBuffer<ByteBuffer> outputBuffer(byte[] array, int offset, int length) {
return new ByteArrayOutput(array, offset, length);
}
public static OutputBuffer<ByteBuffer> outputBuffer(byte[] array) {
return new ByteArrayOutput(array, 0, array.length);
}
public static OutputBuffer<ByteBuffer> outputBuffer(ByteBuffer buffer) {
return new ByteBufferOutput(buffer);
}
/**
* Returns a new {@code Output} that appends bytes to a growable array,
* pre-allocated with space for {@code initialCapacity} bytes, using the
* given {@code settings}. The returned {@code Output} accepts an unbounded
* number of bytes, remaining permanently in the <em>cont</em> state, and can
* {@link Output#bind() bind} a {@code byte[]} array with the current output
* state at any time.
*/
public static Output<byte[]> byteArrayOutput(int initialCapacity, OutputSettings settings) {
if (initialCapacity < 0) {
throw new IllegalArgumentException(Integer.toString(initialCapacity));
}
return new ByteOutputArray(new byte[initialCapacity], 0, settings);
}
/**
* Returns a new {@code Output} that appends bytes to a growable array,
* pre-allocated with space for {@code initialCapacity} bytes. The returned
* {@code Output} accepts an unbounded number of bytes, remaining permanently
* in the <em>cont</em> state, and can {@link Output#bind() bind} a {@code
* byte[]} array with the current output state at any time.
*/
public static Output<byte[]> byteArrayOutput(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException(Integer.toString(initialCapacity));
}
return new ByteOutputArray(new byte[initialCapacity], 0, OutputSettings.standard());
}
/**
* Returns a new {@code Output} that appends bytes to a growable array,
* using the given {@code settings}. The returned {@code Output} accepts
* an unbounded number of bytes, remaining permanently in the <em>cont</em>
* state, and can {@link Output#bind() bind} a {@code byte[]} array with
* the current output state at any time.
*/
public static Output<byte[]> byteArrayOutput(OutputSettings settings) {
return new ByteOutputArray(null, 0, settings);
}
/**
* Returns a new {@code Output} that appends bytes to a growable array.
* The returned {@code Output} accepts an unbounded number of bytes,
* remaining permanently in the <em>cont</em> state, and can {@link
* Output#bind() bind} a {@code byte[]} array with the current output
* state at any time.
*/
public static Output<byte[]> byteArrayOutput() {
return new ByteOutputArray(null, 0, OutputSettings.standard());
}
/**
* Returns a new {@code Output} that appends bytes to a growable array,
* pre-allocated with space for {@code initialCapacity} bytes, using the
* given {@code settings}. The returned {@code Output} accepts an unbounded
* number of bytes, remaining permanently in the <em>cont</em> state, and can
* {@link Output#bind() bind} a {@code ByteBuffer} with the current output
* state at any time.
*/
public static Output<ByteBuffer> byteBufferOutput(int initialCapacity, OutputSettings settings) {
if (initialCapacity < 0) {
throw new IllegalArgumentException(Integer.toString(initialCapacity));
}
return new ByteOutputBuffer(new byte[initialCapacity], 0, settings);
}
/**
* Returns a new {@code Output} that appends bytes to a growable array,
* pre-allocated with space for {@code initialCapacity} bytes. The returned
* {@code Output} accepts an unbounded number of bytes, remaining permanently
* in the <em>cont</em> state, and can {@link Output#bind() bind} a {@code
* ByteBuffer} with the current output state at any time.
*/
public static Output<ByteBuffer> byteBufferOutput(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException(Integer.toString(initialCapacity));
}
return new ByteOutputBuffer(new byte[initialCapacity], 0, OutputSettings.standard());
}
/**
* Returns a new {@code Output} that appends bytes to a growable array,
* using the given {@code settings}. The returned {@code Output} accepts
* an unbounded number of bytes, remaining permanently in the <em>cont</em>
* state, and can {@link Output#bind() bind} a {@code ByteBuffer} with the
* current output state at any time.
*/
public static Output<ByteBuffer> byteBufferOutput(OutputSettings settings) {
return new ByteOutputBuffer(null, 0, settings);
}
/**
* Returns a new {@code Output} that appends bytes to a growable array.
* The returned {@code Output} accepts an unbounded number of bytes,
* remaining permanently in the <em>cont</em> state, and can {@link
* Output#bind() bind} a {@code ByteBuffer} with the current output
* state at any time.
*/
public static Output<ByteBuffer> byteBufferOutput() {
return new ByteOutputBuffer(null, 0, OutputSettings.standard());
}
/**
* Returns a new {@code Parser} that writes decoded bytes to the given
* {@code output}.
*/
public static <O> Parser<O> outputParser(Output<O> output) {
return new ByteParser<O>(output);
}
/**
* Writes the decoded bytes of the {@code input} buffer to the given {@code
* output}, returning a {@code Parser} continuation that knows how to decode
* subsequent input buffers.
*/
public static <O> Parser<O> parseOutput(Output<O> output, Input input) {
return ByteParser.parse(input, output);
}
@SuppressWarnings("unchecked")
public static Writer<byte[], ?> byteArrayWriter() {
return (Writer<byte[], ?>) (Writer<?, ?>) new ByteWriter();
}
@SuppressWarnings("unchecked")
public static Writer<Object, byte[]> byteArrayWriter(byte[] input) {
return (Writer<Object, byte[]>) (Writer<?, ?>) new ByteWriter(input, input);
}
@SuppressWarnings("unchecked")
public static <O> Writer<Object, O> byteArrayWriter(O value, byte[] input) {
return (Writer<Object, O>) (Writer<?, ?>) new ByteWriter(value, input);
}
@SuppressWarnings("unchecked")
public static Writer<ByteBuffer, Object> byteBufferWriter() {
return (Writer<ByteBuffer, Object>) (Writer<?, ?>) new ByteWriter();
}
@SuppressWarnings("unchecked")
public static Writer<Object, ByteBuffer> byteBufferWriter(ByteBuffer input) {
return (Writer<Object, ByteBuffer>) (Writer<?, ?>) new ByteWriter(input, input);
}
@SuppressWarnings("unchecked")
public static <O> Writer<Object, O> byteBufferEWriter(O value, ByteBuffer input) {
return (Writer<Object, O>) (Writer<?, ?>) new ByteWriter(value, input);
}
public static Writer<Object, Object> writeByteArray(byte[] input, Output<?> output) {
return ByteWriter.write(output, input);
}
public static Writer<Object, Object> writeByteBuffer(ByteBuffer input, Output<?> output) {
return ByteWriter.write(output, input);
}
public static Encoder<ReadableByteChannel, ReadableByteChannel> channelEncoder() {
return new ChannelEncoder();
}
public static Encoder<ReadableByteChannel, ReadableByteChannel> channelEncoder(ReadableByteChannel input) {
return new ChannelEncoder(input);
}
public static <O> Decoder<O> decode(Decoder<O> decoder, InputStream input) throws IOException {
final byte[] data = new byte[4096];
final InputBuffer buffer = Binary.inputBuffer(data);
do {
final int count = input.read(data);
buffer.index(0).limit(Math.max(0, count)).isPart(count >= 0);
decoder = decoder.feed(buffer);
if (!decoder.isCont()) {
return decoder;
}
} while (true);
}
public static <O> O read(Decoder<O> decoder, InputStream input) throws IOException {
decoder = decode(decoder, input);
if (decoder.isDone()) {
return decoder.bind();
} else {
final Throwable error = decoder.trap();
if (error instanceof RuntimeException) {
throw (RuntimeException) error;
} else {
throw new RuntimeException(error);
}
}
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteArrayInput.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.codec;
final class ByteArrayInput extends InputBuffer {
byte[] array;
int index;
int limit;
Object id;
long offset;
InputSettings settings;
boolean isPart;
ByteArrayInput(byte[] array, int index, int limit, Object id, long offset,
InputSettings settings, boolean isPart) {
this.array = array;
this.index = index;
this.limit = limit;
this.id = id;
this.offset = offset;
this.settings = settings;
this.isPart = isPart;
}
ByteArrayInput(byte[] array, int offset, int length) {
this(array, offset, offset + length, null, 0L, InputSettings.standard(), false);
}
@Override
public boolean isCont() {
return this.index < this.limit;
}
@Override
public boolean isEmpty() {
return this.isPart && this.index >= this.limit;
}
@Override
public boolean isDone() {
return !this.isPart && this.index >= this.limit;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return this.isPart;
}
@Override
public InputBuffer isPart(boolean isPart) {
this.isPart = isPart;
return this;
}
@Override
public int index() {
return this.index;
}
@Override
public InputBuffer index(int index) {
if (0 <= index && index <= this.limit) {
this.offset += (long) (index - this.index);
this.index = index;
return this;
} else {
final Throwable error = new InputException("invalid index");
return InputBuffer.error(error, this.id, mark(), this.settings);
}
}
@Override
public int limit() {
return this.limit;
}
@Override
public InputBuffer limit(int limit) {
if (0 <= limit && limit <= this.array.length) {
this.limit = limit;
return this;
} else {
final Throwable error = new InputException("invalid limit");
return InputBuffer.error(error, this.id, mark(), this.settings);
}
}
@Override
public int capacity() {
return this.array.length;
}
@Override
public int remaining() {
return this.limit - this.index;
}
@Override
public byte[] array() {
return this.array;
}
@Override
public int arrayOffset() {
return 0;
}
@Override
public boolean has(int index) {
return 0 <= index && index < this.limit;
}
@Override
public int get(int index) {
if (0 <= index && index < this.limit) {
return this.array[index] & 0xff;
} else {
throw new InputException();
}
}
@Override
public void set(int index, int token) {
if (0 <= index && index < this.limit) {
this.array[index] = (byte) token;
} else {
throw new InputException();
}
}
@Override
public int head() {
if (this.index < this.limit) {
return this.array[this.index] & 0xff;
} else {
throw new InputException();
}
}
@Override
public InputBuffer step() {
if (this.index < this.limit) {
this.index += 1;
this.offset += 1L;
return this;
} else {
final Throwable error = new InputException("invalid step");
return InputBuffer.error(error, this.id, mark(), this.settings);
}
}
@Override
public InputBuffer step(int offset) {
final int index = this.index + offset;
if (0 <= index && index <= this.limit) {
this.index = index;
this.offset += (long) offset;
return this;
} else {
final Throwable error = new InputException("invalid step");
return InputBuffer.error(error, this.id, mark(), this.settings);
}
}
@Override
public InputBuffer seek(Mark mark) {
if (mark != null) {
final long index = (long) this.index + (this.offset - mark.offset);
if (0L <= index && index <= (long) this.limit) {
this.index = (int) index;
this.offset = mark.offset;
return this;
} else {
final Throwable error = new InputException("invalid seek to " + mark);
return InputBuffer.error(error, this.id, mark(), this.settings);
}
} else {
this.offset -= (long) this.index;
this.index = 0;
return this;
}
}
@Override
public Object id() {
return this.id;
}
@Override
public InputBuffer id(Object id) {
this.id = id;
return this;
}
@Override
public Mark mark() {
return Mark.at(this.offset, 0, 0);
}
@Override
public InputBuffer mark(Mark mark) {
this.offset = mark.offset;
return this;
}
@Override
public long offset() {
return this.offset;
}
@Override
public int line() {
return 0;
}
@Override
public int column() {
return 0;
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public InputBuffer settings(InputSettings settings) {
this.settings = settings;
return this;
}
@Override
public InputBuffer clone() {
return new ByteArrayInput(this.array, this.index, this.limit, this.id,
this.offset, this.settings, this.isPart);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteArrayOutput.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.codec;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
final class ByteArrayOutput extends OutputBuffer<ByteBuffer> {
byte[] array;
int index;
int limit;
OutputSettings settings;
boolean isPart;
ByteArrayOutput(byte[] array, int index, int limit, OutputSettings settings, boolean isPart) {
this.array = array;
this.index = index;
this.limit = limit;
this.settings = settings;
this.isPart = isPart;
}
ByteArrayOutput(byte[] array, int offset, int length) {
this(array, offset, offset + length, OutputSettings.standard(), false);
}
@Override
public boolean isCont() {
return this.index < this.limit;
}
@Override
public boolean isFull() {
return this.isPart && this.index >= this.limit;
}
@Override
public boolean isDone() {
return !this.isPart && this.index >= this.limit;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return this.isPart;
}
@Override
public OutputBuffer<ByteBuffer> isPart(boolean isPart) {
this.isPart = isPart;
return this;
}
@Override
public int index() {
return this.index;
}
@Override
public OutputBuffer<ByteBuffer> index(int index) {
if (0 <= index && index <= this.limit) {
this.index = index;
return this;
} else {
return OutputBuffer.error(new OutputException("invalid index"), this.settings);
}
}
@Override
public int limit() {
return this.limit;
}
@Override
public OutputBuffer<ByteBuffer> limit(int limit) {
if (0 <= limit && limit <= this.array.length) {
this.limit = limit;
return this;
} else {
return OutputBuffer.error(new OutputException("invalid limit"), this.settings);
}
}
@Override
public int capacity() {
return this.array.length;
}
@Override
public int remaining() {
return this.limit - this.index;
}
@Override
public byte[] array() {
return this.array;
}
@Override
public int arrayOffset() {
return 0;
}
@Override
public boolean has(int index) {
return 0 <= index && index < this.limit;
}
@Override
public int get(int index) {
if (0 <= index && index < this.limit) {
return this.array[index] & 0xff;
} else {
throw new OutputException();
}
}
@Override
public void set(int index, int token) {
if (0 <= index && index < this.limit) {
this.array[index] = (byte) token;
} else {
throw new OutputException();
}
}
@Override
public int write(ReadableByteChannel channel) throws IOException {
final ByteBuffer buffer = ByteBuffer.wrap(this.array, this.index, this.limit - this.index);
try {
return channel.read(buffer);
} finally {
this.index = buffer.position();
this.limit = buffer.limit();
}
}
@Override
public OutputBuffer<ByteBuffer> write(int token) {
final int index = this.index;
if (index < this.limit) {
this.array[index] = (byte) token;
this.index = index + 1;
return this;
} else {
return OutputBuffer.error(new OutputException("full"), this.settings);
}
}
@Override
public OutputBuffer<ByteBuffer> write(String string) {
return OutputBuffer.error(new OutputException("binary output"), this.settings);
}
@Override
public OutputBuffer<ByteBuffer> writeln(String string) {
return OutputBuffer.error(new OutputException("binary output"), this.settings);
}
@Override
public OutputBuffer<ByteBuffer> writeln() {
return OutputBuffer.error(new OutputException("binary output"), this.settings);
}
@Override
public OutputBuffer<ByteBuffer> move(int fromIndex, int toIndex, int length) {
if (0 <= fromIndex && fromIndex <= this.limit) {
final int limit = toIndex + length;
if (0 <= limit && limit <= this.limit) {
System.arraycopy(this.array, fromIndex, this.array, toIndex, length);
return this;
}
}
return OutputBuffer.error(new OutputException("invalid move"), this.settings);
}
@Override
public OutputBuffer<ByteBuffer> step(int offset) {
final int index = this.index + offset;
if (0 <= index && index <= this.limit) {
this.index = index;
return this;
} else {
return OutputBuffer.error(new OutputException("invalid step"), this.settings);
}
}
@Override
public ByteBuffer bind() {
return ByteBuffer.wrap(this.array, 0, this.index);
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public OutputBuffer<ByteBuffer> settings(OutputSettings settings) {
this.settings = settings;
return this;
}
@Override
public OutputBuffer<ByteBuffer> clone() {
return new ByteArrayOutput(this.array, this.index, this.limit, this.settings, this.isPart);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteBufferInput.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.codec;
import java.nio.Buffer;
import java.nio.ByteBuffer;
final class ByteBufferInput extends InputBuffer {
ByteBuffer buffer;
Object id;
long offset;
InputSettings settings;
boolean isPart;
ByteBufferInput(ByteBuffer buffer, Object id, long offset,
InputSettings settings, boolean isPart) {
this.buffer = buffer;
this.id = id;
this.offset = offset;
this.settings = settings;
this.isPart = isPart;
}
ByteBufferInput(ByteBuffer buffer) {
this(buffer, null, 0L, InputSettings.standard(), false);
}
@Override
public boolean isCont() {
return this.buffer.hasRemaining();
}
@Override
public boolean isEmpty() {
return this.isPart && !this.buffer.hasRemaining();
}
@Override
public boolean isDone() {
return !this.isPart && !this.buffer.hasRemaining();
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return this.isPart;
}
@Override
public InputBuffer isPart(boolean isPart) {
this.isPart = isPart;
return this;
}
@Override
public int index() {
return this.buffer.position();
}
@Override
public InputBuffer index(int index) {
((Buffer) this.buffer).position(index);
return this;
}
@Override
public int limit() {
return this.buffer.limit();
}
@Override
public InputBuffer limit(int limit) {
((Buffer) this.buffer).limit(limit);
return this;
}
@Override
public int capacity() {
return this.buffer.capacity();
}
@Override
public int remaining() {
return this.buffer.remaining();
}
@Override
public byte[] array() {
return this.buffer.array();
}
@Override
public int arrayOffset() {
return this.buffer.arrayOffset();
}
@Override
public boolean has(int index) {
return 0 <= index && index < this.buffer.limit();
}
@Override
public int get(int index) {
if (0 <= index && index < this.buffer.limit()) {
return this.buffer.get(index) & 0xff;
} else {
throw new InputException();
}
}
@Override
public void set(int index, int token) {
if (0 <= index && index < this.buffer.limit()) {
this.buffer.put(index, (byte) token);
} else {
throw new InputException();
}
}
@Override
public int head() {
final ByteBuffer buffer = this.buffer;
final int position = buffer.position();
if (position < buffer.limit()) {
return buffer.get(position) & 0xff;
} else {
throw new InputException();
}
}
@Override
public InputBuffer step() {
final ByteBuffer buffer = this.buffer;
final int position = buffer.position();
if (position < buffer.limit()) {
((Buffer) buffer).position(position + 1);
this.offset += 1L;
return this;
} else {
final Throwable error = new InputException("invalid step");
return InputBuffer.error(error, this.id, mark(), this.settings);
}
}
@Override
public InputBuffer step(int offset) {
final ByteBuffer buffer = this.buffer;
final int position = buffer.position() + offset;
if (0 <= position && position <= buffer.limit()) {
((Buffer) buffer).position(position);
this.offset += (long) offset;
return this;
} else {
final Throwable error = new InputException("invalid step");
return InputBuffer.error(error, this.id, mark(), this.settings);
}
}
@Override
public InputBuffer seek(Mark mark) {
final ByteBuffer buffer = this.buffer;
if (mark != null) {
final long position = (long) buffer.position() + (this.offset - mark.offset);
if (0L <= position && position <= (long) buffer.limit()) {
((Buffer) buffer).position((int) position);
this.offset = mark.offset;
return this;
} else {
final Throwable error = new InputException("invalid seek to " + mark);
return InputBuffer.error(error, this.id, mark(), this.settings);
}
} else {
this.offset -= (long) buffer.position();
((Buffer) buffer).position(0);
return this;
}
}
@Override
public Object id() {
return this.id;
}
@Override
public InputBuffer id(Object id) {
this.id = id;
return this;
}
@Override
public Mark mark() {
return Mark.at(this.offset, 0, 0);
}
@Override
public InputBuffer mark(Mark mark) {
this.offset = mark.offset;
return this;
}
@Override
public long offset() {
return this.offset;
}
@Override
public int line() {
return 0;
}
@Override
public int column() {
return 0;
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public InputBuffer settings(InputSettings settings) {
this.settings = settings;
return this;
}
@Override
public InputBuffer clone() {
return new ByteBufferInput(this.buffer.duplicate(), this.id, this.offset,
this.settings, this.isPart);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteBufferOutput.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.codec;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
final class ByteBufferOutput extends OutputBuffer<ByteBuffer> {
ByteBuffer buffer;
OutputSettings settings;
boolean isPart;
ByteBufferOutput(ByteBuffer buffer, OutputSettings settings, boolean isPart) {
this.buffer = buffer;
this.settings = settings;
this.isPart = isPart;
}
ByteBufferOutput(ByteBuffer buffer) {
this(buffer, OutputSettings.standard(), false);
}
@Override
public boolean isCont() {
return this.buffer.hasRemaining();
}
@Override
public boolean isFull() {
return this.isPart && !this.buffer.hasRemaining();
}
@Override
public boolean isDone() {
return !this.isPart && !this.buffer.hasRemaining();
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return this.isPart;
}
@Override
public OutputBuffer<ByteBuffer> isPart(boolean isPart) {
this.isPart = isPart;
return this;
}
@Override
public int index() {
return this.buffer.position();
}
@Override
public OutputBuffer<ByteBuffer> index(int index) {
((Buffer) this.buffer).position(index);
return this;
}
@Override
public int limit() {
return this.buffer.limit();
}
@Override
public OutputBuffer<ByteBuffer> limit(int limit) {
this.buffer.limit(limit);
return this;
}
@Override
public int capacity() {
return this.buffer.capacity();
}
@Override
public int remaining() {
return this.buffer.remaining();
}
@Override
public byte[] array() {
return this.buffer.array();
}
@Override
public int arrayOffset() {
return this.buffer.arrayOffset();
}
@Override
public boolean has(int index) {
return 0 <= index && index < this.buffer.limit();
}
@Override
public int get(int index) {
if (0 <= index && index < this.buffer.limit()) {
return this.buffer.get(index) & 0xff;
} else {
throw new OutputException();
}
}
@Override
public void set(int index, int token) {
if (0 <= index && index < this.buffer.limit()) {
this.buffer.put(index, (byte) token);
} else {
throw new OutputException();
}
}
@Override
public int write(ReadableByteChannel channel) throws IOException {
return channel.read(this.buffer);
}
@Override
public OutputBuffer<ByteBuffer> write(int token) {
final int position = this.buffer.position();
if (position < this.buffer.limit()) {
this.buffer.put((byte) token);
return this;
} else {
return OutputBuffer.error(new OutputException("full"), this.settings);
}
}
@Override
public OutputBuffer<ByteBuffer> write(String string) {
return OutputBuffer.error(new OutputException("binary output"), this.settings);
}
@Override
public OutputBuffer<ByteBuffer> writeln(String string) {
return OutputBuffer.error(new OutputException("binary output"), this.settings);
}
@Override
public OutputBuffer<ByteBuffer> writeln() {
return OutputBuffer.error(new OutputException("binary output"), this.settings);
}
@Override
public OutputBuffer<ByteBuffer> move(int fromIndex, int toIndex, int length) {
if (0 <= fromIndex && fromIndex <= this.buffer.limit()) {
final int limit = toIndex + length;
if (0 <= limit && limit <= this.buffer.limit()) {
if (this.buffer.hasArray()) {
final byte[] array = this.buffer.array();
System.arraycopy(array, fromIndex, array, toIndex, length);
} else {
final ByteBuffer dup = this.buffer.duplicate();
((Buffer) dup).position(fromIndex).limit(fromIndex + length);
final int position = this.buffer.position();
((Buffer) this.buffer).position(toIndex);
this.buffer.put(dup);
((Buffer) this.buffer).position(position);
}
return this;
}
}
return OutputBuffer.error(new OutputException("invalid move"), this.settings);
}
@Override
public OutputBuffer<ByteBuffer> step(int offset) {
final int position = this.buffer.position() + offset;
if (0 <= position && position <= this.buffer.limit()) {
((Buffer) this.buffer).position(position);
return this;
} else {
return OutputBuffer.error(new OutputException("invalid step"), this.settings);
}
}
@Override
public ByteBuffer bind() {
final ByteBuffer dup = this.buffer.duplicate();
dup.flip();
return dup;
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public OutputBuffer<ByteBuffer> settings(OutputSettings settings) {
this.settings = settings;
return this;
}
@Override
public OutputBuffer<ByteBuffer> clone() {
return new ByteBufferOutput(this.buffer, this.settings, this.isPart);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteOutput.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.codec;
import java.nio.ByteBuffer;
abstract class ByteOutput<T> extends Output<T> {
byte[] array;
int size;
OutputSettings settings;
ByteOutput(byte[] array, int size, OutputSettings settings) {
this.array = array;
this.size = size;
this.settings = settings;
}
@Override
public final boolean isCont() {
return true;
}
@Override
public final boolean isFull() {
return false;
}
@Override
public final boolean isDone() {
return false;
}
@Override
public final boolean isError() {
return false;
}
@Override
public final boolean isPart() {
return false;
}
@Override
public final Output<T> isPart(boolean isPart) {
return this;
}
@Override
public final Output<T> write(int b) {
final int n = this.size;
final byte[] oldArray = this.array;
final byte[] newArray;
if (oldArray == null || n + 1 > oldArray.length) {
newArray = new byte[expand(n + 1)];
if (oldArray != null) {
System.arraycopy(oldArray, 0, newArray, 0, n);
}
this.array = newArray;
} else {
newArray = oldArray;
}
newArray[n] = (byte) b;
this.size = n + 1;
return this;
}
@Override
public Output<T> write(String string) {
throw new UnsupportedOperationException("binary output");
}
@Override
public Output<T> writeln(String string) {
throw new UnsupportedOperationException("binary output");
}
@Override
public Output<T> writeln() {
throw new UnsupportedOperationException("binary output");
}
final byte[] toByteArray() {
final int n = this.size;
final byte[] oldArray = this.array;
if (oldArray != null && n == oldArray.length) {
return oldArray;
} else {
final byte[] newArray = new byte[n];
if (oldArray != null) {
System.arraycopy(oldArray, 0, newArray, 0, n);
}
this.array = newArray;
return newArray;
}
}
final ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(this.array != null ? this.array : new byte[0], 0, this.size);
}
final byte[] cloneArray() {
final byte[] oldArray = this.array;
if (oldArray != null) {
final int n = this.size;
final byte[] newArray = new byte[n];
System.arraycopy(oldArray, 0, newArray, 0, n);
return newArray;
} else {
return null;
}
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public Output<T> settings(OutputSettings settings) {
this.settings = settings;
return this;
}
static int expand(int n) {
n = Math.max(32, n) - 1;
n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16;
return n + 1;
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteOutputArray.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.codec;
final class ByteOutputArray extends ByteOutput<byte[]> {
ByteOutputArray(byte[] array, int size, OutputSettings settings) {
super(array, size, settings);
}
@Override
public byte[] bind() {
return toByteArray();
}
@Override
public Output<byte[]> clone() {
return new ByteOutputArray(cloneArray(), this.size, this.settings);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteOutputBuffer.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.codec;
import java.nio.ByteBuffer;
final class ByteOutputBuffer extends ByteOutput<ByteBuffer> {
ByteOutputBuffer(byte[] array, int size, OutputSettings settings) {
super(array, size, settings);
}
@Override
public ByteBuffer bind() {
return toByteBuffer();
}
@Override
public Output<ByteBuffer> clone() {
return new ByteOutputBuffer(cloneArray(), this.size, this.settings);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteParser.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.codec;
final class ByteParser<O> extends Parser<O> {
final Output<O> output;
ByteParser(Output<O> output) {
this.output = output;
}
@Override
public Parser<O> feed(Input input) {
Output<O> output = this.output;
while (input.isCont() && output.isCont()) {
output = output.write(input.head());
input = input.step();
}
if (input.isDone()) {
return done(output.bind());
} else if (input.isError()) {
return error(input.trap());
} else if (output.isDone()) {
return error(new ParserException("incomplete"));
} else if (output.isError()) {
return error(output.trap());
}
return this;
}
static <O> Parser<O> parse(Input input, Output<O> output) {
while (input.isCont() && output.isCont()) {
output = output.write(input.head());
input = input.step();
}
if (input.isDone()) {
return done(output.bind());
} else if (input.isError()) {
return error(input.trap());
} else if (output.isDone()) {
return error(new ParserException("incomplete"));
} else if (output.isError()) {
return error(output.trap());
}
return new ByteParser<O>(output);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ByteWriter.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.codec;
import java.nio.ByteBuffer;
final class ByteWriter extends Writer<Object, Object> {
final Object value;
final Input input;
ByteWriter(Object value, Input input) {
this.value = value;
this.input = input;
}
ByteWriter(Object value, ByteBuffer input) {
this(value, Binary.inputBuffer(input));
}
ByteWriter(Object value, byte[] input) {
this(value, Binary.inputBuffer(input));
}
ByteWriter(Input input) {
this(null, input);
}
ByteWriter(ByteBuffer input) {
this(null, Binary.inputBuffer(input));
}
ByteWriter(byte[] input) {
this(null, Binary.inputBuffer(input));
}
ByteWriter() {
this(null, (Input) null);
}
@Override
public Writer<Object, Object> feed(Object value) {
if (value == null) {
return done();
} else if (value instanceof ByteBuffer) {
return new ByteWriter(((ByteBuffer) value).duplicate());
} else if (value instanceof byte[]) {
return new ByteWriter((byte[]) value);
} else {
throw new IllegalArgumentException(value.toString());
}
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.value, this.input.clone());
}
static Writer<Object, Object> write(Output<?> output, Object value, Input input) {
while (input.isCont() && output.isCont()) {
output = output.write(input.head());
input = input.step();
}
if (input.isDone() && !output.isError()) {
return done(value);
} else if (input.isError()) {
return error(input.trap());
} else if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new ByteWriter(value, input);
}
static Writer<Object, Object> write(Output<?> output, Object value, ByteBuffer input) {
return write(output, value, Binary.inputBuffer(input));
}
static Writer<Object, Object> write(Output<?> output, Object value, byte[] input) {
return write(output, value, Binary.inputBuffer(input));
}
static Writer<Object, Object> write(Output<?> output, ByteBuffer input) {
return write(output, null, Binary.inputBuffer(input));
}
static Writer<Object, Object> write(Output<?> output, byte[] input) {
return write(output, null, Binary.inputBuffer(input));
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ChannelEncoder.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.codec;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
final class ChannelEncoder extends Encoder<ReadableByteChannel, ReadableByteChannel> {
final ReadableByteChannel input;
ChannelEncoder(ReadableByteChannel input) {
this.input = input;
}
ChannelEncoder() {
this(null);
}
@Override
public Encoder<ReadableByteChannel, ReadableByteChannel> feed(ReadableByteChannel input) {
return new ChannelEncoder(input);
}
@Override
public Encoder<ReadableByteChannel, ReadableByteChannel> pull(OutputBuffer<?> output) {
final ReadableByteChannel input = this.input;
try {
final int k = output.write(input);
if (k < 0 || !output.isPart()) {
input.close();
return done(input);
} else if (output.isError()) {
input.close();
return error(output.trap());
} else {
return this;
}
} catch (IOException error) {
try {
input.close();
} catch (IOException ignore) {
// swallow
}
return error(error);
} catch (Throwable error) {
try {
input.close();
} catch (IOException ignore) {
// swallow
}
throw error;
}
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Debug.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.codec;
/**
* Type that can output a developer readable debug string. {@code Debug}
* implementations may use {@link Output#settings()} to tailor the format of
* their debug strings. For example, debug strings may be stylized when
* {@link OutputSettings#isStyled()} returns {@code true}.
*/
public interface Debug {
/**
* Writes a developer readable, debug-formatted string representation of this
* object to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full debug string has been written.
*/
void debug(Output<?> output);
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Decoder.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.codec;
/**
* Continuation of how to decode subsequent input buffers from a byte stream.
* {@code Decoder} enables efficient, interruptible decoding of network
* protocols and data formats, without intermediate buffer copying.
*
* <h3>Decoder states</h3>
* <p>A {@code Decoder} is always in one of three states: <em>cont</em>inue,
* <em>done</em>, or <em>error</em>. The <em>cont</em> state indicates that
* {@link #feed(InputBuffer) feed} is ready to consume input buffer data; the
* <em>done</em> state indicates that decoding terminated successfully, and that
* {@link #bind() bind} will return the decoded result; the <em>error</em> state
* indicates that decoding terminated in failure, and that {@link #trap() trap}
* will return the decode error. {@code Decoder} subclasses default to the
* <em>cont</em> state.</p>
*
* <h3>Feeding input</h3>
* <p>The {@link #feed(InputBuffer)} method incrementally decodes as much
* {@code InputBuffer} data as it can, before returning another {@code Decoder}
* that represents the continuation of how to decode additional {@code
* InputBuffer} data. The {@code InputBuffer} passed to {@code feed} is only
* guaranteed to be valid for the duration of the method call; references to
* the provided {@code InputBuffer} instance must not be stored.</p>
*
* <h3>Decoder results</h3>
* <p>A {@code Decoder} produces a decoded result of type {@code O}, obtained
* via the {@link #bind()} method. {@code bind} is only guaranteed to return
* a result when in the <em>done</em> state; though {@code bind} may optionally
* make available partial results in other states. A failed {@code Decoder}
* provides a decode error via the {@link #trap()} method. {@code trap} is
* only guaranteed to return an error when in the <em>error</em> state.</p>
*
* <h3>Continuations</h3>
* <p>A {@code Decoder} instance represents a continuation of how to decode
* remaining {@code InputBuffer} data. Rather than parsing a completely
* buffered input in one go, a {@code Decoder} takes a buffered chunk and
* returns another {@code Decoder} instance that knows how to decode subsequent
* buffered chunks. This enables non-blocking, incremental decoding that can
* be interrupted whenever an {@code InputBuffer} runs out of immediately
* available data. A {@code Decoder} terminates by returning a continuation
* in either the <em>done</em> state, or the <em>error</em> state. {@link
* Decoder#done(Object)} returns a {@code Decoder} in the <em>done</em> state.
* {@link Decoder#error(Throwable)} returns a {@code Decoder} in the
* <em>error</em> state.</p>
*
* <h3>Immutability</h3>
* <p>A {@code Decoder} should be immutable. Specifically, an invocation of
* {@code feed} should not alter the behavior of future calls to {@code feed}
* on the same {@code Decoder} instance. A {@code Decoder} should only mutate
* its internal state if it's essential to do so, such as for critical path
* performance reasons.</p>
*
* <h3>Forking</h3>
* <p>The {@link #fork(Object)} method passes an out-of-band condition to a
* {@code Decoder}, yielding a {@code Decoder} continuation whose behavior may
* be altered by the given condition. For example, a text {@code Decoder}
* might support a {@code fork} condition to change the character encoding.
* The types of conditions accepted by {@code fork}, and their intended
* semantics, are implementation defined.</p>
*/
public abstract class Decoder<O> {
/**
* Returns {@code true} when {@link #feed(InputBuffer) feed} is able to
* consume {@code InputBuffer} data. i.e. this {@code Decoder} is in the
* <em>cont</em> state.
*/
public boolean isCont() {
return true;
}
/**
* Returns {@code true} when decoding has terminated successfully, and {@link
* #bind() bind} will return the decoded result. i.e. this {@code Decoder}
* is in the <em>done</em> state.
*/
public boolean isDone() {
return false;
}
/**
* Returns {@code true} when decoding has terminated in failure, and {@link
* #trap() trap} will return the decode error. i.e. this {@code Decoder} is
* in the <em>error</em> state.
*/
public boolean isError() {
return false;
}
/**
* Incrementally decodes as much {@code input} buffer data as possible, and
* returns another {@code Decoder} that represents the continuation of how to
* decode additional buffer data. If {@code isLast} is {@code true}, then
* {@code feed} <em>must</em> return a terminated {@code Decoder}, i.e. a
* {@code Decoder} in the <em>done</em> state, or in the <em>error</em>
* state. The given {@code input} buffer is only guaranteed to be valid for
* the duration of the method call; references to {@code input} must not be
* stored.
*/
public abstract Decoder<O> feed(InputBuffer input);
/**
* Returns a {@code Decoder} continuation whose behavior may be altered by
* the given out-of-band {@code condition}.
*/
public Decoder<O> fork(Object condition) {
return this;
}
/**
* Returns the decoded result. Only guaranteed to return a result when in
* the <em>done</em> state.
*
* @throws IllegalStateException if this {@code Decoder} is not in the
* <em>done</em> state.
*/
public O bind() {
throw new IllegalStateException();
}
/**
* Returns the decode error. Only guaranteed to return an error when in the
* <em>error</em> state.
*
* @throws IllegalStateException if this {@code Decoder} is not in the
* <em>error</em> state.
*/
public Throwable trap() {
throw new IllegalStateException();
}
/**
* Casts an errored {@code Decoder} to a different output type.
* A {@code Decoder} in the <em>error</em> state can have any output type.
*
* @throws IllegalStateException if this {@code Decoder} is not in the
* <em>error</em> state.
*/
public <O> Decoder<O> asError() {
throw new IllegalStateException();
}
private static Decoder<Object> done;
/**
* Returns a {@code Decoder} in the <em>done</em> state that {@code bind}s
* a {@code null} decoded result.
*/
@SuppressWarnings("unchecked")
public static <O> Decoder<O> done() {
if (done == null) {
done = new DecoderDone<Object>(null);
}
return (Decoder<O>) done;
}
/**
* Returns a {@code Decoder} in the <em>done</em> state that {@code bind}s
* the given decoded {@code output}.
*/
public static <O> Decoder<O> done(O output) {
if (output == null) {
return done();
} else {
return new DecoderDone<O>(output);
}
}
/**
* Returns a {@code Decoder} in the <em>error</em> state that {@code trap}s
* the given decode {@code error}.
*/
public static <O> Decoder<O> error(Throwable error) {
return new DecoderError<O>(error);
}
}
final class DecoderDone<O> extends Decoder<O> {
private final O output;
DecoderDone(O output) {
this.output = output;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public Decoder<O> feed(InputBuffer input) {
return this;
}
@Override
public O bind() {
return this.output;
}
}
final class DecoderError<O> extends Decoder<O> {
private final Throwable error;
DecoderError(Throwable error) {
this.error = error;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isError() {
return true;
}
@Override
public Decoder<O> feed(InputBuffer input) {
return this;
}
@Override
public Throwable trap() {
return this.error;
}
@SuppressWarnings("unchecked")
@Override
public <O> Decoder<O> asError() {
return (Decoder<O>) this;
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/DecoderException.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.codec;
/**
* Thrown when a {@link Decoder} decodes invalid data.
*/
public class DecoderException extends RuntimeException {
private static final long serialVersionUID = 1L;
public DecoderException(String message, Throwable cause) {
super(message, cause);
}
public DecoderException(String message) {
super(message);
}
public DecoderException(Throwable cause) {
super(cause);
}
public DecoderException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Diagnostic.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.codec;
import java.util.Objects;
import swim.util.Severity;
/**
* Informational message attached to an input location.
*/
public final class Diagnostic implements Display {
final Input input;
final Tag tag;
final Severity severity;
final String message;
final String note;
final Diagnostic cause;
Diagnostic(Input input, Tag tag, Severity severity, String message,
String note, Diagnostic cause) {
this.input = input;
this.tag = tag;
this.severity = severity;
this.message = message;
this.note = note;
this.cause = cause;
}
/**
* Returns the {@code Input} source to which this diagnostic is attached.
*/
public Input input() {
return this.input.clone();
}
/**
* Returns the annotated location {@code Tag} in the {@code input} to which
* this diagnostic is attached.
*/
public Tag tag() {
return this.tag;
}
/**
* Returns the level of importance of this diagnostic.
*/
public Severity severity() {
return this.severity;
}
/**
* Returns the help message that describes this diagnostic.
*/
public String message() {
return this.message;
}
/**
* Returns an informative comment on the source context to which this
* diagnostic is attached.
*/
public String note() {
return this.note;
}
/**
* Returns the {@code Diagnostic} cause of this diagnostic, forming a linked
* chain of diagnostics, or {@code null} if this diagnostic has no cause.
*/
public Diagnostic cause() {
return this.cause;
}
private int lineDigits() {
int digits = Base10.countDigits(this.tag.end().line());
if (this.cause != null) {
digits = Math.max(digits, this.cause.lineDigits());
}
return digits;
}
@Override
public void display(Output<?> output) {
final Input input = this.input.clone();
final Mark start = this.tag.start();
final Mark end = this.tag.end();
final Severity severity = this.severity;
final String message = this.message;
final String note = this.note;
final Diagnostic cause = this.cause;
final int contextLines = 2;
final int lineDigits = lineDigits();
displayDiagnostic(input, start, end, severity, message, note, cause,
contextLines, lineDigits, output);
}
public String toString(OutputSettings settings) {
return Format.display(this, settings);
}
@Override
public String toString() {
return Format.display(this);
}
public static Diagnostic from(Input input, Tag tag, Severity severity,
String message, String note, Diagnostic cause) {
input = input.clone();
tag = Objects.requireNonNull(tag);
severity = Objects.requireNonNull(severity);
return new Diagnostic(input, tag, severity, message, note, cause);
}
public static Diagnostic from(Input input, Tag tag, Severity severity,
String message, String note) {
return from(input, tag, severity, message, note, null);
}
public static Diagnostic from(Input input, Tag tag, Severity severity,
String message, Diagnostic cause) {
return from(input, tag, severity, message, null, cause);
}
public static Diagnostic from(Input input, Tag tag, Severity severity, String message) {
return from(input, tag, severity, message, null, null);
}
public static Diagnostic from(Input input, Tag tag, Severity severity, Diagnostic cause) {
return from(input, tag, severity, null, null, cause);
}
public static Diagnostic from(Input input, Tag tag, Severity severity) {
return from(input, tag, severity, null, null, null);
}
public static Diagnostic message(String message, Input input, Severity severity, String note, Diagnostic cause) {
final Mark mark = input.mark();
final Input source = input.clone().seek(null);
return from(source, mark, severity, message, note, cause);
}
public static Diagnostic message(String message, Input input, Severity severity, String note) {
return message(message, input, severity, note, null);
}
public static Diagnostic message(String message, Input input, Severity severity, Diagnostic cause) {
return message(message, input, severity, null, cause);
}
public static Diagnostic message(String message, Input input, Severity severity) {
return message(message, input, severity, null, null);
}
public static Diagnostic message(String message, Input input, String note, Diagnostic cause) {
return message(message, input, Severity.error(), note, cause);
}
public static Diagnostic message(String message, Input input, String note) {
return message(message, input, Severity.error(), note, null);
}
public static Diagnostic message(String message, Input input, Diagnostic cause) {
return message(message, input, Severity.error(), null, cause);
}
public static Diagnostic message(String message, Input input) {
return message(message, input, Severity.error(), null, null);
}
public static Diagnostic unexpected(Input input, Severity severity, String note, Diagnostic cause) {
final String message;
if (input.isCont()) {
final Output<String> output = Unicode.stringOutput().write("unexpected").write(' ');
Format.debugChar(input.head(), output);
message = output.bind();
} else {
message = "unexpected end of input";
}
final Mark mark = input.mark();
final Input source = input.clone().seek(null);
return from(source, mark, severity, message, note, cause);
}
public static Diagnostic unexpected(Input input, Severity severity, String note) {
return unexpected(input, severity, note, null);
}
public static Diagnostic unexpected(Input input, Severity severity, Diagnostic cause) {
return unexpected(input, severity, null, cause);
}
public static Diagnostic unexpected(Input input, Severity severity) {
return unexpected(input, severity, null, null);
}
public static Diagnostic unexpected(Input input, String note, Diagnostic cause) {
return unexpected(input, Severity.error(), note, cause);
}
public static Diagnostic unexpected(Input input, String note) {
return unexpected(input, Severity.error(), note, null);
}
public static Diagnostic unexpected(Input input, Diagnostic cause) {
return unexpected(input, Severity.error(), null, cause);
}
public static Diagnostic unexpected(Input input) {
return unexpected(input, Severity.error(), null, null);
}
public static Diagnostic expected(int expected, Input input, Severity severity, String note, Diagnostic cause) {
Output<String> output = Unicode.stringOutput().write("expected").write(' ');
Format.debugChar(expected, output);
output = output.write(", ").write("but found").write(' ');
if (input.isCont()) {
Format.debugChar(input.head(), output);
} else {
output = output.write("end of input");
}
final String message = output.bind();
final Mark mark = input.mark();
final Input source = input.clone().seek(null);
return from(source, mark, severity, message, note, cause);
}
public static Diagnostic expected(int expected, Input input, Severity severity, String note) {
return expected(expected, input, severity, note, null);
}
public static Diagnostic expected(int expected, Input input, Severity severity, Diagnostic cause) {
return expected(expected, input, severity, null, cause);
}
public static Diagnostic expected(int expected, Input input, Severity severity) {
return expected(expected, input, severity, null, null);
}
public static Diagnostic expected(int expected, Input input, String note, Diagnostic cause) {
return expected(expected, input, Severity.error(), note, cause);
}
public static Diagnostic expected(int expected, Input input, String note) {
return expected(expected, input, Severity.error(), note, null);
}
public static Diagnostic expected(int expected, Input input, Diagnostic cause) {
return expected(expected, input, Severity.error(), null, cause);
}
public static Diagnostic expected(int expected, Input input) {
return expected(expected, input, Severity.error(), null, null);
}
public static Diagnostic expected(String expected, Input input, Severity severity, String note, Diagnostic cause) {
Output<String> output = Unicode.stringOutput().write("expected").write(' ').write(expected)
.write(", ").write("but found").write(' ');
if (input.isCont()) {
Format.debugChar(input.head(), output);
} else {
output = output.write("end of input");
}
final String message = output.bind();
final Mark mark = input.mark();
final Input source = input.clone().seek(null);
return from(source, mark, severity, message, note, cause);
}
public static Diagnostic expected(String expected, Input input, Severity severity, String note) {
return expected(expected, input, severity, note, null);
}
public static Diagnostic expected(String expected, Input input, Severity severity, Diagnostic cause) {
return expected(expected, input, severity, null, cause);
}
public static Diagnostic expected(String expected, Input input, Severity severity) {
return expected(expected, input, severity, null, null);
}
public static Diagnostic expected(String expected, Input input, String note, Diagnostic cause) {
return expected(expected, input, Severity.error(), note, cause);
}
public static Diagnostic expected(String expected, Input input, String note) {
return expected(expected, input, Severity.error(), note, null);
}
public static Diagnostic expected(String expected, Input input, Diagnostic cause) {
return expected(expected, input, Severity.error(), null, cause);
}
public static Diagnostic expected(String expected, Input input) {
return expected(expected, input, Severity.error(), null, null);
}
static void displayDiagnostic(Input input, Mark start, Mark end, Severity severity,
String message, String note, Diagnostic cause,
int contextLines, int lineDigits, Output<?> output) {
do {
if (message != null) {
displayMessage(severity, message, output);
output = output.writeln();
}
displayAnchor(input, start, lineDigits, output);
output = output.writeln();
final Diagnostic next = displayContext(input, start, end, severity, note,
cause, contextLines, lineDigits, output);
if (next != null) {
output = output.writeln();
input = next.input.clone();
start = next.tag.start();
end = next.tag.end();
severity = next.severity;
message = next.message;
note = next.note;
cause = next.cause;
} else {
break;
}
} while (true);
}
static void displayMessage(Severity severity, String message, Output<?> output) {
formatSeverity(severity, output);
output = output.write(severity.label());
OutputStyle.reset(output);
OutputStyle.bold(output);
output = output.write(':');
if (message != null) {
output = output.write(' ').write(message);
}
OutputStyle.reset(output);
}
static void displayAnchor(Input input, Mark start, int lineDigits, Output<?> output) {
displayLineLeadArrow(lineDigits, output);
output = output.write(' ');
final Object id = input.id();
if (id != null) {
Format.display(id, output);
}
output = output.write(':');
Format.displayInt(start.line, output);
output = output.write(':');
Format.displayInt(start.column, output);
output = output.writeln();
displayLineLead(lineDigits, output);
}
static Diagnostic displayCause(Diagnostic cause, int contextLines, int lineDigits, Output<?> output) {
final Input input = cause.input.clone();
final Mark start = cause.tag.start();
final Mark end = cause.tag.end();
final Severity severity = cause.severity;
final String note = cause.note;
final Diagnostic next = cause.cause;
return displayContext(input, start, end, severity, note, next, contextLines, lineDigits, output);
}
static Diagnostic displayContext(Input input, Mark start, Mark end, Severity severity,
String note, Diagnostic cause, int contextLines,
int lineDigits, Output<?> output) {
Diagnostic next = cause;
final boolean sameCause = cause != null && cause.message == null
&& Objects.equals(input.id(), cause.input.id());
final int causeOrder = sameCause ? (start.offset <= cause.tag.start().offset ? -1 : 1) : 0;
if (causeOrder == 1) {
next = displayCause(cause, contextLines, lineDigits, output);
output = output.writeln();
displayLineLeadEllipsis(lineDigits, output);
output = output.writeln();
}
displayLines(input, start, end, severity, contextLines, lineDigits, output);
if (note != null) {
displayNote(note, lineDigits, output);
}
if (causeOrder == -1) {
output = output.writeln();
displayLineLeadEllipsis(lineDigits, output);
output = output.writeln();
next = displayCause(cause, contextLines, lineDigits, output);
}
return next;
}
static void displayLines(Input input, Mark start, Mark end, Severity severity,
int contextLines, int lineDigits, Output<?> output) {
final int startLine = start.line();
final int endLine = end.line();
int line = input.line();
while (line < startLine) {
consumeLineText(input, line);
line += 1;
}
if (endLine - startLine > 2 * contextLines + 2) {
while (line <= startLine + contextLines) {
displayLine(input, start, end, severity, line, lineDigits, output);
line += 1;
}
displayLineLeadEllipsis(lineDigits, output);
output = output.write(' ');
formatSeverity(severity, output);
output = output.write('|');
OutputStyle.reset(output);
output = output.writeln();
while (line < endLine - contextLines) {
consumeLineText(input, line);
line += 1;
}
}
while (line <= endLine) {
displayLine(input, start, end, severity, line, lineDigits, output);
line += 1;
}
}
static void displayNote(String note, int lineDigits, Output<?> output) {
output = output.writeln();
displayLineLead(lineDigits, output);
output = output.writeln();
displayLineComment("note", note, lineDigits, output);
}
static void displayLine(Input input, Mark start, Mark end, Severity severity,
int line, int lineDigits, Output<?> output) {
if (start.line == line && end.line == line) {
displaySingleLine(input, start, end, severity, line, lineDigits, output);
} else if (start.line == line) {
displayStartLine(input, start, severity, line, lineDigits, output);
} else if (end.line == line) {
displayEndLine(input, end, severity, line, lineDigits, output);
} else {
displayMidLine(input, severity, line, lineDigits, output);
}
}
static void displaySingleLine(Input input, Mark start, Mark end, Severity severity,
int line, int lineDigits, Output<?> output) {
displayLineLeadNumber(line, lineDigits, output);
output = output.write(' ');
for (int i = 1; i < input.column(); i += 1) {
output = output.write(' ');
}
displayLineText(input, line, output);
displayLineLead(lineDigits, output);
output = output.write(' ');
int i = 1;
while (i < start.column) {
output = output.write(' ');
i += 1;
}
formatSeverity(severity, output);
while (i <= end.column) {
output = output.write('^');
i += 1;
}
if (end.note != null) {
output = output.write(' ').write(end.note);
}
OutputStyle.reset(output);
}
static void displayStartLine(Input input, Mark start, Severity severity,
int line, int lineDigits, Output<?> output) {
displayLineLeadNumber(line, lineDigits, output);
output = output.write(' ').write(' ').write(' ');
for (int i = 1; i < input.column(); i += 1) {
output = output.write(' ');
}
displayLineText(input, line, output);
displayLineLead(lineDigits, output);
output = output.write(' ').write(' ');
formatSeverity(severity, output);
output = output.write('_');
int i = 1;
while (i < start.column) {
output = output.write('_');
i += 1;
}
output = output.write('^');
if (start.note != null) {
output = output.write(' ').write(start.note);
}
OutputStyle.reset(output);
output = output.writeln();
}
static void displayEndLine(Input input, Mark end, Severity severity,
int line, int lineDigits, Output<?> output) {
displayLineLeadNumber(line, lineDigits, output);
output = output.write(' ');
formatSeverity(severity, output);
output = output.write('|');
OutputStyle.reset(output);
output = output.write(' ');
displayLineText(input, line, output);
displayLineLead(lineDigits, output);
output = output.write(' ');
formatSeverity(severity, output);
output = output.write('|').write('_');
int i = 1;
while (i < end.column) {
output = output.write('_');
i += 1;
}
output = output.write('^');
if (end.note != null) {
output = output.write(' ').write(end.note);
}
OutputStyle.reset(output);
}
static void displayMidLine(Input input, Severity severity,
int line, int lineDigits, Output<?> output) {
displayLineLeadNumber(line, lineDigits, output);
output = output.write(' ');
formatSeverity(severity, output);
output = output.write('|');
OutputStyle.reset(output);
output = output.write(' ');
displayLineText(input, line, output);
}
static void displayLineComment(String label, String comment,
int lineDigits, Output<?> output) {
displayLineLeadComment(lineDigits, output);
output = output.write(' ');
OutputStyle.bold(output);
output = output.write(label).write(':');
OutputStyle.reset(output);
if (comment != null) {
output = output.write(' ').write(comment);
}
}
static void displayLineLead(int lineDigits, Output<?> output) {
OutputStyle.blueBold(output);
final int padding = 1 + lineDigits;
for (int i = 0; i < padding; i += 1) {
output = output.write(' ');
}
output = output.write('|');
OutputStyle.reset(output);
}
static void displayLineLeadComment(int lineDigits, Output<?> output) {
OutputStyle.blueBold(output);
final int padding = 1 + lineDigits;
for (int i = 0; i < padding; i += 1) {
output = output.write(' ');
}
output = output.write('=');
OutputStyle.reset(output);
}
static void displayLineLeadArrow(int lineDigits, Output<?> output) {
for (int i = 0; i < lineDigits; i += 1) {
output = output.write(' ');
}
OutputStyle.blueBold(output);
output = output.write('-').write('-').write('>');
OutputStyle.reset(output);
}
static void displayLineLeadEllipsis(int lineDigits, Output<?> output) {
OutputStyle.blueBold(output);
for (int i = 0; i < lineDigits; i += 1) {
output = output.write('.');
}
OutputStyle.reset(output);
output = output.write(' ').write(' ');
}
static void displayLineLeadNumber(int line, int lineDigits, Output<?> output) {
final int padding = lineDigits - Base10.countDigits(line);
for (int i = 0; i < padding; i += 1) {
output = output.write(' ');
}
OutputStyle.blueBold(output);
Format.displayInt(line, output);
output = output.write(' ').write('|');
OutputStyle.reset(output);
}
static void displayLineText(Input input, int line, Output<?> output) {
while (input.isCont() && input.line() == line) {
output = output.write(input.head());
input = input.step();
}
if (input.line() == line) {
output = output.writeln();
}
}
static void consumeLineText(Input input, int line) {
while (input.isCont() && input.line() == line) {
input = input.step();
}
}
static void formatSeverity(Severity severity, Output<?> output) {
switch (severity.level()) {
case Severity.FATAL_LEVEL:
case Severity.ALERT_LEVEL:
case Severity.ERROR_LEVEL:
OutputStyle.redBold(output);
break;
case Severity.WARNING_LEVEL:
OutputStyle.yellowBold(output);
break;
case Severity.NOTE_LEVEL:
OutputStyle.greenBold(output);
break;
case Severity.INFO_LEVEL:
OutputStyle.cyanBold(output);
break;
case Severity.DEBUG_LEVEL:
case Severity.TRACE_LEVEL:
default:
OutputStyle.magentaBold(output);
}
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Display.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.codec;
/**
* Type that can output a human readable display string. {@code Display}
* implementations may use {@link Output#settings()} to tailor the format of
* their display strings. For example, display strings may be stylized when
* {@link OutputSettings#isStyled()} returns {@code true}.
*/
public interface Display {
/**
* Writes a human readable, display-formatted string representation of this
* object to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full display string has been written.
*/
void display(Output<?> output);
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/DynamicDecoder.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.codec;
/**
* Dynamically generated {@link Decoder} continuation.
*/
public abstract class DynamicDecoder<O> extends Decoder<O> {
/**
* Current decoder continuation.
*/
protected Decoder<? extends O> decoding;
@Override
public Decoder<O> feed(InputBuffer input) {
Decoder<? extends O> decoder = this.decoding;
if (decoder == null) {
if (input.isDone()) {
return done();
}
decoder = doDecode();
this.decoding = decoder;
if (decoder == null) {
return done();
}
}
if (decoder != null) {
decoder = decoder.feed(input);
if (decoder.isDone()) {
this.decoding = null;
didDecode(decoder.bind());
} else if (decoder.isError()) {
return decoder.asError();
}
}
if (input.isDone()) {
return done();
}
return this;
}
@Override
public Decoder<O> fork(Object condition) {
if (this.decoding != null) {
this.decoding = this.decoding.fork(condition);
}
return this;
}
@Override
public O bind() {
if (this.decoding != null) {
return this.decoding.bind();
} else {
throw new IllegalStateException();
}
}
@Override
public Throwable trap() {
if (this.decoding != null) {
return this.decoding.trap();
} else {
throw new IllegalStateException();
}
}
/**
* Returns a new {@code Decoder} continuation for this {@code DynamicDecoder},
* or {@code null} if this {@code DynamicDecoder} is done.
*/
protected abstract Decoder<? extends O> doDecode();
/**
* Lifecycle callback invoked after this {@code DynamicDecoder} has finished
* decoding a {@code value}.
*/
protected abstract void didDecode(O value);
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/DynamicEncoder.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.codec;
/**
* Dynamically generated {@link Encoder} continuation.
*/
public abstract class DynamicEncoder<I, O> extends Encoder<I, O> {
/**
* Current encoder continuation.
*/
protected Encoder<? super I, ? extends O> encoding;
@Override
public Encoder<I, O> feed(I input) {
if (this.encoding != null) {
this.encoding = this.encoding.feed(input);
return this;
} else {
throw new IllegalStateException();
}
}
@Override
public Encoder<I, O> pull(OutputBuffer<?> output) {
Encoder<? super I, ? extends O> encoder = this.encoding;
if (encoder == null) {
if (output.isDone()) {
return done();
}
encoder = doEncode();
this.encoding = encoder;
if (encoder == null) {
return done();
}
}
if (encoder != null) {
encoder = encoder.pull(output);
if (encoder.isDone()) {
this.encoding = null;
didEncode(encoder.bind());
} else if (encoder.isError()) {
return encoder.asError();
}
}
if (output.isDone()) {
return done();
}
return this;
}
@Override
public Encoder<I, O> fork(Object condition) {
if (this.encoding != null) {
this.encoding = this.encoding.fork(condition);
}
return this;
}
@Override
public O bind() {
if (this.encoding != null) {
return this.encoding.bind();
} else {
throw new IllegalStateException();
}
}
@Override
public Throwable trap() {
if (this.encoding != null) {
return this.encoding.trap();
} else {
throw new IllegalStateException();
}
}
/**
* Returns a new {@code Encoder} continuation for this {@code DynamicEncoder},
* or {@code null} if this {@code DynamicEncoder} is done.
*/
protected abstract Encoder<? super I, ? extends O> doEncode();
/**
* Lifecycle callback invoked after this {@code DynamicEncoder} has finished
* encoding a {@code value}.
*/
protected abstract void didEncode(O value);
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Encoder.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.codec;
/**
* Continuation of how encode subsequent output buffers for a byte stream.
* {@code Encoder} enables efficient, interruptible encoding of network
* protocols and data formats, without intermediate buffer copying.
*
* <h3>Encoder states</h3>
* <p>An {@code Encoder} is always in one of three states: <em>cont</em>inue,
* <em>done</em>, or <em>error</em>. The <em>cont</em> state indicates that
* {@link #pull(OutputBuffer) pull} is ready to produce buffer data; the
* <em>done</em> state indicates that encoding terminated successfully, and that
* {@link #bind() bind} will return the encoded result; the <em>error</em>
* state indicates that encoding terminated in failure, and that {@link #trap()
* trap} will return the encode error. {@code Encoder} subclasses default to
* the <em>cont</em> state.</p>
*
* <h3>Feeding input</h3>
* <p>The {@link #feed(Object) feed(I)} method returns an {@code Encoder} that
* represents the continuation of how to encode the given input object to
* subsequent output buffers. {@code feed} can be used to specify an initial
* object to encode, or to change the object to be encoded.</p>
*
* <h3>Pulling output</h3>
* <p>The {@link #pull(OutputBuffer)} method incrementally encodes as much
* buffer data as it can, before returning another {@code Encoder} that
* represents the continuation of how to encoded additional buffer data.
* The buffer passed to {@code pull} is only guaranteed to be valid for the
* duration of the method call; references to the provided buffer must not be
* stored.</p>
*
* <h3>Encoder results</h3>
* <p>An {@code Encoder} produces an encoded result of type {@code O}, obtained
* via the {@link #bind()} method. {@code bind} is only guaranteed to return a
* result when in the <em>done</em> state; though {@code bind} may optionally
* make available partial results in other states. A failed {@code Encoder}
* provides a write error via the {@link #trap()} method. {@code trap} is only
* guaranteed to return an error when in the <em>error</em> state.</p>
*
* <h3>Continuations</h3>
* <p>An {@code Encoder} instance represents a continuation of how to encode
* remaining buffer data. Rather than encoding a completely buffered output in
* one go, an {@code Encoder} takes a buffer chunk and returns another {@code
* Encoder} instance that knows how to write subsequent buffer chunks.
* This enables non-blocking, incremental encoding that can be interrupted
* whenever an output buffer runs out of space. An {@code Encoder} terminates
* by returning a continuation in either the <em>done</em> state, or the
* <em>error</em> state. {@link Encoder#done(Object)} returns an {@code
* Encoder} in the <em>done</em> state. {@link Encoder#error(Throwable)}
* returns an {@code Encoder} in the <em>error</em> state.</p>
*
* <h3>Forking</h3>
* <p>The {@link #fork(Object)} method passes an out-of-band condition to an
* {@code Encoder}, yielding an {@code Encoder} continuation whose behavior may
* be altered by the given condition. For example, a text {@code Encoder}
* might support a {@code fork} condition to change the character encoding.
* The types of conditions accepted by {@code fork}, and their intended
* semantics, are implementation defined.</p>
*/
public abstract class Encoder<I, O> {
/**
* Returns {@code true} when {@link #pull(OutputBuffer) pull} is able to
* produce buffer data. i.e. this {@code Encoder} is in the <em>cont</em>
* state.
*/
public boolean isCont() {
return true;
}
/**
* Returns {@code true} when encoding has terminated successfully, and {@link
* #bind() bind} will return the encoded result. i.e. this {@code Encoder} is
* in the <em>done</em> state.
*/
public boolean isDone() {
return false;
}
/**
* Returns {@code true} when encoding has terminated in failure, and {@link
* #trap() trap} will return the encode error. i.e. this {@code Encoder} is
* in the <em>error</em> state.
*/
public boolean isError() {
return false;
}
/**
* Returns an {@code Encoder} that represents the continuation of how to
* encode the given {@code input} object.
*
* @throws IllegalArgumentException if this {@code Encoder} does not know how
* to encode the given {@code input} object.
*/
public Encoder<I, O> feed(I input) {
throw new IllegalStateException();
}
/**
* Incrementally encodes as much {@code output} buffer data as possible, and
* returns another {@code Encoder} that represents the continuation of how to
* write additional buffer data. If {@code isLast} is {@code true}, then
* {@code pull} <em>must</em> return a terminated {@code Encoder}, i.e. an
* {@code Encoder} in the <em>done</em> state, or in the <em>error</em> state.
* The given {@code output} buffer is only guaranteed to be valid for the
* duration of the method call; references to {@code output} must not be
* stored.
*/
public abstract Encoder<I, O> pull(OutputBuffer<?> output);
/**
* Returns an {@code Encoder} continuation whose behavior may be altered by
* the given out-of-band {@code condition}.
*/
public Encoder<I, O> fork(Object condition) {
return this;
}
/**
* Returns the encoded result. Only guaranteed to return a result when in
* the <em>done</em> state.
*
* @throws IllegalStateException if this {@code Encoder} is not in the
* <em>done</em> state.
*/
public O bind() {
return null;
}
/**
* Returns the encode error. Only guaranteed to return an error when in the
* <em>error</em> state.
*
* @throws IllegalStateException if this {@code Encoder} is not in the
* <em>error</em> state.
*/
public Throwable trap() {
throw new IllegalStateException();
}
/**
* Casts a done {@code Encoder} to a different input type.
* An {@code Encoder} in the <em>done</em> state can have any input type.
*
* @throws IllegalStateException if this {@code Encoder} is not in the
* <em>done</em> state.
*/
public <I2> Encoder<I2, O> asDone() {
throw new IllegalStateException();
}
/**
* Casts an errored {@code Encoder} to different input and output types.
* An {@code Encoder} in the <em>error</em> state can have any input type,
* and any output type.
*
* @throws IllegalStateException if this {@code Encoder} is not in the
* <em>error</em> state.
*/
public <I2, O2> Encoder<I2, O2> asError() {
throw new IllegalStateException();
}
/**
* Returns an {@code Encoder} that continues encoding {@code that} {@code
* Encoder}, after it finishes encoding {@code this} {@code Encoder}.
*/
public <O2> Encoder<I, O2> andThen(Encoder<I, O2> that) {
return new EncoderAndThen<I, O2>(this, that);
}
private static Encoder<Object, Object> done;
/**
* Returns an {@code Encoder} in the <em>done</em> state that {@code bind}s
* a {@code null} encoded result.
*/
@SuppressWarnings("unchecked")
public static <I, O> Encoder<I, O> done() {
if (done == null) {
done = new EncoderDone<Object, Object>(null);
}
return (Encoder<I, O>) done;
}
/**
* Returns an {@code Encoder} in the <em>done</em> state that {@code bind}s
* the given encoded {@code output}.
*/
public static <I, O> Encoder<I, O> done(O output) {
if (output == null) {
return done();
} else {
return new EncoderDone<I, O>(output);
}
}
/**
* Returns an {@code Encoder} in the <em>error</em> state that {@code trap}s
* the given encode {@code error}.
*/
public static <I, O> Encoder<I, O> error(Throwable error) {
return new EncoderError<I, O>(error);
}
}
final class EncoderDone<I, O> extends Encoder<I, O> {
private final O output;
EncoderDone(O output) {
this.output = output;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public Encoder<I, O> pull(OutputBuffer<?> output) {
return this;
}
@Override
public O bind() {
return this.output;
}
@SuppressWarnings("unchecked")
@Override
public <I2> Encoder<I2, O> asDone() {
return (Encoder<I2, O>) this;
}
@Override
public <O2> Encoder<I, O2> andThen(Encoder<I, O2> that) {
return that;
}
}
final class EncoderError<I, O> extends Encoder<I, O> {
private final Throwable error;
EncoderError(Throwable error) {
this.error = error;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isError() {
return true;
}
@Override
public Encoder<I, O> pull(OutputBuffer<?> output) {
return this;
}
@Override
public Throwable trap() {
return this.error;
}
@SuppressWarnings("unchecked")
@Override
public <I2, O2> Encoder<I2, O2> asError() {
return (Encoder<I2, O2>) this;
}
@SuppressWarnings("unchecked")
@Override
public <O2> Encoder<I, O2> andThen(Encoder<I, O2> that) {
return (Encoder<I, O2>) this;
}
}
final class EncoderAndThen<I, O> extends Encoder<I, O> {
private final Encoder<I, ?> head;
private final Encoder<I, O> tail;
EncoderAndThen(Encoder<I, ?> head, Encoder<I, O> tail) {
this.head = head;
this.tail = tail;
}
@Override
public Encoder<I, O> pull(OutputBuffer<?> output) {
Encoder<I, ?> head = this.head;
if (head.isCont()) {
head = head.pull(output);
}
if (head.isDone()) {
return this.tail;
} else if (head.isError()) {
return head.asError();
} else {
return new EncoderAndThen<I, O>(head, this.tail);
}
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/EncoderException.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.codec;
/**
* Thrown when an {@link Encoder} encodes invalid data.
*/
public class EncoderException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EncoderException(String message, Throwable cause) {
super(message, cause);
}
public EncoderException(String message) {
super(message);
}
public EncoderException(Throwable cause) {
super(cause);
}
public EncoderException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Format.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.codec;
/**
* Text format utility functions.
*/
public final class Format {
private Format() {
}
/**
* Writes the code points of the human-readable {@link Display} string for
* the given {@code object} to {@code output}. Assumes {@code output} is
* a Unicode {@code Output} writer with sufficient capacity. Delegates to
* {@link Display#display(Output)}, if {@code object} implements {@code
* Display}; otherwise writes the result of {@link Object#toString()}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full display string has been written.
*/
public static void display(Object object, Output<?> output) {
if (object == null) {
output = output.write("null");
} else if (object instanceof Integer) {
displayInt(((Integer) object).intValue(), output);
} else if (object instanceof Long) {
displayLong(((Long) object).longValue(), output);
} else if (object instanceof Display) {
((Display) object).display(output);
} else {
output = output.write(object.toString());
}
}
/**
* Returns the human-readable {@link Display} string for the givem {@code
* object}, output using the given {@code settings}. Delegates to {@link
* Display#display(Output)}, if {@code object} implements {@code Display};
* otherwise returns the result of {@link Object#toString()}.
*/
public static String display(Object object, OutputSettings settings) {
final Output<String> output;
if (object == null) {
return "null";
} else if (object instanceof Display) {
output = Unicode.stringOutput(settings);
((Display) object).display(output);
return output.bind();
} else {
return object.toString();
}
}
/**
* Returns the human-readable {@link Display} string for the givem {@code
* object}, output using {@link OutputSettings#standard() standard} settings.
*
* @see #display(Object, OutputSettings)
*/
public static String display(Object object) {
return display(object, OutputSettings.standard());
}
/**
* Writes the code points of the developer-readable {@link Debug} string for
* the given {@code object} to {@code output}. Assumes {@code output} is a
* Unicode {@code Output} writer with sufficient capacity. Delegates to
* {@link Debug#debug(Output)}, if {@code object} implements {@code Debug};
* writes a Java string literal, if {@code object} is a {@code String}, and
* writes a Java number literal, if {@code object} is a {@code Number};
* otherwise writes the result of {@link Object#toString()}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full debug string has been written.
*/
public static void debug(Object object, Output<?> output) {
if (object == null) {
output = output.write("null");
} else if (object instanceof Integer) {
debugInt(((Integer) object).intValue(), output);
} else if (object instanceof Long) {
debugLong(((Long) object).longValue(), output);
} else if (object instanceof Float) {
debugFloat(((Float) object).floatValue(), output);
} else if (object instanceof Character) {
debugChar((int) ((Character) object).charValue(), output);
} else if (object instanceof String) {
debugString((String) object, output);
} else if (object instanceof Debug) {
((Debug) object).debug(output);
} else {
output = output.write(object.toString());
}
}
/**
* Returns the developer-readable {@link Display} string for the givem {@code
* object}, output using the given {@code settings}. Delegates to {@link
* Debug#debug(Output)}, if {@code object} implements {@code Debug}; returns
* a Java string literal, if {@code object} is a {@code String}, and returns
* a Java number literal, if {@code object} is a {@code Number}; otherwise
* returns the result of {@link Object#toString()}.
*/
public static String debug(Object object, OutputSettings settings) {
final Output<String> output;
if (object == null) {
return "null";
} else if (object instanceof Integer) {
output = Unicode.stringOutput(settings);
debugInt(((Integer) object).intValue(), output);
return output.bind();
} else if (object instanceof Long) {
output = Unicode.stringOutput(settings);
debugLong(((Long) object).longValue(), output);
return output.bind();
} else if (object instanceof Float) {
output = Unicode.stringOutput(settings);
debugFloat(((Float) object).floatValue(), output);
return output.bind();
} else if (object instanceof Character) {
output = Unicode.stringOutput(settings);
debugChar((int) ((Character) object).charValue(), output);
return output.bind();
} else if (object instanceof String) {
output = Unicode.stringOutput(settings);
debugString((String) object, output);
return output.bind();
} else if (object instanceof Debug) {
output = Unicode.stringOutput(settings);
((Debug) object).debug(output);
return output.bind();
} else {
return object.toString();
}
}
/**
* Returns the human-readable {@link Debug} string for the givem {@code
* object}, output using {@link OutputSettings#standard() standard} settings.
*
* @see #debug(Object, OutputSettings)
*/
public static String debug(Object object) {
return debug(object, OutputSettings.standard());
}
/**
* Writes the code points of the numeric string for the given {@code value}
* to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full numeric string has been written.
*/
public static void displayInt(int value, Output<?> output) {
if (value < 0) {
output = output.write('-');
}
if (value > -10 && value < 10) {
output = output.write('0' + Math.abs(value));
} else {
final byte[] digits = new byte[10];
long x = value;
int i = 9;
while (x != 0) {
digits[i] = (byte) Math.abs(x % 10);
x /= 10;
i -= 1;
}
i += 1;
while (i < 10) {
output = output.write('0' + digits[i]);
i += 1;
}
}
}
/**
* Writes the code points of the numeric string for the given {@code value}
* to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full numeric string has been written.
*/
public static void displayLong(long value, Output<?> output) {
if (value < 0L) {
output = output.write('-');
}
if (value > -10L && value < 10L) {
output = output.write('0' + Math.abs((int) value));
} else {
final byte[] digits = new byte[19];
long x = value;
int i = 18;
while (x != 0L) {
digits[i] = (byte) Math.abs((int) (x % 10L));
x /= 10L;
i -= 1;
}
i += 1;
while (i < 19) {
output = output.write('0' + digits[i]);
i += 1;
}
}
}
/**
* Writes the code points of the numeric string for the given {@code value}
* to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full numeric string has been written.
*/
public static void displayFloat(float value, Output<?> output) {
output = output.write(Float.toString(value)).write('f');
}
/**
* Writes the code points of the numeric string for the given {@code value}
* to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full numeric string has been written.
*/
public static void displayDouble(double value, Output<?> output) {
output = output.write(Double.toString(value));
}
/**
* Writes the code points of the Java numeric literal for the given
* {@code value} to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full numeric literal has been written.
*/
public static void debugInt(int value, Output<?> output) {
displayInt(value, output);
}
/**
* Writes the code points of the Java numeric literal for the given
* {@code value} to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full numeric literal has been written.
*/
public static void debugLong(long value, Output<?> output) {
displayLong(value, output);
output = output.write('L');
}
/**
* Writes the code points of the Java numeric literal for the given
* {@code value} to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full numeric literal has been written.
*/
public static void debugFloat(float value, Output<?> output) {
output = output.write(Float.toString(value)).write('f');
}
/**
* Writes the code points of the Java numeric literal for the given
* {@code value} to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full numeric literal has been written.
*/
public static void debugDouble(double value, Output<?> output) {
output = output.write(Double.toString(value));
}
/**
* Writes the code points of the Java character literal for the given
* {@code character} to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full character literal has been written.
*/
public static void debugChar(int character, Output<?> output) {
output = output.write('\'');
switch (character) {
case '\b': output.write('\\').write('b'); break;
case '\t': output.write('\\').write('t'); break;
case '\n': output.write('\\').write('n'); break;
case '\f': output.write('\\').write('f'); break;
case '\r': output.write('\\').write('r'); break;
case '\"': output.write('\\').write('\"'); break;
case '\'': output.write('\\').write('\''); break;
case '\\': output.write('\\').write('\\'); break;
default:
if (character >= 0x0000 && character <= 0x001f
|| character >= 0x007f && character <= 0x009f) {
output = output.write('\\').write('u')
.write(encodeHex(character >>> 12 & 0xf))
.write(encodeHex(character >>> 8 & 0xf))
.write(encodeHex(character >>> 4 & 0xf))
.write(encodeHex(character & 0xf));
} else {
output = output.write(character);
}
}
output = output.write('\'');
}
/**
* Writes the code points of the Java string literal for the given
* {@code string} to {@code output}.
*
* @throws OutputException if the {@code output} exits the <em>cont</em>
* state before the full string literal has been written.
*/
public static void debugString(String string, Output<?> output) {
output = output.write('\"');
final int n = string.length();
for (int i = 0; i < n; i = string.offsetByCodePoints(i, 1)) {
final int c = string.codePointAt(i);
switch (c) {
case '\b': output.write('\\').write('b'); break;
case '\t': output.write('\\').write('t'); break;
case '\n': output.write('\\').write('n'); break;
case '\f': output.write('\\').write('f'); break;
case '\r': output.write('\\').write('r'); break;
case '\"': output.write('\\').write('\"'); break;
case '\\': output.write('\\').write('\\'); break;
default:
if (c >= 0x0000 && c <= 0x001f || c >= 0x007f && c <= 0x009f) {
output = output.write('\\').write('u')
.write(encodeHex(c >>> 12 & 0xf))
.write(encodeHex(c >>> 8 & 0xf))
.write(encodeHex(c >>> 4 & 0xf))
.write(encodeHex(c & 0xf));
} else {
output = output.write(c);
}
}
}
output = output.write('\"');
}
private static char encodeHex(int x) {
if (x < 10) {
return (char) ('0' + x);
} else {
return (char) ('A' + (x - 10));
}
}
private static String lineSeparator;
/**
* Returns the operting system specific string used to separate lines of text.
*/
public static String lineSeparator() {
if (lineSeparator == null) {
lineSeparator = System.getProperty("line.separator", "\n");
}
return lineSeparator;
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Input.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.codec;
/**
* Non-blocking token stream reader, with single token lookahead.
* {@code Input} enable incremental, interruptible parsing of network protocols
* and data formats.
*
* <h3>Input tokens</h3>
* <p>Input tokens are modeled as primitive {@code int}s, commonly representing
* Unicode code points, or raw octets; each {@code Input} implementation
* specifies the semantic type of its tokens. The {@link #head()} method
* peeks at the current lookahead token, without consuming it, and the {@link
* #step()} method advances the input to the next token.</p>
*
* <h3>Input states</h3>
* <p>{@code Input} is always in one of four states: <em>cont</em>inue,
* <em>empty</em>, <em>done</em>, or <em>error</em>. The <em>cont</em> state
* indicates that a lookahead token is immediately available; the <em>empty</em>
* state indicates that no additional tokens are available at this time, but
* that the stream may logically resume in the future; the <em>done</em> state
* indicates that the stream has terminated nominally; and the <em>error</em>
* state indicates that the stream has terminated abnormally.
* {@link #isCont()} returns {@code true} when in the <em>cont</em> state;
* {@link #isEmpty()} returns {@code true} when in the <em>empty</em> state;
* {@link #isDone()} returns {@code true} when in the <em>done</em> state; and
* {@link #isError()} returns {@code true} when in the <em>error</em> state.</p>
*
* <h3>Non-blocking semantics</h3>
* <p>{@code Input} never blocks. An {@code Input} that would otherwise block
* awaiting additional tokens instead enters the <em>empty</em> state,
* signaling the input consumer to back off processing the input, but to remain
* prepared to process additional input in the future. An {@code Input} enters
* the <em>done</em> state when it encounters the final end of its input stream,
* signaling the input consumer to terminate processing.</p>
*
* <p>{@link #isPart()} returns {@code true} if the {@code Input} will enter
* the <em>empty</em> state after it consumes the last immediately available
* token; it returns {@code false} if the {@code Input} will enter the
* <em>done</em> state after it consumes the last immediately available token.</p>
*
* <p>{@link Input#empty()} returns an {@code Input} in the <em>empty</em>
* state. {@link Input#done()} returns an {@code Input} in the <em>done</em>
* state.</p>
*
* <h3>Position tracking</h3>
* <p>The logical position of the current lookahead token is made available via
* the {@link #mark()} method, with optimized callouts for the byte {@link
* #offset() offset}, one-based {@link #line() line} number, and one-based
* {@link #column() column} in the current line. The {@link #id()} method
* returns a diagnostic identifier for the token stream.</p>
*
* <h3>Cloning</h3>
* <p>An {@code Input} may be {@link #clone() cloned} to provide an indepently
* mutable position into a shared token stream. Not all {@code Input}
* implementations support cloning.</p>
*
* @see InputSettings
* @see Parser
*/
public abstract class Input {
/**
* Returns {@code true} when a {@link #head() lookeahead} token is
* immediately available. i.e. this {@code Input} is in the <em>cont</em>
* state.
*/
public abstract boolean isCont();
/**
* Returns {@code true} when no lookahead token is currently available, but
* additional input may be available in the future. i.e. this {@code Input}
* is in the <em>empty</em> state.
*/
public abstract boolean isEmpty();
/**
* Returns {@code true} when no lookahead token is currently available, and
* no additional input will ever become available. i.e. this {@code Input}
* is in the <em>done</em> state.
*/
public abstract boolean isDone();
/**
* Returns {@code true} when no lookahead token is currently available due to
* an error with the token stream. i.e. this {@code Input} is in the
* <em>error</em> state. When {@code true}, {@link #trap()} will return the
* input error.
*/
public abstract boolean isError();
/**
* Returns {@code true} if this is a partial {@code Input} will that enter
* the <em>empty</em> state after it consumes the last available input token.
*/
public abstract boolean isPart();
/**
* Returns a partial {@code Input} equivalent to this {@code Input}, if
* {@code isPart} is {@code true}; returns a final {@code Input} equivalent
* to this {@code Input} if {@code isPart} is {@code false}. The caller's
* reference to {@code this} {@code Input} should be replaced by the returned
* {@code Input}.
*/
public abstract Input isPart(boolean isPart);
/**
* Returns the current lookahead token, if this {@code Input} is in the
* <em>cont</em> state.
*
* @throws InputException if this {@code Input} is not in the <em>cont</em>
* state.
*/
public abstract int head();
/**
* Returns an {@code Input} equivalent to this {@code Input}, but advanced to
* the next token. Returns an {@code Input} in the <em>error</em> state if
* this {@code Input} is not in the <em>cont</em> state. The caller's
* reference to {@code this} {@code Input} should be replaced by the returned
* {@code Input}.
*/
public abstract Input step();
/**
* Returns an {@code Input} equivalent to this {@code Input}, but
* repositioned to the given {@code mark}. Returns an {@code Input} in the
* <em>error</em> state if this {@code Input} does not support seeking, or if
* this {@code Input} is unable to reposition to the given {@code mark}. The
* caller's reference to {@code this} {@code Input} should be replaced by the
* returned {@code Input}.
*/
public abstract Input seek(Mark mark);
/**
* Returns an {@code Input} equivalent to this {@code Input}, but whose
* behavior may be altered by the given out-of-band {@code condition}. The
* caller's reference to {@code this} {@code Input} should be replaced by the
* returned {@code Input}.
*/
public Input fork(Object condition) {
return this;
}
/**
* Returns the input error. Only guaranteed to return an error when in the
* <em>error</em> state.
*
* @throws InputException if this {@code Input} is not in the <em>error</em>
* state.
*/
public Throwable trap() {
throw new InputException();
}
/**
* Returns an object that identifies the token stream, or {@code null} if the
* stream is unidentified.
*/
public abstract Object id();
/**
* Returns an {@code Input} equivalent to this {@code Input}, but logically
* identified by the given–possibly {@code null}–{@code id}. The caller's
* reference to {@code this} {@code Input} should be replaced by the returned
* {@code Input}.
*/
public abstract Input id(Object id);
/**
* Returns the position of the current lookahead token, relative to the start
* of the stream.
*/
public abstract Mark mark();
/**
* Returns an {@code Input} equivalent to this {@code Input}, but logically
* positioned at the given {@code mark}. The physical position in the input
* stream is not modified. The caller's reference to {@code this} {@code
* Input} should be replaced by the returned {@code Input}.
*/
public abstract Input mark(Mark mark);
/**
* Returns the byte offset of the current lookahead token, relative to the
* start of the stream.
*/
public long offset() {
return mark().offset;
}
/**
* Returns the one-based line number of the current lookahead token, relative
* to the start of the stream.
*/
public int line() {
return mark().line;
}
/**
* Returns the one-based column number of the current lookahead token,
* relative to the current line in the stream.
*/
public int column() {
return mark().column;
}
/**
* Returns the {@code InputSettings} used to configure the behavior of input
* consumers that read from this {@code Input}.
*/
public abstract InputSettings settings();
/**
* Returns an {@code Input} equivalent to this {@code Input}, but with the
* given input {@code settings}. The caller's reference to {@code this}
* {@code Input} should be replaced by the returned {@code Input}.
*/
public abstract Input settings(InputSettings settings);
/**
* Returns an independently positioned view into the token stream,
* initialized with identical state to this {@code Input}.
*
* @throws UnsupportedOperationException if this {@code Input} cannot be
* cloned.
*/
@Override
public abstract Input clone();
private static Input empty;
private static Input done;
/**
* Returns an {@code Input} in the <em>empty</em> state.
*/
public static Input empty() {
if (empty == null) {
empty = new InputEmpty(null, Mark.zero(), InputSettings.standard());
}
return empty;
}
/**
* Returns an {@code Input} in the <em>empty</em> state, with the given
* {@code settings}.
*/
public static Input empty(InputSettings settings) {
if (settings == InputSettings.standard()) {
return empty();
}
return new InputEmpty(null, Mark.zero(), settings);
}
/**
* Returns an {@code Input} in the <em>empty</em> state, at the {@code mark}
* position of a token stream logically identified by {@code id}.
*/
public static Input empty(Object id, Mark mark) {
if (id == null && (mark == null || mark == Mark.zero())) {
return empty();
}
return new InputEmpty(id, mark, InputSettings.standard());
}
/**
* Returns an {@code Input} in the <em>empty</em> state, at the {@code mark}
* position of a token stream logically identified by {@code id}, with the
* given {@code settings}.
*/
public static Input empty(Object id, Mark mark, InputSettings settings) {
if (id == null && (mark == null || mark == Mark.zero()) && settings == InputSettings.standard()) {
return empty();
}
return new InputEmpty(id, mark, settings);
}
/**
* Returns an {@code Input} in the <em>done</em> state.
*/
public static Input done() {
if (done == null) {
done = new InputDone(null, Mark.zero(), InputSettings.standard());
}
return done;
}
/**
* Returns an {@code Input} in the <em>done</em> state, with the given {@code
* settings}.
*/
public static Input done(InputSettings settings) {
if (settings == InputSettings.standard()) {
return done();
}
return new InputDone(null, Mark.zero(), settings);
}
/**
* Returns an {@code Input} in the <em>done</em> state, at the {@code mark}
* position of a token stream logically identified by {@code id}.
*/
public static Input done(Object id, Mark mark) {
if (id == null && (mark == null || mark == Mark.zero())) {
return done();
}
return new InputDone(id, mark, InputSettings.standard());
}
/**
* Returns an {@code Input} in the <em>done</em> state, at the {@code mark}
* position of a token stream logically identified by {@code id}, with the
* given {@code settings}.
*/
public static Input done(Object id, Mark mark, InputSettings settings) {
if (id == null && (mark == null || mark == Mark.zero()) && settings == InputSettings.standard()) {
return done();
}
return new InputDone(id, mark, settings);
}
/**
* Returns an {@code Input} in the <em>error</em> state, with the given input
* {@code error}.
*/
public static Input error(Throwable error) {
return new InputError(error, null, Mark.zero(), InputSettings.standard());
}
/**
* Returns an {@code Input} in the <em>error</em> state, with the given input
* {@code error} and {@code settings}.
*/
public static Input error(Throwable error, InputSettings settings) {
return new InputError(error, null, Mark.zero(), settings);
}
/**
* Returns an {@code Input} in the <em>error</em> state, with the given input
* {@code error}, at the {@code mark} position of a token stream logically
* identified by {@code id}.
*/
public static Input error(Throwable error, Object id, Mark mark) {
return new InputError(error, id, mark, InputSettings.standard());
}
/**
* Returns an {@code Input} in the <em>error</em> state, with the given input
* {@code error}, at the {@code mark} position of a token stream logically
* identified by {@code id}, with the given {@code settings}.
*/
public static Input error(Throwable error, Object id, Mark mark, InputSettings settings) {
return new InputError(error, id, mark, settings);
}
}
final class InputEmpty extends Input {
final Object id;
final Mark mark;
final InputSettings settings;
InputEmpty(Object id, Mark mark, InputSettings settings) {
this.id = id;
this.mark = mark;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return true;
}
@Override
public Input isPart(boolean isPart) {
if (isPart) {
return this;
} else {
return Input.done(this.id, this.mark, this.settings);
}
}
@Override
public int head() {
throw new IllegalStateException();
}
@Override
public Input step() {
final Throwable error = new InputException("empty step");
return Input.error(error, this.id, this.mark, this.settings);
}
@Override
public Input fork(Object condition) {
if (condition instanceof Input) {
return (Input) condition;
}
return this;
}
@Override
public Input seek(Mark mark) {
final Throwable error = new InputException("empty seek");
return Input.error(error, this.id, this.mark, this.settings);
}
@Override
public Object id() {
return this.id;
}
@Override
public Input id(Object id) {
return Input.empty(id, this.mark, this.settings);
}
@Override
public Mark mark() {
return this.mark;
}
@Override
public Input mark(Mark mark) {
return Input.empty(this.id, mark, this.settings);
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public Input settings(InputSettings settings) {
return Input.empty(this.id, this.mark, settings);
}
@Override
public Input clone() {
return this;
}
}
final class InputDone extends Input {
final Object id;
final Mark mark;
final InputSettings settings;
InputDone(Object id, Mark mark, InputSettings settings) {
this.id = id;
this.mark = mark;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return false;
}
@Override
public Input isPart(boolean isPart) {
if (isPart) {
return Input.empty(this.id, this.mark, this.settings);
} else {
return this;
}
}
@Override
public int head() {
throw new IllegalStateException();
}
@Override
public Input step() {
final Throwable error = new InputException("done step");
return Input.error(error, this.id, this.mark, this.settings);
}
@Override
public Input seek(Mark mark) {
final Throwable error = new InputException("empty seek");
return Input.error(error, this.id, this.mark, this.settings);
}
@Override
public Object id() {
return this.id;
}
@Override
public Input id(Object id) {
return Input.done(id, this.mark, this.settings);
}
@Override
public Mark mark() {
return this.mark;
}
@Override
public Input mark(Mark mark) {
return Input.done(this.id, mark, this.settings);
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public Input settings(InputSettings settings) {
return Input.done(this.id, this.mark, settings);
}
@Override
public Input clone() {
return this;
}
}
final class InputError extends Input {
final Throwable error;
final Object id;
final Mark mark;
final InputSettings settings;
InputError(Throwable error, Object id, Mark mark, InputSettings settings) {
this.error = error;
this.id = id;
this.mark = mark;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return true;
}
@Override
public boolean isPart() {
return false;
}
@Override
public Input isPart(boolean isPart) {
return this;
}
@Override
public int head() {
throw new IllegalStateException();
}
@Override
public Input step() {
final Throwable error = new InputException("error step");
return Input.error(error, this.id, this.mark, this.settings);
}
@Override
public Throwable trap() {
return this.error;
}
@Override
public Input seek(Mark mark) {
final Throwable error = new InputException("error seek");
return Input.error(error, this.id, this.mark, this.settings);
}
@Override
public Object id() {
return this.id;
}
@Override
public Input id(Object id) {
return Input.error(this.error, id, this.mark, this.settings);
}
@Override
public Mark mark() {
return this.mark;
}
@Override
public Input mark(Mark mark) {
return Input.error(this.error, this.id, mark, this.settings);
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public Input settings(InputSettings settings) {
return Input.error(this.error, this.id, this.mark, settings);
}
@Override
public Input clone() {
return this;
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/InputBuffer.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.codec;
/**
* Non-blocking token stream buffer.
*/
public abstract class InputBuffer extends Input {
@Override
public abstract InputBuffer isPart(boolean isPart);
public abstract int index();
public abstract InputBuffer index(int index);
public abstract int limit();
public abstract InputBuffer limit(int limit);
public abstract int capacity();
public abstract int remaining();
public abstract byte[] array();
public abstract int arrayOffset();
public abstract boolean has(int index);
public abstract int get(int index);
public abstract void set(int index, int token);
@Override
public abstract InputBuffer step();
public abstract InputBuffer step(int offset);
@Override
public abstract InputBuffer seek(Mark mark);
@Override
public InputBuffer fork(Object condition) {
return this;
}
@Override
public abstract InputBuffer id(Object id);
@Override
public abstract InputBuffer mark(Mark mark);
@Override
public abstract InputBuffer settings(InputSettings settings);
@Override
public abstract InputBuffer clone();
private static InputBuffer empty;
private static InputBuffer done;
/**
* Returns an {@code InputBuffer} in the <em>empty</em> state.
*/
public static InputBuffer empty() {
if (empty == null) {
empty = new InputBufferEmpty(null, Mark.zero(), InputSettings.standard());
}
return empty;
}
/**
* Returns an {@code InputBuffer} in the <em>empty</em> state, with the given
* {@code settings}.
*/
public static InputBuffer empty(InputSettings settings) {
if (settings == InputSettings.standard()) {
return empty();
}
return new InputBufferEmpty(null, Mark.zero(), settings);
}
/**
* Returns an {@code InputBuffer} in the <em>empty</em> state, at the {@code
* mark} position of a token stream logically identified by {@code id}.
*/
public static InputBuffer empty(Object id, Mark mark) {
if (id == null && (mark == null || mark == Mark.zero())) {
return empty();
}
return new InputBufferEmpty(id, mark, InputSettings.standard());
}
/**
* Returns an {@code InputBuffer} in the <em>empty</em> state, at the {@code
* mark} position of a token stream logically identified by {@code id},
* with the given {@code settings}.
*/
public static InputBuffer empty(Object id, Mark mark, InputSettings settings) {
if (id == null && (mark == null || mark == Mark.zero()) && settings == InputSettings.standard()) {
return empty();
}
return new InputBufferEmpty(id, mark, settings);
}
/**
* Returns an {@code InputBuffer} in the <em>done</em> state.
*/
public static InputBuffer done() {
if (done == null) {
done = new InputBufferDone(null, Mark.zero(), InputSettings.standard());
}
return done;
}
/**
* Returns an {@code InputBuffer} in the <em>done</em> state, with the given
* {@code settings}.
*/
public static InputBuffer done(InputSettings settings) {
if (settings == InputSettings.standard()) {
return done();
}
return new InputBufferDone(null, Mark.zero(), settings);
}
/**
* Returns an {@code InputBuffer} in the <em>done</em> state, at the {@code
* mark} position of a token stream logically identified by {@code id}.
*/
public static InputBuffer done(Object id, Mark mark) {
if (id == null && (mark == null || mark == Mark.zero())) {
return done();
}
return new InputBufferDone(id, mark, InputSettings.standard());
}
/**
* Returns an {@code InputBuffer} in the <em>done</em> state, at the {@code
* mark} position of a token stream logically identified by {@code id},
* with the given {@code settings}.
*/
public static InputBuffer done(Object id, Mark mark, InputSettings settings) {
if (id == null && (mark == null || mark == Mark.zero()) && settings == InputSettings.standard()) {
return done();
}
return new InputBufferDone(id, mark, settings);
}
/**
* Returns an {@code InputBuffer} in the <em>error</em> state, with the given
* input {@code error}.
*/
public static InputBuffer error(Throwable error) {
return new InputBufferError(error, null, Mark.zero(), InputSettings.standard());
}
/**
* Returns an {@code InputBuffer} in the <em>error</em> state, with the given
* input {@code error} and {@code settings}.
*/
public static InputBuffer error(Throwable error, InputSettings settings) {
return new InputBufferError(error, null, Mark.zero(), settings);
}
/**
* Returns an {@code InputBuffer} in the <em>error</em> state, with the given
* input {@code error}, at the {@code mark} position of a token stream
* logically identified by {@code id}.
*/
public static InputBuffer error(Throwable error, Object id, Mark mark) {
return new InputBufferError(error, id, mark, InputSettings.standard());
}
/**
* Returns an {@code InputBuffer} in the <em>error</em> state, with the given
* input {@code error}, at the {@code mark} position of a token stream
* logically identified by {@code id}, with the given {@code settings}.
*/
public static InputBuffer error(Throwable error, Object id, Mark mark, InputSettings settings) {
return new InputBufferError(error, id, mark, settings);
}
}
final class InputBufferEmpty extends InputBuffer {
final Object id;
final Mark mark;
final InputSettings settings;
InputBufferEmpty(Object id, Mark mark, InputSettings settings) {
this.id = id;
this.mark = mark;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return true;
}
@Override
public InputBuffer isPart(boolean isPart) {
if (isPart) {
return this;
} else {
return InputBuffer.done(this.id, this.mark, this.settings);
}
}
@Override
public int index() {
return 0;
}
@Override
public InputBuffer index(int index) {
if (index == 0) {
return this;
} else {
final Throwable error = new InputException("invalid index");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
}
@Override
public int limit() {
return 0;
}
@Override
public InputBuffer limit(int limit) {
if (limit == 0) {
return this;
} else {
final Throwable error = new InputException("invalid limit");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
}
@Override
public int capacity() {
return 0;
}
@Override
public int remaining() {
return 0;
}
@Override
public byte[] array() {
throw new UnsupportedOperationException();
}
@Override
public int arrayOffset() {
throw new UnsupportedOperationException();
}
@Override
public boolean has(int index) {
return false;
}
@Override
public int get(int index) {
throw new InputException();
}
@Override
public void set(int index, int token) {
throw new InputException();
}
@Override
public int head() {
throw new InputException();
}
@Override
public InputBuffer step() {
final Throwable error = new InputException("empty step");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public InputBuffer step(int offset) {
final Throwable error = new InputException("empty step");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public InputBuffer fork(Object condition) {
if (condition instanceof InputBuffer) {
return (InputBuffer) condition;
}
return this;
}
@Override
public InputBuffer seek(Mark mark) {
final Throwable error = new InputException("empty seek");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public Object id() {
return this.id;
}
@Override
public InputBuffer id(Object id) {
return InputBuffer.empty(id, this.mark, this.settings);
}
@Override
public Mark mark() {
return this.mark;
}
@Override
public InputBuffer mark(Mark mark) {
return InputBuffer.empty(this.id, mark, this.settings);
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public InputBuffer settings(InputSettings settings) {
return InputBuffer.empty(this.id, this.mark, settings);
}
@Override
public InputBuffer clone() {
return this;
}
}
final class InputBufferDone extends InputBuffer {
final Object id;
final Mark mark;
final InputSettings settings;
InputBufferDone(Object id, Mark mark, InputSettings settings) {
this.id = id;
this.mark = mark;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return false;
}
@Override
public InputBuffer isPart(boolean isPart) {
if (isPart) {
return InputBuffer.empty(this.id, this.mark, this.settings);
} else {
return this;
}
}
@Override
public int index() {
return 0;
}
@Override
public InputBuffer index(int index) {
if (index == 0) {
return this;
} else {
final Throwable error = new InputException("invalid index");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
}
@Override
public int limit() {
return 0;
}
@Override
public InputBuffer limit(int limit) {
if (limit == 0) {
return this;
} else {
final Throwable error = new InputException("invalid limit");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
}
@Override
public int capacity() {
return 0;
}
@Override
public int remaining() {
return 0;
}
@Override
public byte[] array() {
throw new UnsupportedOperationException();
}
@Override
public int arrayOffset() {
throw new UnsupportedOperationException();
}
@Override
public boolean has(int index) {
return false;
}
@Override
public int get(int index) {
throw new InputException();
}
@Override
public void set(int index, int token) {
throw new InputException();
}
@Override
public int head() {
throw new InputException();
}
@Override
public InputBuffer step() {
final Throwable error = new InputException("done step");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public InputBuffer step(int offset) {
final Throwable error = new InputException("done step");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public InputBuffer seek(Mark mark) {
final Throwable error = new InputException("empty seek");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public Object id() {
return this.id;
}
@Override
public InputBuffer id(Object id) {
return InputBuffer.done(id, this.mark, this.settings);
}
@Override
public Mark mark() {
return this.mark;
}
@Override
public InputBuffer mark(Mark mark) {
return InputBuffer.done(this.id, mark, this.settings);
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public InputBuffer settings(InputSettings settings) {
return InputBuffer.done(this.id, this.mark, settings);
}
@Override
public InputBuffer clone() {
return this;
}
}
final class InputBufferError extends InputBuffer {
final Throwable error;
final Object id;
final Mark mark;
final InputSettings settings;
InputBufferError(Throwable error, Object id, Mark mark, InputSettings settings) {
this.error = error;
this.id = id;
this.mark = mark;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return true;
}
@Override
public boolean isPart() {
return false;
}
@Override
public InputBuffer isPart(boolean isPart) {
return this;
}
@Override
public int index() {
return 0;
}
@Override
public InputBuffer index(int index) {
if (index == 0) {
return this;
} else {
final Throwable error = new InputException("invalid index");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
}
@Override
public int limit() {
return 0;
}
@Override
public InputBuffer limit(int limit) {
if (limit == 0) {
return this;
} else {
final Throwable error = new InputException("invalid limit");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
}
@Override
public int capacity() {
return 0;
}
@Override
public int remaining() {
return 0;
}
@Override
public byte[] array() {
throw new UnsupportedOperationException();
}
@Override
public int arrayOffset() {
throw new UnsupportedOperationException();
}
@Override
public boolean has(int index) {
return false;
}
@Override
public int get(int index) {
throw new InputException();
}
@Override
public void set(int index, int token) {
throw new InputException();
}
@Override
public int head() {
throw new InputException();
}
@Override
public InputBuffer step() {
final Throwable error = new InputException("error step");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public InputBuffer step(int offset) {
final Throwable error = new InputException("error step");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public Throwable trap() {
return this.error;
}
@Override
public InputBuffer seek(Mark mark) {
final Throwable error = new InputException("empty seek");
return InputBuffer.error(error, this.id, this.mark, this.settings);
}
@Override
public Object id() {
return this.id;
}
@Override
public InputBuffer id(Object id) {
return InputBuffer.error(this.error, id, this.mark, this.settings);
}
@Override
public Mark mark() {
return this.mark;
}
@Override
public InputBuffer mark(Mark mark) {
return InputBuffer.error(this.error, this.id, mark, this.settings);
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public InputBuffer settings(InputSettings settings) {
return InputBuffer.error(this.error, this.id, this.mark, settings);
}
@Override
public InputBuffer clone() {
return this;
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/InputException.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.codec;
/**
* Thrown when reading invalid {@link Input}.
*/
public class InputException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InputException(String message, Throwable cause) {
super(message, cause);
}
public InputException(String message) {
super(message);
}
public InputException(Throwable cause) {
super(cause);
}
public InputException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/InputParser.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.codec;
final class InputParser<O> extends Parser<O> {
final Input input;
final Parser<O> parser;
InputParser(Input input, Parser<O> parser) {
this.input = input;
this.parser = parser;
}
@Override
public Parser<O> feed(Input input) {
if (this.input != null) {
input = this.input.fork(input);
}
return parse(input, this.parser);
}
@Override
public Parser<O> fork(Object condition) {
return new InputParser<O>(this.input, this.parser.fork(condition));
}
@Override
public O bind() {
return this.parser.bind();
}
@Override
public Throwable trap() {
return this.parser.trap();
}
static <O> Parser<O> parse(Input input, Parser<O> parser) {
parser = parser.feed(input);
if (!parser.isCont()) {
return parser;
} else if (input.isError()) {
return error(input.trap());
}
return new InputParser<O>(input, parser);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/InputSettings.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.codec;
import swim.util.Murmur3;
/**
* {@code Input} consumption parameters. {@code InputSettings} provide
* contextual configuration parameters to input consumers, such as {@link
* Parser Parsers}.
*/
public class InputSettings implements Debug {
protected final boolean isStripped;
protected InputSettings(boolean isStripped) {
this.isStripped = isStripped;
}
protected boolean canEqual(Object other) {
return other instanceof InputSettings;
}
/**
* Returns {@code true} if input consumers should not include diagnostic
* metadata in generated output.
*/
public final boolean isStripped() {
return this.isStripped;
}
/**
* Returns a copy of these settings with the given {@code isStripped} flag.
*/
public InputSettings isStripped(boolean isStripped) {
return copy(isStripped);
}
protected InputSettings copy(boolean isStripped) {
return create(isStripped);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof InputSettings) {
final InputSettings that = (InputSettings) other;
return that.canEqual(this) && this.isStripped == that.isStripped;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(InputSettings.class);
}
return Murmur3.mash(Murmur3.mix(hashSeed, Murmur3.hash(this.isStripped)));
}
@Override
public void debug(Output<?> output) {
output = output.write("InputSettings").write('.');
if (!this.isStripped) {
output = output.write("standard");
} else {
output = output.write("stripped");
}
output = output.write('(').write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static InputSettings standard;
private static InputSettings stripped;
/**
* Returns {@code InputSettings} configured to include diagnostic metadata
* in generated output.
*/
public static final InputSettings standard() {
if (standard == null) {
standard = new InputSettings(false);
}
return standard;
}
/**
* Returns {@code InputSettings} configured to not include diagnostic
* metadata in generated output.
*/
public static final InputSettings stripped() {
if (stripped == null) {
stripped = new InputSettings(true);
}
return stripped;
}
/**
* Returns {@code InputSettings} configured to not include diagnostic
* metadata in generated output, if {@code isStripped} is {@code true}.
*/
public static final InputSettings create(boolean isStripped) {
if (isStripped) {
return stripped();
}
return standard();
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/LineParser.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.codec;
final class LineParser extends Parser<String> {
final StringBuilder output;
LineParser(StringBuilder output) {
this.output = output;
}
LineParser() {
this(null);
}
@Override
public Parser<String> feed(Input input) {
return parse(input, this.output);
}
static Parser<String> parse(Input input, StringBuilder output) {
if (output == null) {
output = new StringBuilder();
}
while (input.isCont()) {
final int c = input.head();
input = input.step();
if (c == '\r') {
continue;
} else if (c != '\n') {
output.appendCodePoint(c);
} else {
return done(output.toString());
}
}
if (input.isDone()) {
return done(output.toString());
} else if (input.isError()) {
return error(input.trap());
}
return new LineParser(output);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Mark.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.codec;
import java.util.Objects;
import swim.util.Murmur3;
/**
* Description of a source position, identified by byte offset, line, and
* column number, with an optional note.
*/
public final class Mark extends Tag implements Comparable<Mark> {
final long offset;
final int line;
final int column;
final String note;
Mark(long offset, int line, int column, String note) {
this.offset = offset;
this.line = line;
this.column = column;
this.note = note;
}
/**
* Returns the zero-based byte offset of this position.
*/
public long offset() {
return this.offset;
}
/**
* Returns the one-based line number of this position.
*/
public int line() {
return this.line;
}
/**
* Returns the one-based column number of this position.
*/
public int column() {
return this.column;
}
/**
* Returns the note attached to the marked position, or {@code null} if this
* position has no attached note.
*/
public String note() {
return this.note;
}
/**
* Returns {@code this} position, if its byte offset is less than or equal
* to {@code that} position; otherwise returns {@code that} position.
*/
public Mark min(Mark that) {
if (this.offset <= that.offset) {
return this;
} else {
return that;
}
}
/**
* Returns {@code this} position, if its byte offset is greater than or equal
* to {@code that} position; otherwise returns {@code that} position.
*/
public Mark max(Mark that) {
if (this.offset >= that.offset) {
return this;
} else {
return that;
}
}
@Override
public Mark start() {
return this;
}
@Override
public Mark end() {
return this;
}
@Override
public Tag union(Tag other) {
if (other instanceof Mark) {
final Mark that = (Mark) other;
if (this.offset == that.offset && this.line == that.line
&& this.column == that.column) {
return this;
} else {
return Span.from(this, that);
}
} else if (other instanceof Span) {
final Span that = (Span) other;
final Mark start = min(that.start);
final Mark end = max(that.end);
if (start == that.start && end == that.end) {
return that;
} else {
return Span.from(start, end);
}
}
throw new UnsupportedOperationException(other.toString());
}
@Override
public Mark shift(Mark mark) {
final long offset = this.offset + (this.offset - mark.offset);
final int line = this.line + (this.line - mark.line);
int column = this.column;
if (line == 1) {
column += (this.column - mark.column);
}
if (offset == this.offset && line == this.line && column == this.column) {
return this;
} else {
return Mark.at(offset, line, column, this.note);
}
}
@Override
public int compareTo(Mark that) {
return Long.compare(this.offset, that.offset);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Mark) {
final Mark that = (Mark) other;
return this.offset == that.offset && this.line == that.line
&& this.column == that.column && Objects.equals(this.note, that.note);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(Mark.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.offset)), this.line), this.column), Murmur3.hash(this.note)));
}
@Override
public void display(Output<?> output) {
Format.displayInt(this.line, output);
output = output.write(':');
Format.displayInt(this.column, output);
if (this.note != null) {
output = output.write(": ").write(this.note);
}
}
@Override
public void debug(Output<?> output) {
output = output.write("Mark").write('.').write("at").write('(');
Format.debugLong(this.offset, output);
output = output.write(", ");
Format.debugInt(this.line, output);
output = output.write(", ");
Format.debugInt(this.column, output);
if (this.note != null) {
output = output.write(", ");
Format.debugString(this.note, output);
}
output = output.write(')');
}
@Override
public String toString() {
return Format.display(this);
}
private static int hashSeed;
private static Mark zero;
/**
* Returns a {@code Mark} at byte offset {@code 0}, line {@code 1}, and
* column {@code 1}, with no attached note.
*/
public static Mark zero() {
if (zero == null) {
zero = new Mark(0L, 1, 1, null);
}
return zero;
}
/**
* Returns a new {@code Mark} at the given zero-based byte {@code offset},
* one-based {@code line} number, and one-based {@code column} number,
* with the attached {@code note}.
*/
public static Mark at(long offset, int line, int column, String note) {
return new Mark(offset, line, column, note);
}
/**
* Returns a new {@code Mark} at the given zero-based byte {@code offset},
* one-based {@code line} number, and one-based {@code column} number,
* with no attached note.
*/
public static Mark at(long offset, int line, int column) {
return at(offset, line, column, null);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Output.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.codec;
/**
* Non-blocking token stream writer. {@code Output} enables incremental,
* interruptible writing of network protocols and data formats.
*
* <h3>Output tokens</h3>
* <p>Output tokens are modeled as primitive {@code int}s, commonly
* representing Unicode code points, or raw octets; each {@code Output}
* implementation specifies the semantic type of its tokens.</p>
*
* <h3>Output states</h3>
* <p>{@code Output} is always in one of four states: <em>cont</em>inue,
* <em>full</em>, <em>done</em>, or <em>error</em>. The <em>cont</em> state
* indicates that the stream is ready to write a single token; the <em>full</em>
* state indicates that the stream is unable to write additional tokens at this
* time, but that the stream may logically resume at some point in the future;
* and the <em>done</em> state indicates that the stream has terminated, and
* that {@link #bind() bind} will return the output result; and the
* <em>error</em> state indicates that the stream has terminated abnormally.
* {@link #isCont()} returns {@code true} when in the <em>cont</em> state;
* {@link #isFull()} returns {@code true} when in the <em>full</em> state;
* {@link #isDone()} returns {@code true} when in the <em>done</em> state; and
* {@link #isError()} returns {@code true} when in the <em>error</em> state.</p>
*
* <h3>Output results</h3>
* <p>An {@code Output} yields a value of type {@code T}, obtained via the
* {@link #bind()} method, representing some implementation defined result of
* writing the output. For example, an {@code Output<String>} implementation
* may–but is not required to–yield a {@code String} containing all code points
* written to the output.</p>
*
* <h3>Non-blocking behavior</h3>
* <p>{@code Output} writers never block. An {@code Output} that would
* otherwise block writing additional output instead enters the <em>full</em>
* state, signaling the output generator to back off producing the output, but
* to remain prepared to produce additional output in the future. An {@code
* Output} enters the <em>done</em> state when it encounters the final enf of
* its output, signaling to the output generator to stop producing.</p>
*
* <h3>Output settings</h3>
* <p>An output generator may alter the tokens it produces based on its {@code
* Output}'s {@link #settings() settings}. Uses include pretty printing and
* styling generated output. {@link OutputSettings} subclasses can provide
* additional parameters understood by specialized output producers.</p>
*
* <h3>Cloning</h3>
* <p>An {@code Output} may be {@link #clone() cloned} to branch the token
* stream in an implementation specified manner. Not all {@code Output}
* implementations support cloning.</p>
*
* @see OutputSettings
* @see Writer
*/
public abstract class Output<T> {
/**
* Returns {@code true} when the next {@link #write(int)} will succeed.
* i.e. this {@code Output} is in the <em>cont</em> state.
*/
public abstract boolean isCont();
/**
* Returns {@code true} when an immediate {@code write} will fail,
* but writes may succeed at some point in the future. i.e. this
* {@code Output} is in the <em>full</em> state.
*/
public abstract boolean isFull();
/**
* Returns {@code true} when no {@code write} will ever again suucced.
* i.e. this {@code Output} is in the <em>done</em> state.
*/
public abstract boolean isDone();
/**
* Returns {@code true} when an immediate {@code write} will fail due to an
* error with the token stream. i.e. this {@code Output} is in the
* <em>error</em> state. When {@code true}, {@link #trap()} will return the
* output error.
*/
public abstract boolean isError();
/**
* Returns {@code true} if this is a partial {@code Output} that will enter
* the <em>full</em> state when it is unable to write additional tokens.
*/
public abstract boolean isPart();
/**
* Returns a partial {@code Output} equivalent to this {@code Output}, if
* {@code isPart} is {@code true}; returns a final {@code Output} equivalent
* to this {@code Output} if {@code isPart} is {@code false}. The caller's
* reference to {@code this} {@code Output} should be replaced by the
* returned {@code Output}.
*/
public abstract Output<T> isPart(boolean isPart);
/**
* Writes a single {@code token} to the stream, if this {@code Output} is in
* the <em>cont</em> state. Returns an {@code Output} in the <em>error</em>
* state if this {@code Output} is not in the <em>cont</em> state. The
* caller's reference to {@code this} {@code Output} should be replaced by
* the returned {@code Output}.
*/
public abstract Output<T> write(int token);
/**
* Writes the code points of the given {@code string}. Assumes this is a
* Unicode {@code Output} with sufficient capacity. Returns an {@code
* Output} in the <em>error</em> state if this {@code Output} exits the
* <em>cont</em> state before the full {@code string} has been writtem. The
* caller's reference to {@code this} {@code Output} should be replaced by
* the returned {@code Output}.
*/
public Output<T> write(String string) {
Output<T> output = this;
final int n = string.length();
for (int i = 0; i < n; i = string.offsetByCodePoints(i, 1)) {
output = output.write(string.codePointAt(i));
}
return output;
}
/**
* Writes the code points of the given {@code string}, followed by the code
* points of the {@code settings}' {@link OutputSettings#lineSeparator()
* line separator}. Assumes this is a Unicode {@code Output} with sufficient
* capacity. Returns an {@code Output} in the <em>error</em> state if this
* {@code Output} exits the <em>cont</em> state before the full {@code
* string} and line separator has been written. The caller's reference to
* {@code this} {@code Output} should be replaced by the returned {@code
* Output}.
*/
public Output<T> writeln(String string) {
return write(string).writeln();
}
/**
* Writes the code points of the {@code settings}'
* {@link OutputSettings#lineSeparator() line separator}. Assumes this is a
* Unicode {@code Output} with sufficient capacity. Returns an {@code
* Output} in the <em>error</em> state if this {@code Output} exits the
* <em>cont</em> state before the full line separator has been written. The
* caller's reference to {@code this} {@code Output} should be replaced by
* the returned {@code Output}.
*/
public Output<T> writeln() {
return write(settings().lineSeparator());
}
/**
* Writes the code points of the human-readable {@link Display} string
* of the given {@code object}. Assumes this is a Unicode {@code Output}
* with sufficient capacity. Returns an {@code Output} in the <em>error</em>
* state if this {@code Output} exits the <em>contt</em> state before the
* full display string has been written. The caller's reference to {@code
* this} {@code Output} should be replaced by the returned {@code Output}.
*/
public Output<T> display(Object object) {
Format.display(object, this);
return this;
}
/**
* Writes the code points of the developer-readable {@link Debug} string
* of the given {@code object}. Assumes this is a Unicode {@code Output}
* with sufficient capacity. Returns an {@code Output} in the <em>error</em>
* state if this {@code Output} exits the <em>contt</em> state before the
* full debug string has been written. The caller's reference to {@code
* this} {@code Output} should be replaced by the returned {@code Output}.
*/
public Output<T> debug(Object object) {
Format.debug(object, this);
return this;
}
/**
* Writes any internally buffered state to the underlying output stream.
*/
public Output<T> flush() {
return this;
}
/**
* Returns an {@code Output} equivalent to this {@code Output}, but whose
* behavior may be altered by the given out-of-band {@code condition}. The
* caller's reference to {@code this} {@code Output} should be replaced by
* the returned {@code Output}.
*/
public Output<T> fork(Object condition) {
return this;
}
/**
* Returns the implementation-defined result of writing the output.
*/
public abstract T bind();
/**
* Returns the output error. Only guaranteed to return an error when in the
* <em>error</em> state.
*
* @throws OutputException if this {@code Output} is not in the
* <em>error</em> state.
*/
public Throwable trap() {
throw new OutputException();
}
/**
* Returns the {@code OutputSettings} used to configure the behavior of
* output producers that write to this {@code Output}.
*/
public abstract OutputSettings settings();
/**
* Updates the {@code settings} associated with this {@code Output}.
*
* @return {@code this}
*/
public abstract Output<T> settings(OutputSettings settings);
/**
* Returns an implementation-defined branch of the token stream.
*
* @throws UnsupportedOperationException if this {@code Output} cannot be
* cloned.
*/
@Override
public Output<T> clone() {
throw new UnsupportedOperationException();
}
private static Output<Object> full;
private static Output<Object> done;
/**
* Returns an {@code Output} in the <em>full</em> state, that binds a {@code
* null} result.
*/
@SuppressWarnings("unchecked")
public static <T> Output<T> full() {
if (full == null) {
full = new OutputFull<Object>(null, OutputSettings.standard());
}
return (Output<T>) full;
}
/**
* Returns an {@code Output} in the <em>full</em> state, with the given
* {@code settings}.
*/
public static <T> Output<T> full(OutputSettings settings) {
if (settings == OutputSettings.standard()) {
return full();
}
return new OutputFull<T>(null, settings);
}
/**
* Returns an {@code Output} in the <em>full</em> state, that binds the given
* {@code value}.
*/
public static <T> Output<T> full(T value) {
if (value == null) {
return full();
}
return new OutputFull<T>(value, OutputSettings.standard());
}
/**
* Returns an {@code Output} in the <em>full</em> state, that binds the given
* {@code value}, with the given {@code settings}.
*/
public static <T> Output<T> full(T value, OutputSettings settings) {
if (value == null && settings == OutputSettings.standard()) {
return full();
}
return new OutputFull<T>(value, settings);
}
/**
* Returns an {@code Output} in the <em>done</em> state, that binds a {@code
* null} result.
*/
@SuppressWarnings("unchecked")
public static <T> Output<T> done() {
if (done == null) {
done = new OutputDone<Object>(null, OutputSettings.standard());
}
return (Output<T>) done;
}
/**
* Returns an {@code Output} in the <em>done</em> state, with the given {@code
* settings}.
*/
public static <T> Output<T> done(OutputSettings settings) {
if (settings == OutputSettings.standard()) {
return done();
}
return new OutputDone<T>(null, settings);
}
/**
* Returns an {@code Output} in the <em>done</em> state, that binds the given
* {@code value}.
*/
public static <T> Output<T> done(T value) {
if (value == null) {
return done();
}
return new OutputDone<T>(value, OutputSettings.standard());
}
/**
* Returns an {@code Output} in the <em>done</em> state, that binds the given
* {@code value}, with the given {@code settings}.
*/
public static <T> Output<T> done(T value, OutputSettings settings) {
if (value == null && settings == OutputSettings.standard()) {
return done();
}
return new OutputDone<T>(value, settings);
}
/**
* Returns an {@code Output} in the <em>error</em> state, with the given
* output {@code error}.
*/
public static <T> Output<T> error(Throwable error) {
return new OutputError<T>(error, OutputSettings.standard());
}
/**
* Returns an {@code Output} in the <em>error</em> state, with the given
* output {@code error} and {@code settings}.
*/
public static <T> Output<T> error(Throwable error, OutputSettings settings) {
return new OutputError<T>(error, settings);
}
}
final class OutputFull<T> extends Output<T> {
final T value;
final OutputSettings settings;
OutputFull(T value, OutputSettings settings) {
this.value = value;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isFull() {
return true;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return true;
}
@Override
public Output<T> isPart(boolean isPart) {
if (isPart) {
return Output.done(this.value, this.settings);
} else {
return this;
}
}
@Override
public Output<T> write(int token) {
return Output.error(new OutputException("full"), this.settings);
}
@Override
public Output<T> write(String string) {
return Output.error(new OutputException("full"), this.settings);
}
@Override
public Output<T> writeln(String string) {
return Output.error(new OutputException("full"), this.settings);
}
@Override
public Output<T> writeln() {
return Output.error(new OutputException("full"), this.settings);
}
@Override
public T bind() {
return this.value;
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public Output<T> settings(OutputSettings settings) {
return Output.full(this.value, settings);
}
@Override
public Output<T> clone() {
return this;
}
}
final class OutputDone<T> extends Output<T> {
final T value;
final OutputSettings settings;
OutputDone(T value, OutputSettings settings) {
this.value = value;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isFull() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return false;
}
@Override
public Output<T> isPart(boolean isPart) {
if (isPart) {
return this;
} else {
return Output.full(this.value, this.settings);
}
}
@Override
public Output<T> write(int token) {
return Output.error(new OutputException("done"), this.settings);
}
@Override
public Output<T> write(String string) {
return Output.error(new OutputException("done"), this.settings);
}
@Override
public Output<T> writeln(String string) {
return Output.error(new OutputException("done"), this.settings);
}
@Override
public Output<T> writeln() {
return Output.error(new OutputException("done"), this.settings);
}
@Override
public T bind() {
return this.value;
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public Output<T> settings(OutputSettings settings) {
return Output.done(this.value, settings);
}
@Override
public Output<T> clone() {
return this;
}
}
final class OutputError<T> extends Output<T> {
final Throwable error;
final OutputSettings settings;
OutputError(Throwable error, OutputSettings settings) {
this.error = error;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isFull() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return true;
}
@Override
public boolean isPart() {
return false;
}
@Override
public Output<T> isPart(boolean isPart) {
return this;
}
@Override
public Output<T> write(int token) {
return this;
}
@Override
public Output<T> write(String string) {
return this;
}
@Override
public Output<T> writeln(String string) {
return this;
}
@Override
public Output<T> writeln() {
return this;
}
@Override
public T bind() {
return null;
}
@Override
public Throwable trap() {
return this.error;
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public Output<T> settings(OutputSettings settings) {
return Output.error(this.error, settings);
}
@Override
public Output<T> clone() {
return this;
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/OutputBuffer.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.codec;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
/**
* Non-blocking token stream buffer.
*/
public abstract class OutputBuffer<T> extends Output<T> {
public abstract OutputBuffer<T> isPart(boolean isPart);
public abstract int index();
public abstract OutputBuffer<T> index(int index);
public abstract int limit();
public abstract OutputBuffer<T> limit(int limit);
public abstract int capacity();
public abstract int remaining();
public abstract byte[] array();
public abstract int arrayOffset();
public abstract boolean has(int index);
public abstract int get(int index);
public abstract void set(int index, int token);
public abstract int write(ReadableByteChannel channel) throws IOException;
@Override
public abstract OutputBuffer<T> write(int token);
@Override
public OutputBuffer<T> write(String string) {
OutputBuffer<T> output = this;
final int n = string.length();
for (int i = 0; i < n; i = string.offsetByCodePoints(i, 1)) {
output = output.write(string.codePointAt(i));
}
return output;
}
@Override
public OutputBuffer<T> writeln(String string) {
return write(string).writeln();
}
@Override
public OutputBuffer<T> writeln() {
return write(settings().lineSeparator());
}
@Override
public OutputBuffer<T> display(Object object) {
Format.display(object, this);
return this;
}
@Override
public OutputBuffer<T> debug(Object object) {
Format.debug(object, this);
return this;
}
public abstract OutputBuffer<T> move(int fromIndex, int toIndex, int length);
public abstract OutputBuffer<T> step(int offset);
@Override
public OutputBuffer<T> flush() {
return this;
}
@Override
public OutputBuffer<T> fork(Object condition) {
return this;
}
@Override
public abstract OutputBuffer<T> settings(OutputSettings settings);
@Override
public OutputBuffer<T> clone() {
throw new UnsupportedOperationException();
}
private static OutputBuffer<Object> full;
private static OutputBuffer<Object> done;
/**
* Returns an {@code OutputBuffer} in the <em>full</em> state, that binds a
* {@code null} result.
*/
@SuppressWarnings("unchecked")
public static <T> OutputBuffer<T> full() {
if (full == null) {
full = new OutputBufferFull<Object>(null, OutputSettings.standard());
}
return (OutputBuffer<T>) full;
}
/**
* Returns an {@code OutputBuffer} in the <em>full</em> state, with the given
* {@code settings}.
*/
public static <T> OutputBuffer<T> full(OutputSettings settings) {
if (settings == OutputSettings.standard()) {
return full();
}
return new OutputBufferFull<T>(null, settings);
}
/**
* Returns an {@code OutputBuffer} in the <em>full</em> state, that binds the
* given {@code value}.
*/
public static <T> OutputBuffer<T> full(T value) {
if (value == null) {
return full();
}
return new OutputBufferFull<T>(value, OutputSettings.standard());
}
/**
* Returns an {@code OutputBuffer} in the <em>full</em> state, that binds the
* given {@code value}, with the given {@code settings}.
*/
public static <T> OutputBuffer<T> full(T value, OutputSettings settings) {
if (value == null && settings == OutputSettings.standard()) {
return full();
}
return new OutputBufferFull<T>(value, settings);
}
/**
* Returns an {@code OutputBuffer} in the <em>done</em> state, that binds a
* {@code null} result.
*/
@SuppressWarnings("unchecked")
public static <T> OutputBuffer<T> done() {
if (done == null) {
done = new OutputBufferDone<Object>(null, OutputSettings.standard());
}
return (OutputBuffer<T>) done;
}
/**
* Returns an {@code OutputBuffer} in the <em>done</em> state, with the given
* {@code settings}.
*/
public static <T> OutputBuffer<T> done(OutputSettings settings) {
if (settings == OutputSettings.standard()) {
return done();
}
return new OutputBufferDone<T>(null, settings);
}
/**
* Returns an {@code OutputBuffer} in the <em>done</em> state, that binds the
* given {@code value}.
*/
public static <T> OutputBuffer<T> done(T value) {
if (value == null) {
return done();
}
return new OutputBufferDone<T>(value, OutputSettings.standard());
}
/**
* Returns an {@code OutputBuffer} in the <em>done</em> state, that binds the
* given {@code value}, with the given {@code settings}.
*/
public static <T> OutputBuffer<T> done(T value, OutputSettings settings) {
if (value == null && settings == OutputSettings.standard()) {
return done();
}
return new OutputBufferDone<T>(value, settings);
}
/**
* Returns an {@code OutputBuffer} in the <em>error</em> state, with the
* given output {@code error}.
*/
public static <T> OutputBuffer<T> error(Throwable error) {
return new OutputBufferError<T>(error, OutputSettings.standard());
}
/**
* Returns an {@code OutputBuffer} in the <em>error</em> state, with the
* given output {@code error} and {@code settings}.
*/
public static <T> OutputBuffer<T> error(Throwable error, OutputSettings settings) {
return new OutputBufferError<T>(error, settings);
}
}
final class OutputBufferFull<T> extends OutputBuffer<T> {
final T value;
final OutputSettings settings;
OutputBufferFull(T value, OutputSettings settings) {
this.value = value;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isFull() {
return true;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return true;
}
@Override
public OutputBuffer<T> isPart(boolean isPart) {
if (isPart) {
return OutputBuffer.done(this.value, this.settings);
} else {
return this;
}
}
@Override
public int index() {
return 0;
}
@Override
public OutputBuffer<T> index(int index) {
if (index == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid index"), this.settings);
}
}
@Override
public int limit() {
return 0;
}
@Override
public OutputBuffer<T> limit(int limit) {
if (limit == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid limit"), this.settings);
}
}
@Override
public int capacity() {
return 0;
}
@Override
public int remaining() {
return 0;
}
@Override
public byte[] array() {
throw new UnsupportedOperationException();
}
@Override
public int arrayOffset() {
throw new UnsupportedOperationException();
}
@Override
public boolean has(int index) {
return false;
}
@Override
public int get(int index) {
throw new OutputException();
}
@Override
public void set(int index, int token) {
throw new OutputException();
}
@Override
public int write(ReadableByteChannel channel) throws IOException {
return 0;
}
@Override
public OutputBuffer<T> write(int token) {
return OutputBuffer.error(new OutputException("full"), this.settings);
}
@Override
public OutputBuffer<T> write(String string) {
return OutputBuffer.error(new OutputException("full"), this.settings);
}
@Override
public OutputBuffer<T> writeln(String string) {
return OutputBuffer.error(new OutputException("full"), this.settings);
}
@Override
public OutputBuffer<T> writeln() {
return OutputBuffer.error(new OutputException("full"), this.settings);
}
@Override
public OutputBuffer<T> move(int fromIndex, int toIndex, int length) {
if (fromIndex == 0 && toIndex == 0 && length == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid move"), this.settings);
}
}
@Override
public OutputBuffer<T> step(int offset) {
if (offset == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid step"), this.settings);
}
}
@Override
public T bind() {
return this.value;
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public OutputBuffer<T> settings(OutputSettings settings) {
return OutputBuffer.full(this.value, settings);
}
@Override
public OutputBuffer<T> clone() {
return this;
}
}
final class OutputBufferDone<T> extends OutputBuffer<T> {
final T value;
final OutputSettings settings;
OutputBufferDone(T value, OutputSettings settings) {
this.value = value;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isFull() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return false;
}
@Override
public OutputBuffer<T> isPart(boolean isPart) {
if (isPart) {
return this;
} else {
return OutputBuffer.full(this.value, this.settings);
}
}
@Override
public int index() {
return 0;
}
@Override
public OutputBuffer<T> index(int index) {
if (index == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid index"), this.settings);
}
}
@Override
public int limit() {
return 0;
}
@Override
public OutputBuffer<T> limit(int limit) {
if (limit == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid limit"), this.settings);
}
}
@Override
public int capacity() {
return 0;
}
@Override
public int remaining() {
return 0;
}
@Override
public byte[] array() {
throw new UnsupportedOperationException();
}
@Override
public int arrayOffset() {
throw new UnsupportedOperationException();
}
@Override
public boolean has(int index) {
return false;
}
@Override
public int get(int index) {
throw new OutputException();
}
@Override
public void set(int index, int token) {
throw new OutputException();
}
@Override
public int write(ReadableByteChannel channel) throws IOException {
return 0;
}
@Override
public OutputBuffer<T> write(int token) {
return OutputBuffer.error(new OutputException("done"), this.settings);
}
@Override
public OutputBuffer<T> write(String string) {
return OutputBuffer.error(new OutputException("done"), this.settings);
}
@Override
public OutputBuffer<T> writeln(String string) {
return OutputBuffer.error(new OutputException("done"), this.settings);
}
@Override
public OutputBuffer<T> writeln() {
return OutputBuffer.error(new OutputException("done"), this.settings);
}
@Override
public OutputBuffer<T> move(int fromIndex, int toIndex, int length) {
if (fromIndex == 0 && toIndex == 0 && length == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid move"), this.settings);
}
}
@Override
public OutputBuffer<T> step(int offset) {
if (offset == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid step"), this.settings);
}
}
@Override
public T bind() {
return this.value;
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public OutputBuffer<T> settings(OutputSettings settings) {
return OutputBuffer.done(this.value, settings);
}
@Override
public OutputBuffer<T> clone() {
return this;
}
}
final class OutputBufferError<T> extends OutputBuffer<T> {
final Throwable error;
final OutputSettings settings;
OutputBufferError(Throwable error, OutputSettings settings) {
this.error = error;
this.settings = settings;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isFull() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return true;
}
@Override
public boolean isPart() {
return false;
}
@Override
public OutputBuffer<T> isPart(boolean isPart) {
return this;
}
@Override
public int index() {
return 0;
}
@Override
public OutputBuffer<T> index(int index) {
if (index == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid index"), this.settings);
}
}
@Override
public int limit() {
return 0;
}
@Override
public OutputBuffer<T> limit(int limit) {
if (limit == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid limit"), this.settings);
}
}
@Override
public int capacity() {
return 0;
}
@Override
public int remaining() {
return 0;
}
@Override
public byte[] array() {
throw new UnsupportedOperationException();
}
@Override
public int arrayOffset() {
throw new UnsupportedOperationException();
}
@Override
public boolean has(int index) {
return false;
}
@Override
public int get(int index) {
throw new OutputException();
}
@Override
public void set(int index, int token) {
throw new OutputException();
}
@Override
public int write(ReadableByteChannel channel) throws IOException {
return 0;
}
@Override
public OutputBuffer<T> write(int token) {
return this;
}
@Override
public OutputBuffer<T> write(String string) {
return this;
}
@Override
public OutputBuffer<T> writeln(String string) {
return this;
}
@Override
public OutputBuffer<T> writeln() {
return this;
}
@Override
public OutputBuffer<T> move(int fromIndex, int toIndex, int length) {
if (fromIndex == 0 && toIndex == 0 && length == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid move"), this.settings);
}
}
@Override
public OutputBuffer<T> step(int offset) {
if (offset == 0) {
return this;
} else {
return OutputBuffer.error(new OutputException("invalid step"), this.settings);
}
}
@Override
public T bind() {
return null;
}
@Override
public Throwable trap() {
return this.error;
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public OutputBuffer<T> settings(OutputSettings settings) {
return OutputBuffer.error(this.error, settings);
}
@Override
public OutputBuffer<T> clone() {
return this;
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/OutputException.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.codec;
/**
* Thrown when writing invalid {@link Output}.
*/
public class OutputException extends RuntimeException {
private static final long serialVersionUID = 1L;
public OutputException(String message, Throwable cause) {
super(message, cause);
}
public OutputException(String message) {
super(message);
}
public OutputException(Throwable cause) {
super(cause);
}
public OutputException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/OutputParser.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.codec;
final class OutputParser<O> extends Parser<O> {
final Input input;
final Output<O> output;
OutputParser(Input input, Output<O> output) {
this.input = input;
this.output = output;
}
@Override
public Parser<O> feed(Input input) {
if (this.input != null) {
input = this.input.fork(input);
}
return parse(input, this.output);
}
static <O> Parser<O> parse(Input input, Output<O> output) {
while (input.isCont()) {
output = output.write(input.head());
input = input.step();
}
if (input.isDone()) {
return done(output.bind());
} else if (input.isError()) {
return error(input.trap());
} else if (output.isError()) {
return error(output.trap());
}
return new OutputParser<O>(input, output);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/OutputSettings.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.codec;
import swim.util.Murmur3;
/**
* {@link Output} production parameters. {@code OutputSettings} provide
* contextual configuration parameters to output producers, such as {@link
* Writer Writers}. Uses include enabling pretty printing and styling
* generated output. Subclasses can provide additional parameters understood
* by specialized output producers.
*/
public class OutputSettings implements Debug {
protected final String lineSeparator;
protected final boolean isPretty;
protected final boolean isStyled;
protected OutputSettings(String lineSeparator, boolean isPretty, boolean isStyled) {
this.lineSeparator = lineSeparator;
this.isPretty = isPretty;
this.isStyled = isStyled;
}
/**
* Returns the code point sequence used to separate lines of text.
* Defaults to the operating system's line separator.
*/
public final String lineSeparator() {
return this.lineSeparator;
}
/**
* Returns a copy of these settings with the given {@code lineSeparator}.
*/
public OutputSettings lineSeparator(String lineSeparator) {
return copy(lineSeparator, this.isPretty, this.isStyled);
}
/**
* Returns {@code true} if output producers should pretty print their output,
* when possible.
*/
public final boolean isPretty() {
return this.isPretty;
}
/**
* Returns a copy of these settings with the given {@code isPretty} flag.
*/
public OutputSettings isPretty(boolean isPretty) {
return copy(this.lineSeparator, isPretty, this.isStyled);
}
/**
* Returns {@code true} if output producers should style their output,
* when possible.
*/
public final boolean isStyled() {
return this.isStyled;
}
/**
* Returns a copy of these settings with the given {@code isStyled} flag.
*/
public OutputSettings isStyled(boolean isStyled) {
return copy(this.lineSeparator, this.isPretty, isStyled);
}
protected OutputSettings copy(String lineSeparator, boolean isPretty, boolean isStyled) {
return create(lineSeparator, isPretty, isStyled);
}
protected boolean canEqual(Object other) {
return other instanceof OutputSettings;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof OutputSettings) {
final OutputSettings that = (OutputSettings) other;
return that.canEqual(this) && this.lineSeparator.equals(that.lineSeparator)
&& this.isPretty == that.isPretty && this.isStyled == that.isStyled;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(OutputSettings.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
this.lineSeparator.hashCode()), Murmur3.hash(this.isPretty)),
Murmur3.hash(this.isStyled)));
}
@Override
public void debug(Output<?> output) {
output = output.write("OutputSettings").write('.');
if (!this.isPretty && !this.isStyled) {
output = output.write("standard");
} else if (this.isPretty && !this.isStyled) {
output = output.write("pretty");
} else if (!this.isPretty && this.isStyled) {
output = output.write("styled");
} else {
output = output.write("prettyStyled");
}
output = output.write('(').write(')');
if (!Format.lineSeparator().equals(this.lineSeparator)) {
output = output.write('.').write("lineSeparator").write('(').display(this.lineSeparator).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static OutputSettings standard;
private static OutputSettings pretty;
private static OutputSettings styled;
private static OutputSettings prettyStyled;
/**
* Returns {@code OutputSettings} configured with the system line separator,
* pretty printing disabled, and styling disabled.
*/
public static final OutputSettings standard() {
if (standard == null) {
standard = new OutputSettings(Format.lineSeparator(), false, false);
}
return standard;
}
/**
* Returns {@code OutputSettings} configured with the system line separator,
* pretty printing enabled, and styling disabled.
*/
public static final OutputSettings pretty() {
if (pretty == null) {
pretty = new OutputSettings(Format.lineSeparator(), true, false);
}
return pretty;
}
/**
* Returns {@code OutputSettings} configured with the system line separator,
* pretty printing disabled, and styling enabled.
*/
public static final OutputSettings styled() {
if (styled == null) {
styled = new OutputSettings(Format.lineSeparator(), false, true);
}
return styled;
}
/**
* Returns {@code OutputSettings} configured with the system line separator,
* pretty printing enabled, and styling enabled.
*/
public static final OutputSettings prettyStyled() {
if (prettyStyled == null) {
prettyStyled = new OutputSettings(Format.lineSeparator(), true, true);
}
return prettyStyled;
}
/**
* Returns {@code OutputSettings} configured with the given {@code
* lineSeparator}, pretty printing enabled if {@code isPretty} is {@code
* true}, and styling enabled if {@code isStyled} is {@code true}.
*/
public static final OutputSettings create(String lineSeparator, boolean isPretty, boolean isStyled) {
if (lineSeparator == null) {
lineSeparator = Format.lineSeparator();
}
if (Format.lineSeparator().equals(lineSeparator)) {
if (!isPretty && !isStyled) {
return standard();
} else if (isPretty && !isStyled) {
return pretty();
} else if (!isPretty && isStyled) {
return styled();
} else {
return prettyStyled();
}
}
return new OutputSettings(lineSeparator, isPretty, isStyled);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/OutputStyle.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.codec;
/**
* Stylized text output utility functions.
*/
public final class OutputStyle {
private OutputStyle() {
}
/**
* Writes the ASCII reset escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void reset(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write('m');
}
}
/**
* Writes the ASCII bold (increased intensity) escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void bold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write('m');
}
}
/**
* Writes the ASCII faint (decreased intensity) escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void faint(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('2').write('m');
}
}
/**
* Writes the ASCII black foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void black(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write(';').write('3').write('0').write('m');
}
}
/**
* Writes the ASCII red foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void red(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write(';').write('3').write('1').write('m');
}
}
/**
* Writes the ASCII green foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void green(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write(';').write('3').write('2').write('m');
}
}
/**
* Writes the ASCII yellow foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void yellow(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write(';').write('3').write('3').write('m');
}
}
/**
* Writes the ASCII blue foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void blue(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write(';').write('3').write('4').write('m');
}
}
/**
* Writes the ASCII magenta foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void magenta(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write(';').write('3').write('5').write('m');
}
}
/**
* Writes the ASCII cyan foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void cyan(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write(';').write('3').write('6').write('m');
}
}
/**
* Writes the ASCII gray foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void gray(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('0').write(';').write('3').write('7').write('m');
}
}
/**
* Writes the ASCII bold black foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void blackBold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write(';').write('3').write('0').write('m');
}
}
/**
* Writes the ASCII bold red foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void redBold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write(';').write('3').write('1').write('m');
}
}
/**
* Writes the ASCII bold green foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void greenBold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write(';').write('3').write('2').write('m');
}
}
/**
* Writes the ASCII bold yellow foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void yellowBold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write(';').write('3').write('3').write('m');
}
}
/**
* Writes the ASCII bold blue foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void blueBold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write(';').write('3').write('4').write('m');
}
}
/**
* Writes the ASCII bold magenta foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void magentaBold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write(';').write('3').write('5').write('m');
}
}
/**
* Writes the ASCII bold cyan foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void cyanBold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write(';').write('3').write('6').write('m');
}
}
/**
* Writes the ASCII bold gray foreground color escape code to {@code output},
* if {@link OutputSettings#isStyled output.settings().isStyled()} is {@code true}.
*
* @throws OutputException if {@code output} exits the <em>cont</em> state
* before the full escape code has been written.
*/
public static void grayBold(Output<?> output) {
if (output.settings().isStyled()) {
output = output.write(27).write('[').write('1').write(';').write('3').write('7').write('m');
}
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/OutputWriter.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.codec;
final class OutputWriter<I, O> extends Writer<I, O> {
final Output<?> output;
final Writer<I, O> writer;
OutputWriter(Output<?> output, Writer<I, O> writer) {
this.output = output;
this.writer = writer;
}
@Override
public Writer<I, O> feed(I input) {
return new OutputWriter<I, O>(this.output, this.writer.feed(input));
}
@Override
public Writer<I, O> pull(Output<?> output) {
if (this.output != null) {
output = this.output.fork(output);
}
return write(output, this.writer);
}
@Override
public Writer<I, O> fork(Object condition) {
return new OutputWriter<I, O>(this.output, this.writer.fork(condition));
}
@Override
public O bind() {
return this.writer.bind();
}
@Override
public Throwable trap() {
return this.writer.trap();
}
static <I, O> Writer<I, O> write(Output<?> output, Writer<I, O> writer) {
writer = writer.pull(output);
if (!writer.isCont()) {
return writer;
}
return new OutputWriter<I, O>(output, writer);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Parser.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.codec;
/**
* Continuation of how to parse subsequent {@link Input} tokens from a stream.
* {@code Parser} enables efficient, interruptible parsing of network protocols
* and data formats, without intermediate buffering.
*
* <h3>Input tokens</h3>
* <p>A {@code Parser} reads tokens from an {@code Input} reader. Input tokens
* are modeled as primitive {@code int}s, commonly representing Unicode code
* points, or raw octets. Each {@code Parser} implementation specifies the
* semantic type of input tokens it consumes.</p>
*
* <h3>Parser states</h3>
* <p>A {@code Parser} is always in one of three states: <em>cont</em>inue,
* <em>done</em>, or <em>error</em>. The <em>cont</em> state indicates that
* {@link #feed(Input) feed} is ready to consume {@code Input}; the
* <em>done</em> state indicates that parsing terminated successfully, and that
* {@link #bind() bind} will return the parsed result; the <em>error</em> state
* indicates that parsing terminated in failure, and that {@link #trap() trap}
* will return the parse error. {@code Parser} subclasses default to the
* <em>cont</em> state.</p>
*
* <h3>Feeding input</h3>
* <p>The {@link #feed(Input)} method incrementally parses as much {@code
* Input} as it can, before returning another {@code Parser} that represents
* the continuation of how to parse additional {@code Input}. The {@code Input}
* passed to {@code feed} is only guaranteed to be valid for the duration of
* the method call; references to the provided {@code Input} instance must not
* be stored.</p>
*
* <h3>Parser results</h3>
* <p>A {@code Parser} produces a parsed result of type {@code O}, obtained
* via the {@link #bind()} method. {@code bind} is only guaranteed to return a
* result when in the <em>done</em> state; though {@code bind} may optionally
* make available partial results in other states. A failed {@code Parser}
* provides a parse error via the {@link #trap()} method. {@code trap} is only
* guaranteed to return an error when in the <em>error</em> state.</p>
*
* <h3>Continuations</h3>
* <p>A {@code Parser} instance represents a continuation of how to parse
* remaining {@code Input}. Rather than parsing a complete input in one go,
* a {@code Parser} takes an {@code Input} chunk and returns another {@code
* Parser} instance that knows how to parse subsequent {@code Input} chunks.
* This enables non-blocking, incremental parsing that can be interrupted
* whenever an {@code Input} reader runs out of immediately available data.
* A {@code Parser} terminates by returning a continuation in either the
* <em>done</em> state, or the <em>error</em> state.
* {@link Parser#done(Object)} returns a {@code Parser} in the <em>done</em>
* state. {@link Parser#error(Throwable)} returns a {@code Parser} in the
* <em>error</em> state.</p>
*
* <h3>Iteratees</h3>
* <p>{@code Parser} is an <a href="https://en.wikipedia.org/wiki/Iteratee">
* Iteratee</a>. Though unlike strictly functional iteratees, a {@code Parser}
* statefully iterates over its {@code Input}, rather than allocating an object
* for each incremental input continutaion. This internal mutability minimizes
* garbage collector memory pressure, without violating the functional Iteratee
* abstraction, provided that {@code feed} logically takes exclusive ownership
* of its {@code Input} when invoked, and logically returns ownership of the
* {@code Input} in a state that's consistent with the returned {@code Parser}
* continuation.</p>
*
* <h3>Immutability</h3>
* <p>A {@code Parser} should be immutable. Specifically, an invocation of
* {@code feed} should not alter the behavior of future calls to {@code feed}
* on the same {@code Parser} instance. A {@code Parser} should only mutate
* its internal state if it's essential to do so, such as for critical path
* performance reasons.</p>
*
* <h3>Backtracking</h3>
* <p>{@code feed} can internally {@link Input#clone() clone} its {@code
* Input}, if it might need to backtrack. Keep in mind that, because {@code
* Input} is only valid for the duration of a call to {@code feed}, input must
* be internally buffered if it needs to be preserved between {@code feed}
* invocations.</p>
*
* <h3>Forking</h3>
* <p>The {@link #fork(Object)} method passes an out-of-band condition to a
* {@code Parser}, yielding a {@code Parser} continuation whose behavior may
* be altered by the given condition. For example, an HTML {@code Parser}
* might {@code fork} an inner text parser to directly parse an embedded micro
* format out of an HTML element, based on some out-of-band schema information.
* The types of conditions accepted by {@code fork}, and their intended
* semantics, are implementation defined.</p>
*/
public abstract class Parser<O> extends Decoder<O> {
/**
* Returns {@code true} when {@link #feed(Input) feed} is able to consume
* {@code Input}. i.e. this {@code Parser} is in the <em>cont</em> state.
*/
@Override
public boolean isCont() {
return true;
}
/**
* Returns {@code true} when parsing has terminated successfully, and {@link
* #bind() bind} will return the parsed result. i.e. this {@code Parser} is
* in the <em>done</em> state.
*/
@Override
public boolean isDone() {
return false;
}
/**
* Returns {@code true} when parsing has terminated in failure, and {@link
* #trap() trap} will return the parse error. i.e. this {@code Parser} is in
* the <em>error</em> state.
*/
@Override
public boolean isError() {
return false;
}
/**
* Incrementally parses as much {@code input} as possible, and returns
* another {@code Parser} that represents the continuation of how to parse
* additional {@code Input}. If {@code input} enters the <em>done</em> state,
* {@code feed} <em>must</em> return a terminated {@code Parser}, i.e. a
* {@code Parser} in the <em>done</em> state, or in the <em>error</em> state.
* The given {@code input} is only guaranteed to be valid for the duration of
* the method call; references to {@code input} must not be stored.
*/
public abstract Parser<O> feed(Input input);
@Override
public Parser<O> feed(InputBuffer input) {
return feed((Input) input);
}
/**
* Returns a {@code Parser} continuation whose behavior may be altered by the
* given out-of-band {@code condition}.
*/
@Override
public Parser<O> fork(Object condition) {
return this;
}
/**
* Returns the parsed result. Only guaranteed to return a result when in the
* <em>done</em> state.
*
* @throws IllegalStateException if this {@code Parser} is not in the
* <em>done</em> state.
*/
@Override
public O bind() {
throw new IllegalStateException();
}
/**
* Returns the parse error. Only guaranteed to return an error when in the
* <em>error</em> state.
*
* @throws IllegalStateException if this {@code Parser} is not in the
* <em>error</em> state.
*/
@Override
public Throwable trap() {
throw new IllegalStateException();
}
/**
* Casts an errored {@code Parser} to a different output type.
* A {@code Parser} in the <em>error</em> state can have any output type.
*
* @throws IllegalStateException if this {@code Parser} is not in the
* <em>error</em> state.
*/
@Override
public <O2> Parser<O2> asError() {
throw new IllegalStateException();
}
private static Parser<Object> done;
/**
* Returns a {@code Parser} in the <em>done</em> state that {@code bind}s
* a {@code null} parsed result.
*/
@SuppressWarnings("unchecked")
public static <O> Parser<O> done() {
if (done == null) {
done = new ParserDone<Object>(null);
}
return (Parser<O>) done;
}
/**
* Returns a {@code Parser} in the <em>done</em> state that {@code bind}s
* the given parsed {@code output}.
*/
public static <O> Parser<O> done(O output) {
if (output == null) {
return done();
} else {
return new ParserDone<O>(output);
}
}
/**
* Returns a {@code Parser} in the <em>error</em> state that {@code trap}s
* the given parse {@code error}.
*/
public static <O> Parser<O> error(Throwable error) {
return new ParserError<O>(error);
}
/**
* Returns a {@code Parser} in the <em>error</em> state that {@code trap}s a
* {@link ParserException} with the given {@code diagnostic}.
*/
public static <O> Parser<O> error(Diagnostic diagnostic) {
return error(new ParserException(diagnostic));
}
}
final class ParserDone<O> extends Parser<O> {
final O output;
ParserDone(O output) {
this.output = output;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public Parser<O> feed(Input input) {
return this;
}
@Override
public O bind() {
return this.output;
}
}
final class ParserError<O> extends Parser<O> {
final Throwable error;
ParserError(Throwable error) {
this.error = error;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isError() {
return true;
}
@Override
public Parser<O> feed(Input input) {
return this;
}
@Override
public O bind() {
if (this.error instanceof Error) {
throw (Error) this.error;
} else if (this.error instanceof RuntimeException) {
throw (RuntimeException) this.error;
} else {
throw new ParserException(this.error);
}
}
@Override
public Throwable trap() {
return this.error;
}
@SuppressWarnings("unchecked")
@Override
public <O2> Parser<O2> asError() {
return (Parser<O2>) this;
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/ParserException.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.codec;
/**
* Thrown when a {@link Parser} parses invdalid syntax.
*/
public class ParserException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final Diagnostic diagnostic;
public ParserException(Diagnostic diagnostic) {
super(diagnostic.message());
this.diagnostic = diagnostic;
}
public ParserException(String message, Throwable cause) {
super(message, cause);
this.diagnostic = null;
}
public ParserException(String message) {
super(message);
this.diagnostic = null;
}
public ParserException(Throwable cause) {
super(cause);
this.diagnostic = null;
}
public ParserException() {
super();
this.diagnostic = null;
}
public Diagnostic getDiagnostic() {
return this.diagnostic;
}
@Override
public String toString() {
if (this.diagnostic != null) {
return this.diagnostic.toString();
} else {
return super.toString();
}
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Span.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.codec;
import java.util.Objects;
import swim.util.Murmur3;
/**
* Description of a source range, identified by a closed interval between start
* and end {@link Mark marks}.
*/
public final class Span extends Tag {
final Mark start;
final Mark end;
Span(Mark start, Mark end) {
this.start = start;
this.end = end;
}
@Override
public Mark start() {
return this.start;
}
@Override
public Mark end() {
return this.end;
}
@Override
public Tag union(Tag other) {
if (other instanceof Mark) {
final Mark that = (Mark) other;
final Mark start = this.start.min(that);
final Mark end = this.end.max(that);
if (start == this.start && end == this.end) {
return this;
} else {
return Span.from(start, end);
}
} else if (other instanceof Span) {
final Span that = (Span) other;
final Mark start = this.start.min(that.start);
final Mark end = this.end.max(that.end);
if (start == this.start && end == this.end) {
return this;
} else {
return Span.from(start, end);
}
}
throw new UnsupportedOperationException(other.toString());
}
@Override
public Span shift(Mark mark) {
final Mark start = this.start.shift(mark);
final Mark end = this.end.shift(mark);
if (start == this.start && end == this.end) {
return this;
} else {
return Span.from(start, end);
}
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Span) {
final Span that = (Span) other;
return this.start.equals(that.start) && this.end.equals(that.end);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(Span.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.start.hashCode()), this.end.hashCode()));
}
@Override
public void display(Output<?> output) {
if (this.start.note != null) {
output = output.write(this.start.note).write(": ");
}
Format.displayInt(this.start.line, output);
output = output.write(':');
Format.displayInt(this.start.column, output);
output = output.write('-');
Format.displayInt(this.end.line, output);
output = output.write(':');
Format.displayInt(this.end.column, output);
if (this.end.note != null) {
output = output.write(": ").write(this.end.note);
}
}
@Override
public void debug(Output<?> output) {
output = output.write("Span").write('.').write("from").write('(');
this.start.debug(output);
output = output.write(", ");
this.end.debug(output);
output = output.write(')');
}
@Override
public String toString() {
return Format.display(this);
}
private static int hashSeed;
/**
* Returns a new {@code Span} representing the closed interval between the
* given {@code start} and {@code end} marks.
*/
public static Span from(Mark start, Mark end) {
start = Objects.requireNonNull(start);
end = Objects.requireNonNull(end);
if (start.offset > end.offset) {
final Mark tmp = start;
start = end;
end = tmp;
}
return new Span(start, end);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/StringInput.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.codec;
final class StringInput extends Input {
String string;
Object id;
long offset;
int line;
int column;
InputSettings settings;
int index;
boolean isPart;
StringInput(String string, Object id, long offset, int line, int column,
InputSettings settings, int index, boolean isPart) {
this.string = string;
this.id = id;
this.offset = offset;
this.line = line;
this.column = column;
this.settings = settings;
this.index = index;
this.isPart = isPart;
}
StringInput(String string) {
this(string, null, 0L, 1, 1, InputSettings.standard(), 0, false);
}
@Override
public boolean isCont() {
return this.index < this.string.length();
}
@Override
public boolean isEmpty() {
return this.isPart && this.index >= this.string.length();
}
@Override
public boolean isDone() {
return !this.isPart && this.index >= this.string.length();
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return this.isPart;
}
@Override
public Input isPart(boolean isPart) {
this.isPart = isPart;
return this;
}
@Override
public int head() {
if (this.index < this.string.length()) {
return this.string.codePointAt(this.index);
} else {
throw new InputException();
}
}
@Override
public Input step() {
final int index = this.index;
if (index < this.string.length()) {
final int c = this.string.codePointAt(index);
this.index = this.string.offsetByCodePoints(index, 1);
this.offset += (long) (this.index - index);
if (c == '\n') {
this.line += 1;
this.column = 1;
} else {
this.column += 1;
}
return this;
} else {
final Throwable error = new InputException("invalid step");
return Input.error(error, this.id, mark(), this.settings);
}
}
@Override
public Input seek(Mark mark) {
if (mark != null) {
final long index = (long) this.index + (this.offset - mark.offset);
if (0L <= index && index <= this.string.length()) {
this.offset = mark.offset;
this.line = mark.line;
this.column = mark.column;
this.index = (int) index;
return this;
} else {
final Throwable error = new InputException("invalid seek to " + mark);
return Input.error(error, this.id, mark(), this.settings);
}
} else {
this.offset = 0L;
this.line = 1;
this.column = 1;
this.index = 0;
return this;
}
}
@Override
public Object id() {
return this.id;
}
@Override
public Input id(Object id) {
this.id = id;
return this;
}
@Override
public Mark mark() {
return Mark.at(this.offset, this.line, this.column);
}
@Override
public Input mark(Mark mark) {
this.offset = mark.offset;
this.line = mark.line;
this.column = mark.column;
return this;
}
public long offset() {
return this.offset;
}
public int line() {
return this.line;
}
public int column() {
return this.column;
}
@Override
public InputSettings settings() {
return this.settings;
}
@Override
public Input settings(InputSettings settings) {
this.settings = settings;
return this;
}
@Override
public Input clone() {
return new StringInput(this.string, this.id, this.offset, this.line,
this.column, this.settings, this.index, this.isPart);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/StringOutput.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.codec;
final class StringOutput extends Output<String> {
final StringBuilder builder;
OutputSettings settings;
StringOutput(StringBuilder builder, OutputSettings settings) {
this.builder = builder;
this.settings = settings;
}
@Override
public boolean isCont() {
return true;
}
@Override
public boolean isFull() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return false;
}
@Override
public Output<String> isPart(boolean isPart) {
return this;
}
@Override
public Output<String> write(int codePoint) {
this.builder.appendCodePoint(codePoint);
return this;
}
@Override
public Output<String> write(String string) {
this.builder.append(string);
return this;
}
@Override
public Output<String> writeln(String string) {
this.builder.append(string).append(this.settings.lineSeparator);
return this;
}
@Override
public Output<String> writeln() {
this.builder.append(this.settings.lineSeparator);
return this;
}
@Override
public OutputSettings settings() {
return this.settings;
}
@Override
public Output<String> settings(OutputSettings settings) {
this.settings = settings;
return this;
}
@Override
public String bind() {
return this.builder.toString();
}
@Override
public Output<String> clone() {
return new StringOutput(new StringBuilder(this.builder.toString()), this.settings);
}
@Override
public String toString() {
return this.builder.toString();
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/StringParser.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.codec;
final class StringParser extends Parser<String> {
final StringBuilder builder;
StringParser(StringBuilder builder) {
this.builder = builder;
}
StringParser() {
this(null);
}
@Override
public Parser<String> feed(Input input) {
return parse(input, this.builder);
}
static Parser<String> parse(Input input, StringBuilder builder) {
if (builder == null) {
builder = new StringBuilder();
}
while (input.isCont()) {
builder.appendCodePoint(input.head());
input = input.step();
}
if (input.isDone()) {
return done(builder.toString());
} else if (input.isError()) {
return error(input.trap());
}
return new StringParser(builder);
}
static Parser<String> parse(Input input) {
return parse(input, null);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/StringWriter.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.codec;
final class StringWriter extends Writer<Object, Object> {
final Object value;
final String input;
final int index;
StringWriter(Object value, String input, int index) {
this.value = value;
this.input = input;
this.index = index;
}
StringWriter(Object value, Object input) {
this(value, input != null ? input.toString() : "null", 0);
}
StringWriter() {
this(null, "", 0);
}
@Override
public Writer<Object, Object> feed(Object input) {
if (input instanceof Integer) {
return new Base10IntegerWriter(input, ((Integer) input).longValue());
} else if (input instanceof Long) {
return new Base10IntegerWriter(input, ((Long) input).longValue());
} else {
return new StringWriter(input, input);
}
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, value, input, index);
}
static Writer<Object, Object> write(Output<?> output, Object value, String input, int index) {
final int length = input != null ? input.length() : 0;
while (index < length && output.isCont()) {
output = output.write(input.codePointAt(index));
index = input.offsetByCodePoints(index, 1);
}
if (index == length) {
return done(value);
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new StringWriter(value, input, index);
}
static Writer<Object, Object> write(Output<?> output, Object value, Object input) {
if (input instanceof Integer) {
return Base10IntegerWriter.write(output, value, ((Integer) input).longValue());
} else if (input instanceof Long) {
return Base10IntegerWriter.write(output, value, ((Long) input).longValue());
} else {
return write(output, value, input != null ? input.toString() : "null", 0);
}
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Tag.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.codec;
/**
* Description of a source location. Tags are used to annotate input sources,
* particularly for {@link Diagnostic diagnostic} purposes. A {@link Mark} tag
* annotates a source position. A {@link Span} tag annotate a source range.
*
* @see Diagnostic
*/
public abstract class Tag implements Display, Debug {
/**
* Returns the first source position covered by this {@code Tag}.
*/
public abstract Mark start();
/**
* Returns the last source position covered by this {@code Tag}.
*/
public abstract Mark end();
/**
* Returns a {@code Tag} that includes all source locations covered by
* both this tag, and some {@code other} tag.
*/
public abstract Tag union(Tag other);
/**
* Returns the position of this {@code Tag} relative to the given
* {@code mark}.
*/
public abstract Tag shift(Mark mark);
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Unicode.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.codec;
/**
* Unicode code point {@link Input}/{@link Output}/{@link Writer} factory.
*
* <p>The {@code Unicode.stringInput(...)} family of functions return an {@code
* Input} that reads the Unicode code points of a {@code String}.</p>
*
* <p>The {@code Unicode.stringOutput(...)} family of functions return an {@code
* Output} that writes Unicode code points to an internal buffer, and {@link
* Output#bind() bind} a {@code String} containing all written code points.</p>
*/
public final class Unicode {
private Unicode() {
// nop
}
public static Input stringInput(String string) {
return new StringInput(string);
}
/**
* Returns a new {@code Output} that writes Unicode code points to the
* given string {@code builder}, using the given output {@code settings}.
* The returned {@code Output} accepts an unbounded number of code points,
* remaining permanently in the <em>cont</em> state, and {@link Output#bind()
* binds} a {@code String} containing all written code points.
*/
public static Output<String> stringOutput(StringBuilder builder, OutputSettings settings) {
return new StringOutput(builder, settings);
}
/**
* Returns a new {@code Output} that writes Unicode code points to the given
* string {@code builder}. The returned {@code Output} accepts an unbounded
* number of code points, remaining permanently in the <em>cont</em> state,
* and {@link Output#bind() binds} a {@code String} containing all written
* code points.
*/
public static Output<String> stringOutput(StringBuilder builder) {
return new StringOutput(builder, OutputSettings.standard());
}
/**
* Returns a new {@code Output} that appends Unicode code points to the given
* {@code string}, using the given output {@code settings}. The returned
* {@code Output} accepts an unbounded number of code points, remaining
* permanently in the <em>cont</em> state, and {@link Output#bind() binds}
* a {@code String} containing the given {@code string}, and all appended
* code points.
*/
public static Output<String> stringOutput(String string, OutputSettings settings) {
return new StringOutput(new StringBuilder(string), settings);
}
/**
* Returns a new {@code Output} that appends Unicode code points to the given
* {@code string}. The returned {@code Output} accepts an unbounded number
* of code points, remaining permanently in the <em>cont</em> state, and
* {@link Output#bind() binds} a {@code String} containing the given {@code
* string}, and all appended code points.
*/
public static Output<String> stringOutput(String string) {
return new StringOutput(new StringBuilder(string), OutputSettings.standard());
}
public static Output<String> stringOutput(int initialCapacity, OutputSettings settings) {
return new StringOutput(new StringBuilder(initialCapacity), settings);
}
public static Output<String> stringOutput(int initialCapacity) {
return new StringOutput(new StringBuilder(initialCapacity), OutputSettings.standard());
}
/**
* Returns a new {@code Output} that buffers Unicode code points, using the
* given output {@code settings}. The returned {@code Output} accepts an
* unbounded number of code points, remaining permanently in the <em>cont</em>
* state, and {@link Output#bind() binds} a {@code String} containing all
* written code points.
*/
public static Output<String> stringOutput(OutputSettings settings) {
return new StringOutput(new StringBuilder(), settings);
}
/**
* Returns a new {@code Output} that buffers Unicode code points.
* The returned {@code Output} accepts an unbounded number of code points,
* remaining permanently in the <em>cont</em> state, and {@link Output#bind()
* binds} a {@code String} containing all written code points.
*/
public static Output<String> stringOutput() {
return new StringOutput(new StringBuilder(), OutputSettings.standard());
}
public static Parser<String> stringParser(StringBuilder builder) {
return new StringParser(builder);
}
public static Parser<String> stringParser() {
return new StringParser();
}
public static Parser<String> parseString(Input input, StringBuilder builder) {
return StringParser.parse(input, builder);
}
public static Parser<String> parseString(Input input) {
return StringParser.parse(input);
}
@SuppressWarnings("unchecked")
public static <I> Writer<I, Object> stringWriter() {
return (Writer<I, Object>) new StringWriter();
}
@SuppressWarnings("unchecked")
public static <I, O> Writer<I, O> stringWriter(O input) {
return (Writer<I, O>) new StringWriter(input, input);
}
@SuppressWarnings("unchecked")
public static <I> Writer<I, Object> writeString(Object input, Output<?> output) {
return (Writer<I, Object>) StringWriter.write(output, null, input);
}
public static Parser<String> lineParser() {
return new LineParser();
}
public static Parser<String> parseLine(Input input, StringBuilder output) {
return LineParser.parse(input, output);
}
public static Parser<String> parseLine(Input input) {
return LineParser.parse(input, new StringBuilder());
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Utf8.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.codec;
import java.io.IOException;
import java.io.InputStream;
/**
* UTF-8 {@link Input}/{@link Output} factory.
*/
public final class Utf8 {
private Utf8() {
// nop
}
/**
* Returns the number of bytes in the UTF-8 encoding of the Unicode code
* point {@code c}, handling invalid code unit sequences according to the
* {@code errorMode} policy. Returns the size of the {@link
* UtfErrorMode#replacementChar()} for surrogates and invalid code points,
* if {@link UtfErrorMode#isReplacement()} is `true`; otherwise returns `0`
* for surrogates and invalid code points. Uses the two byte modified UTF-8
* encoding of the NUL character ({@code U+0000}), if {@link
* UtfErrorMode#isNonZero()} is `true`.
*/
public static int sizeOf(int c, UtfErrorMode errorMode) {
if (c == 0x0000 && errorMode.isNonZero()) { // Modified UTF-8
return 2; // U+0000 encoded as 0xC0, 0x80
} else if (c >= 0x0000 && c <= 0x007F) { // U+0000..U+007F
return 1;
} else if (c >= 0x0080 && c <= 0x07FF) { // U+0080..U+07FF
return 2;
} else if (c >= 0x0800 && c <= 0xFFFF || // U+0800..U+D7FF
c >= 0xE000 && c <= 0xFFFF) { // U+E000..U+FFFF
return 3;
} else if (c >= 0x10000 && c <= 0x10FFFF) { // U+10000..U+10FFFF
return 4;
} else { // surrogate or invalid code point
if (errorMode.isReplacement()) {
return sizeOf(errorMode.replacementChar());
} else {
return 0;
}
}
}
/**
* Returns the number of bytes in the UTF-8 encoding of the Unicode code
* point {@code c}; returns the size of the Unicode replacement character
* ({@code U+FFFD}) for surrogates and invalid code points.
*/
public static int sizeOf(int c) {
if (c >= 0x0000 && c <= 0x007F) { // U+0000..U+007F
return 1;
} else if (c >= 0x0080 && c <= 0x07FF) { // U+0080..U+07FF
return 2;
} else if (c >= 0x0800 && c <= 0xFFFF || // U+0800..U+D7FF
c >= 0xE000 && c <= 0xFFFF) { // U+E000..U+FFFF
return 3;
} else if (c >= 0x10000 && c <= 0x10FFFF) { // U+10000..U+10FFFF
return 4;
} else { // surrogate or invalid code point
return 3;
}
}
/**
* Returns the number of bytes in the UTF-8 encoding the given {@code string},
* handling invalid code unit sequences according to the {@code errorMode}
* policy.
*/
public static int sizeOf(String string, UtfErrorMode errorMode) {
int size = 0;
for (int i = 0, n = string.length(); i < n; i = string.offsetByCodePoints(i, 1)) {
size += Utf8.sizeOf(string.codePointAt(i), errorMode);
}
return size;
}
/**
* Returns the number of bytes in the UTF-8 encoding the given {@code string},
* assuming the Unicode replacement character ({@code U+FFFD}) replaces
* unpaired surrogates and invalid code points.
*/
public static int sizeOf(String string) {
int size = 0;
for (int i = 0, n = string.length(); i < n; i = string.offsetByCodePoints(i, 1)) {
size += Utf8.sizeOf(string.codePointAt(i));
}
return size;
}
public static Input decodedInput(Input input, UtfErrorMode errorMode) {
return new Utf8DecodedInput(input, errorMode);
}
public static Input decodedInput(Input input) {
return new Utf8DecodedInput(input, UtfErrorMode.fatal());
}
/**
* Returns a new {@code Output} that accepts UTF-8 code unit sequences, and
* writes decoded Unicode code points to the composed {@code output}, handling
* invalid code unit sequences according to the {@code errorMode} policy.
*/
public static <T> Output<T> decodedOutput(Output<T> output, UtfErrorMode errorMode) {
return new Utf8DecodedOutput<T>(output, errorMode);
}
/**
* Returns a new {@code Output} that accepts UTF-8 code unit sequences, and
* writes decoded Unicode code points to the composed {@code output}, handling
* invalid code unit sequences according to the {@link UtfErrorMode#fatal()}
* policy.
*/
public static <T> Output<T> decodedOutput(Output<T> output) {
return new Utf8DecodedOutput<T>(output, UtfErrorMode.fatal());
}
/**
* Returns a new {@code Output} that accepts UTF-8 code unit sequences, and
* writes decoded Unicode code points to a growable {@code String}, handling
* invalid code unit sequences according to the {@link UtfErrorMode#fatal()}
* policy. The returned {@code Output} accepts an unbounded number of UTF-8
* code units, remaining permanently in the <em>cont</em> state, and {@link
* Output#bind() binds} a {@code String} containing all decoded code points.
*/
public static Output<String> decodedString() {
return decodedOutput(Unicode.stringOutput());
}
public static <T> Output<T> encodedOutput(Output<T> output, UtfErrorMode errorMode) {
return new Utf8EncodedOutput<T>(output, errorMode);
}
public static <T> Output<T> encodedOutput(Output<T> output) {
return new Utf8EncodedOutput<T>(output, UtfErrorMode.fatal());
}
public static Parser<String> stringParser(StringBuilder builder, UtfErrorMode errorMode) {
return new InputParser<String>(decodedInput(Input.empty(), errorMode), Unicode.stringParser(builder));
}
public static Parser<String> stringParser(StringBuilder builder) {
return new InputParser<String>(decodedInput(Input.empty()), Unicode.stringParser(builder));
}
public static Parser<String> stringParser(UtfErrorMode errorMode) {
return new InputParser<String>(decodedInput(Input.empty(), errorMode), Unicode.stringParser());
}
public static Parser<String> stringParser() {
return new InputParser<String>(decodedInput(Input.empty()), Unicode.stringParser());
}
public static Parser<String> parseString(Input input, StringBuilder builder, UtfErrorMode errorMode) {
return InputParser.parse(decodedInput(input, errorMode), Unicode.stringParser(builder));
}
public static Parser<String> parseString(Input input, StringBuilder builder) {
return InputParser.parse(decodedInput(input), Unicode.stringParser(builder));
}
public static Parser<String> parseString(Input input, UtfErrorMode errorMode) {
return InputParser.parse(decodedInput(input, errorMode), Unicode.stringParser());
}
public static Parser<String> parseString(Input input) {
return InputParser.parse(decodedInput(input), Unicode.stringParser());
}
public static <I, O> Writer<I, O> stringWriter(O input, UtfErrorMode errorMode) {
final Writer<I, O> writer = Unicode.stringWriter(input);
return new OutputWriter<I, O>(encodedOutput(Output.full(), errorMode), writer);
}
public static <I, O> Writer<I, O> stringWriter(O input) {
final Writer<I, O> writer = Unicode.stringWriter(input);
return new OutputWriter<I, O>(encodedOutput(Output.full()), writer);
}
public static <O> Writer<?, O> writeString(O input, Output<?> output, UtfErrorMode errorMode) {
return OutputWriter.write(encodedOutput(output, errorMode), Unicode.stringWriter(input));
}
public static <O> Writer<?, O> writeString(O input, Output<?> output) {
return OutputWriter.write(encodedOutput(output), Unicode.stringWriter(input));
}
/**
* Returns a new {@code Decoder} that writes decoded Unicode code points to
* the given {@code output}, handling invalid code unit sequences according
* to the {@code errorMode} policy.
*/
public static <O> Decoder<O> outputDecoder(Output<O> output, UtfErrorMode errorMode) {
return new OutputParser<O>(decodedInput(Input.empty(), errorMode), output);
}
/**
* Returns a new {@code Decoder} that writes decoded Unicode code points to
* the given {@code output}, handling invalid code unit sequences according
* to the {@link UtfErrorMode#fatal()} policy.
*/
public static <O> Decoder<O> outputDecoder(Output<O> output) {
return new OutputParser<O>(decodedInput(Input.empty()), output);
}
/**
* Writes the decoded Unicode code points of the {@code input} buffer to the
* given {@code output}, returning a {@code Decoder} continuation that knows
* how to decode subsequent input buffers. Handles invalid code unit
* sequences according to the {@code errorMode} policy.
*/
public static <O> Decoder<O> decodeOutput(Output<O> output, InputBuffer input, UtfErrorMode errorMode) {
return OutputParser.parse(decodedInput(input, errorMode), output);
}
/**
* Writes the decoded Unicode code points of the {@code input} buffer to the
* given {@code output}, returning a {@code Decoder} continuation that knows
* how to decode subsequent input buffers. Handles invalid code unit
* sequences according to the {@link UtfErrorMode#fatal()} policy.
*/
public static <O> Decoder<O> decodeOutput(Output<O> output, Input input) {
return OutputParser.parse(decodedInput(input), output);
}
public static <O> Parser<O> decodedParser(Parser<O> parser, UtfErrorMode errorMode) {
return new InputParser<O>(decodedInput(Input.empty(), errorMode), parser);
}
public static <O> Parser<O> decodedParser(Parser<O> parser) {
return new InputParser<O>(decodedInput(Input.empty()), parser);
}
public static <O> Parser<O> parseDecoded(Parser<O> parser, Input input, UtfErrorMode errorMode) {
return InputParser.parse(decodedInput(input, errorMode), parser);
}
public static <O> Parser<O> parseDecoded(Parser<O> parser, Input input) {
return InputParser.parse(decodedInput(input), parser);
}
public static <I, O> Writer<I, O> encodedWriter(Writer<I, O> writer, UtfErrorMode errorMode) {
return new OutputWriter<I, O>(encodedOutput(Output.full(), errorMode), writer);
}
public static <I, O> Writer<I, O> encodedWriter(Writer<I, O> writer) {
return new OutputWriter<I, O>(encodedOutput(Output.full()), writer);
}
public static <I, O> Writer<I, O> writeEncoded(Writer<I, O> writer, Output<?> output, UtfErrorMode errorMode) {
return OutputWriter.write(encodedOutput(output, errorMode), writer);
}
public static <I, O> Writer<I, O> writeEncoded(Writer<I, O> writer, Output<?> output) {
return OutputWriter.write(encodedOutput(output), writer);
}
public static <O> Decoder<O> decode(Parser<O> parser, InputStream input) throws IOException {
return Binary.decode(decodedParser(parser), input);
}
public static <O> O read(Parser<O> parser, InputStream input) throws IOException {
return Binary.read(decodedParser(parser), input);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Utf8DecodedInput.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.codec;
final class Utf8DecodedInput extends Input {
Input input;
UtfErrorMode errorMode;
long offset;
int line;
int column;
int state;
int c1;
int c2;
int c3;
int have;
InputException error;
Utf8DecodedInput(Input input, UtfErrorMode errorMode, long offset, int line,
int column, int c1, int c2, int c3, int have, int state,
InputException error) {
this.input = input;
this.errorMode = errorMode;
this.offset = offset;
this.line = line;
this.column = column;
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
this.have = have;
this.state = state;
this.error = error;
}
Utf8DecodedInput(Input input, UtfErrorMode errorMode) {
this(input, errorMode, 0L, 1, 1, -1, -1, -1, 0, DECODE, null);
}
@Override
public boolean isCont() {
return state() >= 0;
}
@Override
public boolean isEmpty() {
return state() == EMPTY;
}
@Override
public boolean isDone() {
return state() == DONE;
}
@Override
public boolean isError() {
return state() == ERROR;
}
@Override
public boolean isPart() {
return this.input.isPart();
}
@Override
public Input isPart(boolean isPart) {
this.input = this.input.isPart(isPart);
return this;
}
int state() {
if (this.state == DECODE) {
Input input = this.input;
final int c1;
final int c2;
final int c3;
final int c4;
if (this.c1 >= 0) { // use buffered c1
c1 = this.c1;
} else if (input.isCont()) {
c1 = input.head();
input = input.step();
} else {
c1 = -1;
}
if (c1 == 0 && this.errorMode.isNonZero()) { // invalid NUL byte
this.have = 1;
this.state = ERROR;
this.error = new InputException("invalid NUL byte");
} else if (c1 >= 0 && c1 <= 0x7f) { // U+0000..U+007F
this.have = 1;
this.state = c1;
} else if (c1 >= 0xc2 && c1 <= 0xf4) {
if (this.c2 >= 0) { // use buffered c2
c2 = this.c2;
} else if (input.isCont()) {
c2 = input.head();
} else {
c2 = -1;
}
if (c1 >= 0xc2 && c1 <= 0xdf && c2 >= 0x80 && c2 <= 0xbf) { // U+0080..U+07FF
if (this.c2 < 0) { // consume valid c2
input = input.step();
}
this.have = 2;
this.state = (c1 & 0x1f) << 6 | c2 & 0x3f;
} else if (c1 == 0xe0 && c2 >= 0xa0 && c2 <= 0xbf // U+0800..U+0FFF
|| c1 >= 0xe1 && c1 <= 0xec && c2 >= 0x80 && c2 <= 0xbf // U+1000..U+CFFF
|| c1 == 0xed && c2 >= 0x80 && c2 <= 0x9f // U+D000..U+D7FF
|| c1 >= 0xee && c1 <= 0xef && c2 >= 0x80 && c2 <= 0xbf) { // U+E000..U+FFFF
if (this.c2 < 0) { // consume valid c2
input = input.step();
}
if (this.c3 >= 0) { // use buffered c3
c3 = this.c3;
} else if (input.isCont()) {
c3 = input.head();
} else {
c3 = -1;
}
if (c3 >= 0x80 && c3 <= 0xbf) {
if (this.c3 < 0) { // consume valid c3
input = input.step();
}
this.have = 3;
this.state = (c1 & 0x0f) << 12 | (c2 & 0x3f) << 6 | c3 & 0x3f;
} else if (c3 >= 0) { // invalid c3
this.have = 2;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1, c2, c3));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isDone()) { // truncated c3
this.have = 2;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1, c2));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isEmpty()) { // awaiting c3
this.c1 = c1;
this.c2 = c2;
this.state = EMPTY;
}
} else if (c1 == 0xf0 && c2 >= 0x90 && c2 <= 0xbf // U+10000..U+3FFFF
|| c1 >= 0xf1 && c1 <= 0xf3 && c2 >= 0x80 && c2 <= 0xbf // U+40000..U+FFFFF
|| c1 == 0xf4 && c2 >= 0x80 && c2 <= 0x8f) { // U+100000..U+10FFFF
if (this.c2 < 0) { // consume valid c2
input = input.step();
}
if (this.c3 >= 0) { // use buffered c3
c3 = this.c3;
} else if (input.isCont()) {
c3 = input.head();
} else {
c3 = -1;
}
if (c3 >= 0x80 && c3 <= 0xbf) {
if (this.c3 < 0) { // consume valid c3
input = input.step();
}
if (input.isCont()) {
c4 = input.head();
} else {
c4 = -1;
}
if (c4 >= 0x80 && c4 <= 0xbf) {
input = input.step(); // consume valid c4
this.have = 4;
this.state = (c1 & 0x07) << 18 | (c2 & 0x3f) << 12 | (c3 & 0x3f) << 6 | c4 & 0x3f;
} else if (c4 >= 0) { // invalid c4
this.have = 3;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1, c2, c3, c4));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isDone()) { // truncated c4
this.have = 3;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1, c2, c3));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isEmpty()) { // awaiting c4
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
this.state = EMPTY;
}
} else if (c3 >= 0) { // invalid c3
this.have = 2;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1, c2, c3));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isDone()) { // truncated c3
this.have = 2;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1, c2));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isEmpty()) { // awaiting c3
this.c1 = c1;
this.c2 = c2;
this.state = EMPTY;
}
} else if (c2 >= 0) { // invalid c2
this.have = 1;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1, c2));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isDone()) { // truncated c2
this.have = 1;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isEmpty()) { // awaiting c2
this.c1 = c1;
this.state = EMPTY;
}
} else if (c1 >= 0) { // invalid c1
this.have = 1;
if (this.errorMode.isFatal()) {
this.state = ERROR;
this.error = new InputException(invalid(c1));
} else {
this.state = this.errorMode.replacementChar();
}
} else if (input.isDone()) { // end of input
this.state = DONE;
} else if (input.isEmpty()) { // awaiting c1
this.state = EMPTY;
}
this.input = input;
}
return this.state;
}
private static String invalid(int c1) {
Output<String> output = Unicode.stringOutput();
output = output.write("invalid UTF-8 code unit: ");
Base16.uppercase().writeIntLiteral(c1, output, 2);
return output.bind();
}
private static String invalid(int c1, int c2) {
Output<String> output = Unicode.stringOutput();
output = output.write("invalid UTF-8 code unit sequence: ");
Base16.uppercase().writeIntLiteral(c1, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c2, output, 2);
return output.bind();
}
private static String invalid(int c1, int c2, int c3) {
Output<String> output = Unicode.stringOutput();
output = output.write("invalid UTF-8 code unit sequence: ");
Base16.uppercase().writeIntLiteral(c1, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c2, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c3, output, 2);
return output.bind();
}
private static String invalid(int c1, int c2, int c3, int c4) {
Output<String> output = Unicode.stringOutput();
output = output.write("invalid UTF-8 code unit sequence: ");
Base16.uppercase().writeIntLiteral(c1, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c2, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c3, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c4, output, 2);
return output.bind();
}
@Override
public int head() {
final int state = state();
if (state < 0) {
throw new InputException();
}
return state;
}
@Override
public Input step() {
final int state = state();
if (state >= 0) {
this.offset += (long) this.have;
if (state == '\n') {
this.line += 1;
this.column = 1;
} else {
this.column += 1;
}
this.c1 = -1;
this.c2 = -1;
this.c3 = -1;
this.have = 0;
this.state = DECODE;
return this;
} else {
final Throwable error = new InputException("invalid step");
return Input.error(error, this.input.id(), mark(), this.input.settings());
}
}
@Override
public Input fork(Object condition) {
if (condition instanceof Input) {
this.input = (Input) condition;
this.state = DECODE;
}
return this;
}
@Override
public Throwable trap() {
if (state() == ERROR) {
return this.error;
} else {
throw new IllegalStateException();
}
}
@Override
public Input seek(Mark mark) {
this.input.seek(mark);
if (mark != null) {
this.offset = mark.offset;
this.line = mark.line;
this.column = mark.column;
} else {
this.offset = 0L;
this.line = 1;
this.column = 1;
}
this.c1 = -1;
this.c2 = -1;
this.c3 = -1;
this.have = 0;
this.state = DECODE;
this.error = null;
return this;
}
@Override
public Object id() {
return this.input.id();
}
@Override
public Input id(Object id) {
this.input = this.input.id(id);
return this;
}
@Override
public Mark mark() {
return Mark.at(this.offset, this.line, this.column);
}
@Override
public Input mark(Mark mark) {
this.input = this.input.mark(mark);
this.offset = mark.offset;
this.line = mark.line;
this.column = mark.column;
return this;
}
public long offset() {
return this.offset;
}
public int line() {
return this.line;
}
public int column() {
return this.column;
}
@Override
public InputSettings settings() {
return this.input.settings();
}
@Override
public Input settings(InputSettings settings) {
this.input = this.input.settings(settings);
return this;
}
@Override
public Input clone() {
return new Utf8DecodedInput(this.input.clone(), this.errorMode, this.offset,
this.line, this.column, this.c1, this.c2, this.c3,
this.have, this.state, this.error);
}
private static final int DECODE = -1;
private static final int EMPTY = -2;
private static final int DONE = -3;
private static final int ERROR = -4;
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Utf8DecodedOutput.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.codec;
final class Utf8DecodedOutput<T> extends Output<T> {
Output<T> output;
final UtfErrorMode errorMode;
int c1;
int c2;
int c3;
int have;
Utf8DecodedOutput(Output<T> output, UtfErrorMode errorMode,
int c1, int c2, int c3, int have) {
this.output = output;
this.errorMode = errorMode;
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
this.have = have;
}
Utf8DecodedOutput(Output<T> output, UtfErrorMode errorMode) {
this(output, errorMode, -1, -1, -1, 0);
}
@Override
public boolean isCont() {
return this.output.isCont();
}
@Override
public boolean isFull() {
return this.output.isFull();
}
@Override
public boolean isDone() {
return this.output.isDone();
}
@Override
public boolean isError() {
return this.output.isError();
}
@Override
public boolean isPart() {
return this.output.isPart();
}
@Override
public Output<T> isPart(boolean isPart) {
this.output = this.output.isPart(isPart);
return this;
}
@Override
public Output<T> write(int c) {
int c1 = this.c1;
int c2 = this.c2;
int c3 = this.c3;
int c4 = -1;
int have = this.have;
if (c >= 0) {
switch (have) {
case 0:
c1 = c & 0xff;
have = 1;
break;
case 1:
c2 = c & 0xff;
have = 2;
break;
case 2:
c3 = c & 0xff;
have = 3;
break;
case 3:
c4 = c & 0xff;
have = 4;
break;
default:
throw new AssertionError("unreachable");
}
}
if (c1 == 0 && this.errorMode.isNonZero()) { // invalid NUL byte
return error(new OutputException("unexpected NUL byte"));
} else if (c1 >= 0 && c1 <= 0x7f) { // U+0000..U+007F
this.output = this.output.write(c1);
this.have = 0;
} else if (c1 >= 0xc2 && c1 <= 0xf4) {
if (c1 >= 0xc2 && c1 <= 0xdf && c2 >= 0x80 && c2 <= 0xbf) { // U+0080..U+07FF
this.output = this.output.write((c1 & 0x1f) << 6 | c2 & 0x3f);
this.c1 = -1;
this.have = 0;
} else if (c1 == 0xe0 && c2 >= 0xa0 && c2 <= 0xbf // U+0800..U+0FFF
|| c1 >= 0xe1 && c1 <= 0xec && c2 >= 0x80 && c2 <= 0xbf // U+1000..U+CFFF
|| c1 == 0xed && c2 >= 0x80 && c2 <= 0x9f // U+D000..U+D7FF
|| c1 >= 0xee && c1 <= 0xef && c2 >= 0x80 && c2 <= 0xbf) { // U+E000..U+FFFF
if (c3 >= 0x80 && c3 <= 0xbf) {
this.output = this.output.write((c1 & 0x0f) << 12 | (c2 & 0x3f) << 6 | c3 & 0x3f);
this.c1 = -1;
this.c2 = -1;
this.have = 0;
} else if (c3 >= 0) { // invalid c3
if (this.errorMode.isFatal()) {
return error(new OutputException(invalid(c1, c2, c3)));
}
this.output = this.output.write(this.errorMode.replacementChar());
this.c1 = c3;
this.c2 = -1;
this.have = 1;
} else if (c < 0 || this.output.isDone()) { // incomplete c3
return error(new OutputException(invalid(c1, c2)));
} else { // awaiting c3
this.c2 = c2;
this.have = 2;
}
} else if (c1 == 0xf0 && c2 >= 0x90 && c2 <= 0xbf // U+10000..U+3FFFF
|| c1 >= 0xf1 && c1 <= 0xf3 && c2 >= 0x80 && c2 <= 0xbf // U+40000..U+FFFFF
|| c1 == 0xf4 && c2 >= 0x80 && c2 <= 0x8f) { // U+100000..U+10FFFF
if (c3 >= 0x80 && c3 <= 0xbf) {
if (c4 >= 0x80 && c4 <= 0xbf) {
this.have = 4;
this.output = this.output.write((c1 & 0x07) << 18 | (c2 & 0x3f) << 12 | (c3 & 0x3f) << 6 | c4 & 0x3f);
this.c1 = -1;
this.c2 = -1;
this.c3 = -1;
this.have = 0;
} else if (c4 >= 0) { // invalid c4
if (this.errorMode.isFatal()) {
return error(new OutputException(invalid(c1, c2, c3, c4)));
}
this.output = this.output.write(this.errorMode.replacementChar());
this.c1 = c4;
this.c2 = -1;
this.c3 = -1;
this.have = 1;
} else if (c < 0 || this.output.isDone()) { // incomplete c4
return error(new OutputException(invalid(c1, c2, c3)));
} else { // awaiting c4
this.c3 = c3;
this.have = 3;
}
} else if (c3 >= 0) { // invalid c3
if (this.errorMode.isFatal()) {
return error(new OutputException(invalid(c1, c2, c3)));
}
this.output = this.output.write(this.errorMode.replacementChar());
this.c1 = c3;
this.c2 = -1;
this.have = 1;
} else if (c < 0 || this.output.isDone()) { // incomplete c3
return error(new OutputException(invalid(c1, c2)));
} else { // awaiting c3
this.c2 = c2;
this.have = 2;
}
} else if (c2 >= 0) { // invalid c2
if (this.errorMode.isFatal()) {
return error(new OutputException(invalid(c1, c2)));
}
this.output = this.output.write(this.errorMode.replacementChar());
this.c1 = c2;
this.have = 1;
} else if (c < 0 || this.output.isDone()) { // incomplete c2
return error(new OutputException(invalid(c1)));
} else { // awaiting c2
this.c1 = c1;
this.have = 1;
}
} else if (c1 >= 0) { // invalid c1
if (this.errorMode.isFatal()) {
return error(new OutputException(invalid(c1)));
}
this.output = this.output.write(this.errorMode.replacementChar());
this.have = 0;
}
if (this.output.isError()) {
return this.output;
}
return this;
}
private static String invalid(int c1) {
Output<String> output = Unicode.stringOutput();
output = output.write("invalid UTF-8 code unit: ");
Base16.uppercase().writeIntLiteral(c1, output, 2);
return output.bind();
}
private static String invalid(int c1, int c2) {
Output<String> output = Unicode.stringOutput();
output = output.write("invalid UTF-8 code unit sequence: ");
Base16.uppercase().writeIntLiteral(c1, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c2, output, 2);
return output.bind();
}
private static String invalid(int c1, int c2, int c3) {
Output<String> output = Unicode.stringOutput();
output = output.write("invalid UTF-8 code unit sequence: ");
Base16.uppercase().writeIntLiteral(c1, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c2, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c3, output, 2);
return output.bind();
}
private static String invalid(int c1, int c2, int c3, int c4) {
Output<String> output = Unicode.stringOutput();
output = output.write("invalid UTF-8 code unit sequence: ");
Base16.uppercase().writeIntLiteral(c1, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c2, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c3, output, 2);
output = output.write(' ');
Base16.uppercase().writeIntLiteral(c4, output, 2);
return output.bind();
}
@Override
public OutputSettings settings() {
return this.output.settings();
}
@Override
public Output<T> settings(OutputSettings settings) {
this.output = this.output.settings(settings);
return this;
}
@Override
public Output<T> fork(Object condition) {
this.output = this.output.fork(condition);
return this;
}
@Override
public T bind() {
if (this.have == 0) {
return this.output.bind();
} else {
return write(-1).bind();
}
}
@Override
public Throwable trap() {
return this.output.trap();
}
@Override
public Output<T> clone() {
return new Utf8DecodedOutput<T>(this.output.clone(), this.errorMode,
this.c1, this.c2, this.c3, this.have);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Utf8EncodedOutput.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.codec;
final class Utf8EncodedOutput<T> extends Output<T> {
Output<T> output;
UtfErrorMode errorMode;
int c2;
int c3;
int c4;
int index;
Utf8EncodedOutput(Output<T> output, UtfErrorMode errorMode, int c2, int c3, int c4, int index) {
this.output = output;
this.errorMode = errorMode;
this.c2 = c2;
this.c3 = c3;
this.c4 = c4;
this.index = index;
}
Utf8EncodedOutput(Output<T> output, UtfErrorMode errorMode) {
this(output, errorMode, 0, 0, 0, 4);
}
@Override
public boolean isCont() {
return this.output.isCont();
}
@Override
public boolean isFull() {
return this.output.isFull();
}
@Override
public boolean isDone() {
return this.output.isDone();
}
@Override
public boolean isError() {
return false;
}
@Override
public boolean isPart() {
return this.output.isPart();
}
@Override
public Output<T> isPart(boolean isPart) {
this.output = this.output.isPart(isPart);
return this;
}
@Override
public Output<T> write(int c) {
int c1 = 0;
int c2 = this.c2;
int c3 = this.c3;
int c4 = this.c4;
int index = this.index;
while (index < 4) {
if (this.output.isCont()) {
switch (index) {
case 1: this.output = this.output.write(c2); this.c2 = 0; break;
case 2: this.output = this.output.write(c3); this.c3 = 0; break;
case 3: this.output = this.output.write(c4); this.c4 = 0; break;
default: throw new AssertionError("unreachable");
}
index += 1;
} else {
return error(new OutputException("unable to flush buffered code units"));
}
}
if (c >= 0 && c <= 0x7f) { // U+0000..U+007F
c4 = c;
index = 3;
} else if (c >= 0x80 && c <= 0x7ff) { // U+0080..U+07FF
c3 = 0xc0 | (c >>> 6);
c4 = 0x80 | (c & 0x3f);
index = 2;
} else if (c >= 0x0800 && c <= 0xffff || // U+0800..U+D7FF
c >= 0xe000 && c <= 0xffff) { // U+E000..U+FFFF
c2 = 0xe0 | (c >>> 12);
c3 = 0x80 | ((c >>> 6) & 0x3f);
c4 = 0x80 | (c & 0x3f);
index = 1;
} else if (c >= 0x10000 && c <= 0x10ffff) { // U+10000..U+10FFFF
c1 = 0xf0 | (c >>> 18);
c2 = 0x80 | ((c >>> 12) & 0x3f);
c3 = 0x80 | ((c >>> 6) & 0x3f);
c4 = 0x80 | (c & 0x3f);
index = 0;
} else { // surrogate or invalid code point
if (this.errorMode.isFatal()) {
return error(new OutputException("invalid code point: U+" + Integer.toHexString(c)));
} else {
return write(this.errorMode.replacementChar());
}
}
do {
switch (index) {
case 0: this.output = this.output.write(c1); break;
case 1: this.output = this.output.write(c2); this.c2 = 0; break;
case 2: this.output = this.output.write(c3); this.c3 = 0; break;
case 3: this.output = this.output.write(c4); this.c4 = 0; break;
default: throw new AssertionError("unreachable");
}
index += 1;
} while (index < 4 && this.output.isCont());
if (index < 4) {
if (index < 3) {
if (index < 2) {
this.c2 = c2;
}
this.c3 = c3;
}
this.c4 = c4;
}
this.index = index;
return this;
}
@Override
public Output<T> flush() {
int index = this.index;
while (index < 4) {
if (this.output.isCont()) {
switch (index) {
case 1: this.output = this.output.write(this.c2); this.c2 = 0; break;
case 2: this.output = this.output.write(this.c3); this.c3 = 0; break;
case 3: this.output = this.output.write(this.c4); this.c4 = 0; break;
default: throw new AssertionError("unreachable");
}
index += 1;
} else {
return error(new OutputException("unable to flush buffered code units"));
}
}
this.index = index;
return this;
}
@Override
public OutputSettings settings() {
return this.output.settings();
}
@Override
public Output<T> settings(OutputSettings settings) {
this.output.settings(settings);
return this;
}
@SuppressWarnings("unchecked")
@Override
public Output<T> fork(Object condition) {
if (condition instanceof Output<?>) {
this.output = (Output<T>) condition;
}
return this;
}
@Override
public T bind() {
return this.output.bind();
}
@Override
public Output<T> clone() {
return new Utf8EncodedOutput<T>(this.output.clone(), this.errorMode,
this.c2, this.c3, this.c4, this.index);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/UtfErrorMode.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.codec;
import swim.util.Murmur3;
/**
* Unicode transformation format error handling mode.
*/
public abstract class UtfErrorMode implements Debug {
UtfErrorMode() {
}
/**
* Returns {@code true} if a Unicode decoding should abort with an error when
* an invalid code unit sequence is encountered.
*/
public boolean isFatal() {
return false;
}
/**
* Returns {@code true} if a Unicode decoding should substitute invalid code
* unit sequences with a replacement character.
*/
public boolean isReplacement() {
return false;
}
/**
* Returns the Unicode code point of the replacement character to substitute
* for invalid code unit sequences. Defaults to {@code U+FFFD}.
*/
public int replacementChar() {
return 0xfffd;
}
/**
* Returns {@code true} if Unicode decoding should abort with an error when
* a {@code NUL} byte is encountered.
*/
public abstract boolean isNonZero();
/**
* Returns a {@code UtfErrorMode} that, if {@code isNonZero} is {@code true},
* aborts when Unicode decoding encounters a {@code NUL} byte.
*/
public abstract UtfErrorMode isNonZero(boolean isNonZero);
@Override
public abstract void debug(Output<?> output);
@Override
public String toString() {
return Format.debug(this);
}
private static UtfErrorMode fatal;
private static UtfErrorMode fatalNonZero;
private static UtfErrorMode replacement;
private static UtfErrorMode replacementNonZero;
/**
* Returns a {@code UtfErrorMode} that aborts Unicode decoding with an error
* when invalid code unit sequences are encountered.
*/
public static UtfErrorMode fatal() {
if (fatal == null) {
fatal = new UtfFatalErrorMode(false);
}
return fatal;
}
/**
* Returns a {@code UtfErrorMode} that aborts Unicode decoding with an error
* when invalid code unit sequences, and {@code NUL} bytes, are encountered.
*/
public static UtfErrorMode fatalNonZero() {
if (fatalNonZero == null) {
fatalNonZero = new UtfFatalErrorMode(true);
}
return fatalNonZero;
}
/**
* Returns a {@code UtfErrorMode} that substitutes invalid code unit
* sequences with the replacement character ({@code U+FFFD}).
*/
public static UtfErrorMode replacement() {
if (replacement == null) {
replacement = new UtfReplacementErrorMode(0xfffd, false);
}
return replacement;
}
/**
* Returns a {@code UtfErrorMode} that substitutes invalid code unit
* sequences with the given {@code replacementChar}.
*/
public static UtfErrorMode replacement(int replacementChar) {
if (replacementChar == 0xfffd) {
return replacement();
} else {
return new UtfReplacementErrorMode(replacementChar, false);
}
}
/**
* Returns a {@code UtfErrorMode} that substitutes invalid code unit
* sequences with the replacement character ({@code U+FFFD}), and aborts
* decoding with an error when {@code NUL} bytes are encountered.
*/
public static UtfErrorMode replacementNonZero() {
if (replacementNonZero == null) {
replacementNonZero = new UtfReplacementErrorMode(0xfffd, true);
}
return replacementNonZero;
}
/**
* Returns a {@code UtfErrorMode} that substitutes invalid code unit
* sequences with the given {@code replacementChar}, and aborts decoding
* with an error when {@code NUL} bytes are encountered.
*/
public static UtfErrorMode replacementNonZero(int replacementChar) {
if (replacementChar == 0xfffd) {
return replacementNonZero();
} else {
return new UtfReplacementErrorMode(replacementChar, true);
}
}
}
final class UtfFatalErrorMode extends UtfErrorMode {
private final boolean isNonZero;
UtfFatalErrorMode(boolean isNonZero) {
this.isNonZero = isNonZero;
}
@Override
public boolean isFatal() {
return true;
}
@Override
public boolean isNonZero() {
return this.isNonZero;
}
@Override
public UtfErrorMode isNonZero(boolean isNonZero) {
if (isNonZero) {
return UtfErrorMode.fatalNonZero();
} else {
return UtfErrorMode.fatal();
}
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof UtfFatalErrorMode) {
final UtfFatalErrorMode that = (UtfFatalErrorMode) other;
return this.isNonZero == that.isNonZero;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(UtfFatalErrorMode.class);
}
return Murmur3.mash(Murmur3.mix(hashSeed, Murmur3.hash(this.isNonZero)));
}
@Override
public void debug(Output<?> output) {
output = output.write("UtfErrorMode").write('.')
.write(this.isNonZero ? "fatalNonZero" : "fatal")
.write('(').write(')');
}
private static int hashSeed;
}
final class UtfReplacementErrorMode extends UtfErrorMode {
private final int replacementChar;
private final boolean isNonZero;
UtfReplacementErrorMode(int replacementChar, boolean isNonZero) {
this.replacementChar = replacementChar;
this.isNonZero = isNonZero;
}
@Override
public boolean isReplacement() {
return true;
}
@Override
public int replacementChar() {
return this.replacementChar;
}
@Override
public boolean isNonZero() {
return this.isNonZero;
}
@Override
public UtfErrorMode isNonZero(boolean isNonZero) {
if (this.replacementChar == 0xfffd) {
if (isNonZero) {
return UtfErrorMode.replacementNonZero();
} else {
return UtfErrorMode.replacement();
}
} else {
return new UtfReplacementErrorMode(this.replacementChar, isNonZero);
}
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof UtfReplacementErrorMode) {
final UtfReplacementErrorMode that = (UtfReplacementErrorMode) other;
return this.replacementChar == that.replacementChar
&& this.isNonZero == that.isNonZero;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(UtfReplacementErrorMode.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.replacementChar), Murmur3.hash(this.isNonZero)));
}
@Override
public void debug(Output<?> output) {
output = output.write("UtfErrorMode").write('.')
.write(this.isNonZero ? "replacementNonZero" : "replacement")
.write('(');
if (this.replacementChar != 0xfffd) {
Format.debugChar(this.replacementChar, output);
}
output = output.write(')');
}
private static int hashSeed;
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/Writer.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.codec;
/**
* Continuation of how to write subsequent {@link Output} tokens to a stream.
* {@code Writer} enables efficient, interruptible writing of network protocols
* and data formats, without intermediate buffering.
*
* <h3>Output tokens</h3>
* <p>A {@code Writer} writes tokens to an {@code Output} writer. Output
* tokens are modeled as primitive {@code int}s, commonly representing Unicode
* code points, or raw octets. Each {@code Writer} implementation specifies
* the semantic type of output tokens it produces.</p>
*
* <h3>Writer states</h3>
* <p>A {@code Writer} is always in one of three states: <em>cont</em>inue,
* <em>done</em>, or <em>error</em>. The <em>cont</em> state indicates that
* {@link #pull(Output) pull} is ready to produce {@code Output}; the
* <em>done</em> state indicates that writing terminated successfully, and that
* {@link #bind() bind} will return the written result; the <em>error</em>
* state indicates that writing terminated in failure, and that {@link #trap()
* trap} will return the write error. {@code Writer} subclasses default to the
* <em>cont</em> state.</p>
*
* <h3>Feeding input</h3>
* <p>The {@link #feed(Object) feed(I)} method returns a {@code Writer} that
* represents the continuation of how to write the given input object to
* subsequent {@code Output} writers. {@code feed} can be used to specify
* an initial object to write, or to change the object to be written.</p>
*
* <h3>Pulling output</h3>
* <p>The {@link #pull(Output)} method incrementally writes as much {@code
* Output} as it can, before returning another {@code Writer} that represents
* the continuation of how to write additional {@code Output}. The {@code
* Output} passed to {@code pull} is only guaranteed to be valid for the
* duration of the method call; references to the provided {@code Output}
* instance must not be stored.</p>
*
* <h3>Writer results</h3>
* <p>A {@code Writer} produces a written result of type {@code O}, obtained
* via the {@link #bind()} method. {@code bind} is only guaranteed to return a
* result when in the <em>done</em> state; though {@code bind} may optionally
* make available partial results in other states. A failed {@code Writer}
* provides a write error via the {@link #trap()} method. {@code trap} is only
* guaranteed to return an error when in the <em>error</em> state.</p>
*
* <h3>Continuations</h3>
* <p>A {@code Writer} instance represents a continuation of how to write
* remaining {@code Output}. Rather than writing a complete output in one go,
* a {@code Writer} takes an {@code Output} chunk and returns another {@code
* Writer} instance that knows how to write subsequent {@code Output} chunks.
* This enables non-blocking, incremental writing that can be interrupted
* whenever an {@code Output} writer runs out of space. A {@code Writer}
* terminates by returning a continuation in either the <em>done</em> state,
* or the <em>error</em> state. {@link Writer#done(Object)} returns a {@code
* Writer} in the <em>done</em> state. {@link Writer#error(Throwable)} returns
* a {@code Writer} in the <em>error</em> state.</p>
*
* <h3>Forking</h3>
* <p>The {@link #fork(Object)} method passes an out-of-band condition to a
* {@code Writer}, yielding a {@code Writer} continuation whose behavior may
* be altered by the given condition. For example, a console {@code Writer}
* might support a {@code fork} condition that changes the color and style of
* printed text. The types of conditions accepted by {@code fork}, and their
* intended semantics, are implementation defined.</p>
*/
public abstract class Writer<I, O> extends Encoder<I, O> {
/**
* Returns {@code true} when {@link #pull(Output) pull} is able to produce
* {@code Output}. i.e. this {@code Writer} is in the <em>cont</em> state.
*/
@Override
public boolean isCont() {
return true;
}
/**
* Returns {@code true} when writing has terminated successfully, and {@link
* #bind() bind} will return the written result. i.e. this {@code Writer} is
* in the <em>done</em> state.
*/
@Override
public boolean isDone() {
return false;
}
/**
* Returns {@code true} when writing has terminated in failure, and {@link
* #trap() trap} will return the write error. i.e. this {@code Writer} is in
* the <em>error</em> state.
*/
@Override
public boolean isError() {
return false;
}
/**
* Returns a {@code Writer} that represents the continuation of how to write
* the given {@code input} object.
*
* @throws IllegalArgumentException if this {@code Writer} does not know how
* to write the given {@code input} object.
*/
@Override
public Writer<I, O> feed(I input) {
throw new IllegalArgumentException();
}
/**
* Incrementally writes as much {@code output} as possible, and returns
* another {@code Writer} that represents the continuation of how to write
* additional {@code Output}. If {@code output} enters the <em>done</em>
* state, {@code pull} <em>must</em> return a terminated {@code Writer},
* i.e. a {@code Writer} in the <em>done</em> state, or in the <em>error</em>
* state. The given {@code output} is only guaranteed to be valid for the
* duration of the method call; references to {@code output} must not be
* stored.
*/
public abstract Writer<I, O> pull(Output<?> output);
@Override
public Writer<I, O> pull(OutputBuffer<?> output) {
return pull((Output<?>) output);
}
/**
* Returns a {@code Writer} continuation whose behavior may be altered by the
* given out-of-band {@code condition}.
*/
@Override
public Writer<I, O> fork(Object condition) {
return this;
}
/**
* Returns the written result. Only guaranteed to return a result when in
* the <em>done</em> state.
*
* @throws IllegalStateException if this {@code Writer} is not in the
* <em>done</em> state.
*/
@Override
public O bind() {
throw new IllegalStateException();
}
/**
* Returns the write error. Only guaranteed to return an error when in the
* <em>error</em> state.
*
* @throws IllegalStateException if this {@code Writer} is not in the
* <em>error</em> state.
*/
@Override
public Throwable trap() {
throw new IllegalStateException();
}
/**
* Casts a done {@code Writer} to a different input type.
* A {@code Writer} in the <em>done</em> state can have any input type.
*
* @throws IllegalStateException if this {@code Writer} is not in the
* <em>done</em> state.
*/
@Override
public <I2> Writer<I2, O> asDone() {
throw new IllegalStateException();
}
/**
* Casts an errored {@code Writer} to different input and output types.
* A {@code Writer} in the <em>error</em> state can have any input type,
* and any output type.
*
* @throws IllegalStateException if this {@code Writer} is not in the
* <em>error</em> state.
*/
@Override
public <I2, O2> Writer<I2, O2> asError() {
throw new IllegalStateException();
}
/**
* Returns a {@code Writer} that continues writing {@code that} {@code
* Writer}, after it finishes writing {@code this} {@code Writer}.
*/
public <O2> Writer<I, O2> andThen(Writer<I, O2> that) {
return new WriterAndThen<I, O2>(this, that);
}
@Override
public <O2> Writer<I, O2> andThen(Encoder<I, O2> that) {
return andThen((Writer<I, O2>) that);
}
private static Writer<Object, Object> done;
/**
* Returns a {@code Writer} in the <em>done</em> state that {@code bind}s
* a {@code null} written result.
*/
@SuppressWarnings("unchecked")
public static <I, O> Writer<I, O> done() {
if (done == null) {
done = new WriterDone<Object, Object>(null);
}
return (Writer<I, O>) done;
}
/**
* Returns a {@code Writer} in the <em>done</em> state that {@code bind}s
* the given written {@code output}.
*/
public static <I, O> Writer<I, O> done(O output) {
if (output == null) {
return done();
} else {
return new WriterDone<I, O>(output);
}
}
/**
* Returns a {@code Writer} in the <em>error</em> state that {@code trap}s
* the given write {@code error}.
*/
public static <I, O> Writer<I, O> error(Throwable error) {
return new WriterError<I, O>(error);
}
}
final class WriterDone<I, O> extends Writer<I, O> {
private final O output;
WriterDone(O output) {
this.output = output;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public Writer<I, O> pull(Output<?> output) {
return this;
}
@Override
public O bind() {
return this.output;
}
@SuppressWarnings("unchecked")
@Override
public <I2> Writer<I2, O> asDone() {
return (Writer<I2, O>) this;
}
@Override
public <O2> Writer<I, O2> andThen(Writer<I, O2> that) {
return that;
}
}
final class WriterError<I, O> extends Writer<I, O> {
private final Throwable error;
WriterError(Throwable error) {
this.error = error;
}
@Override
public boolean isCont() {
return false;
}
@Override
public boolean isError() {
return true;
}
@Override
public Writer<I, O> pull(Output<?> output) {
return this;
}
@Override
public O bind() {
if (this.error instanceof Error) {
throw (Error) this.error;
} else if (this.error instanceof RuntimeException) {
throw (RuntimeException) this.error;
} else {
throw new ParserException(this.error);
}
}
@Override
public Throwable trap() {
return this.error;
}
@SuppressWarnings("unchecked")
@Override
public <I2, O2> Writer<I2, O2> asError() {
return (Writer<I2, O2>) this;
}
@SuppressWarnings("unchecked")
@Override
public <O2> Writer<I, O2> andThen(Writer<I, O2> that) {
return (Writer<I, O2>) this;
}
}
final class WriterAndThen<I, O> extends Writer<I, O> {
private final Writer<I, ?> head;
private final Writer<I, O> tail;
WriterAndThen(Writer<I, ?> head, Writer<I, O> tail) {
this.head = head;
this.tail = tail;
}
@Override
public Writer<I, O> pull(Output<?> output) {
final Writer<I, ?> head = this.head.pull(output);
if (head.isDone()) {
return this.tail;
} else if (head.isError()) {
return head.asError();
}
return new WriterAndThen<I, O>(head, this.tail);
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/WriterException.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.codec;
/**
* Thrown when a {@link Writer} attempts to write invalid syntax.
*/
public class WriterException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WriterException(String message, Throwable cause) {
super(message, cause);
}
public WriterException(String message) {
super(message);
}
public WriterException(Throwable cause) {
super(cause);
}
public WriterException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-codec/3.10.0/swim | java-sources/ai/swim/swim-codec/3.10.0/swim/codec/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.
/**
* Incremental decoders, encoders, parsers, and writers. {@code swim.codec}
* enables efficient, interruptible transcoding of network protocols and data
* formats, without blocking or intermediate buffering.
*
* <h2>Inputs and Outputs</h2>
*
* <p>An {@link Input} reader abstracts over a non-blocking token input stream,
* with single token lookahead. An {@link Output} writer abstracts over a
* non-blocking token output stream.</p>
*
* <h2>Parsers and Writers</h2>
*
* <p>A {@link Parser} incrementally reads from a sequence of {@link Input}
* chunks to produce a parsed result. A {@link Writer} incrementally writes
* to a sequence of {@link Output} chunks.</p>
*
* <h2>Decoders and Encoders</h2>
*
* <p>A {@link Decoder} incrementally decodes a sequence of {@link InputBuffer
* input buffers} to produce a decoded result. An {@link Encoder}
* incrementally encodes a value into a sequence of {@link OutputBuffer output
* buffers}.</p>
*
* <h2>Binary codecs</h2>
*
* <p>The {@link Binary} factory has methods to create {@link Input} readers
* that read bytes out of byte buffers, and methods to create {@link Output}
* writers that write bytes into byte buffers.</p>
*
* <h2>Text codecs</h2>
*
* <p>The {@link Unicode} factory has methods to create {@link Input} readers
* that read Unicode code points out of strings, and methods to create {@link
* Output} writers that write Unicode code points into strings.</p>
*
* <p>The {@link Utf8} factory has methods to create {@link Input} readers
* that decode Unicode code points out of UTF-8 encoded byte buffers, and
* methods to create {@link Output} writers that encode Unicode code points
* into UTF-8 encoded byte buffers.</p>
*
* <h2>Binary-Text codecs</h2>
*
* <p>The {@link Base10} factory has methods to create {@link Parser}s that
* incrementally parse decimal formatted integers, and methods to create {@link
* Writer}s that incrementally write decimal formatted integers.</p>
*
* <p>The {@link Base16} factory has methods to create {@link Parser}s that
* incrementally decode hexadecimal encoded text input into byte buffers, and
* methods to create {@link Writer}s that incrementally encode byte buffers to
* hexadecimal encoded text output.</p>
*
* <p>The {@link Base64} factory has methods to create {@link Parser}s that
* incrementally decode base-64 encoded text input into byte buffers, and
* methods to create {@link Writer}s that incrementally encode byte buffers to
* base-64 encoded text output.</p>
*
* <h2>Formatters</h2>
*
* <p>The {@link Display} interface provides a standard way for implementing
* classes to directly output human readable display strings. Similarly, the
* {@link Debug} interface provides a standard way for implementing classes to
* directly output developer readable debug strings.</p>
*
* <p>{@link Format} provides extension methods to output display and debug
* strings for all types, including builtin Java types. {@link OutputStyle}
* provides helper functions to conditionally emit ASCII escape codes to
* stylize text for console output.</p>
*
* <h2>Diagnostics</h2>
*
* <p>A {@link Tag} abstracts over a source input location. A {@link Mark}
* describes a source input position, and a {@link Span} describes a source
* input range. A {@link Diagnostic} attaches an informational message to a
* source input location, and supports displaying the diagnostic as an
* annotated snippet of the relevant source input.</p>
*/
package swim.codec;
|
0 | java-sources/ai/swim/swim-collections | java-sources/ai/swim/swim-collections/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.
/**
* Immutable, structure sharing collections.
*/
module swim.collections {
requires transitive swim.util;
requires transitive swim.codec;
exports swim.collections;
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/ArrayMap.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.collections;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Murmur3;
final class ArrayMap<K, V> implements Debug {
final Object[] slots;
ArrayMap(Object[] slots) {
this.slots = slots;
}
ArrayMap(K key, V value) {
slots = new Object[2];
slots[0] = key;
slots[1] = value;
}
ArrayMap(K key0, V value0, K key1, V value1) {
slots = new Object[4];
slots[0] = key0;
slots[1] = value0;
slots[2] = key1;
slots[3] = value1;
}
public boolean isEmpty() {
return slots.length == 0;
}
public int size() {
return slots.length >> 1;
}
public boolean containsKey(Object key) {
final int n = slots.length;
for (int i = 0; i < n; i += 2) {
if (key.equals(slots[i])) {
return true;
}
}
return false;
}
public boolean containsValue(Object value) {
final int n = slots.length;
for (int i = 0; i < n; i += 2) {
final Object v = slots[i + 1];
if (value == null ? v == null : value.equals(v)) {
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
public Map.Entry<K, V> head() {
if (slots.length > 1) {
return new AbstractMap.SimpleImmutableEntry<K, V>((K) slots[0], (V) slots[1]);
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public K headKey() {
if (slots.length > 1) {
return (K) slots[0];
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public V headValue() {
if (slots.length > 1) {
return (V) slots[1];
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public Map.Entry<K, V> next(Object key) {
final int n = slots.length;
if (n > 1 && key == null) {
return new AbstractMap.SimpleImmutableEntry<K, V>((K) slots[0], (V) slots[1]);
}
for (int i = 0; i < n; i += 2) {
if (key.equals(slots[i]) && i + 3 < n) {
return new AbstractMap.SimpleImmutableEntry<K, V>((K) slots[i + 2], (V) slots[i + 3]);
}
}
return null;
}
@SuppressWarnings("unchecked")
public K nextKey(Object key) {
final int n = slots.length;
if (n > 1 && key == null) {
return (K) slots[0];
}
for (int i = 0; i < n; i += 2) {
if (key.equals(slots[i]) && i + 3 < n) {
return (K) slots[i + 2];
}
}
return null;
}
@SuppressWarnings("unchecked")
public V nextValue(Object key) {
final int n = slots.length;
if (n > 1 && key == null) {
return (V) slots[1];
}
for (int i = 0; i < n; i += 2) {
if (key.equals(slots[i]) && i + 3 < n) {
return (V) slots[i + 3];
}
}
return null;
}
@SuppressWarnings("unchecked")
public V get(Object key) {
final int n = slots.length;
for (int i = 0; i < n; i += 2) {
if (key.equals(slots[i])) {
return (V) slots[i + 1];
}
}
return null;
}
public ArrayMap<K, V> updated(K key, V value) {
final int n = slots.length;
for (int i = 0; i < n; i += 2) {
if (key.equals(slots[i])) {
final Object v = slots[i + 1];
if (value == null ? v == null : value.equals(v)) {
return this;
} else {
final Object[] newSlots = new Object[n];
System.arraycopy(slots, 0, newSlots, 0, n);
newSlots[i] = key;
newSlots[i + 1] = value;
return new ArrayMap<K, V>(newSlots);
}
}
}
final Object[] newSlots = new Object[n + 2];
System.arraycopy(slots, 0, newSlots, 0, n);
newSlots[n] = key;
newSlots[n + 1] = value;
return new ArrayMap<K, V>(newSlots);
}
public ArrayMap<K, V> removed(Object key) {
final int n = slots.length;
for (int i = 0; i < n; i += 1) {
if (key.equals(slots[i])) {
if (n == 2) {
return empty();
} else {
final Object[] newSlots = new Object[n - 2];
System.arraycopy(slots, 0, newSlots, 0, i);
System.arraycopy(slots, i + 2, newSlots, i, (n - 2) - i);
return new ArrayMap<K, V>(newSlots);
}
}
}
return this;
}
boolean isUnary() {
return slots.length == 2;
}
@SuppressWarnings("unchecked")
K unaryKey() {
return (K) slots[0];
}
@SuppressWarnings("unchecked")
V unaryValue() {
return (V) slots[1];
}
@SuppressWarnings("unchecked")
K keyAt(int index) {
return (K) slots[index << 1];
}
@SuppressWarnings("unchecked")
V valueAt(int index) {
return (V) slots[(index << 1) + 1];
}
public Iterator<Map.Entry<K, V>> iterator() {
return new ArrayMapIterator<K, V>(slots);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof ArrayMap<?, ?>) {
final ArrayMap<K, V> that = (ArrayMap<K, V>) other;
if (size() == that.size()) {
final Iterator<Map.Entry<K, V>> those = that.iterator();
while (those.hasNext()) {
final Map.Entry<K, V> entry = those.next();
final V value = get(entry.getKey());
final V v = entry.getValue();
if (value == null ? v != null : !value.equals(v)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(ArrayMap.class);
}
int a = 0;
int b = 0;
int c = 1;
final Iterator<Map.Entry<K, V>> these = iterator();
while (these.hasNext()) {
final Map.Entry<K, V> entry = these.next();
final int h = Murmur3.mix(Murmur3.hash(entry.getKey()), Murmur3.hash(entry.getValue()));
a ^= h;
b += h;
if (h != 0) {
c *= h;
}
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, a), b), c));
}
@Override
public void debug(Output<?> output) {
output = output.write("ArrayMap").write('.');
final Iterator<Map.Entry<K, V>> these = iterator();
if (these.hasNext()) {
Map.Entry<K, V> entry = these.next();
output = output.write("of").write('(')
.debug(entry.getKey()).write(", ").debug(entry.getValue());
while (these.hasNext()) {
entry = these.next();
output = output.write(')').write('.').write("put").write('(')
.debug(entry.getKey()).write(", ").debug(entry.getValue());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static ArrayMap<Object, Object> empty;
@SuppressWarnings("unchecked")
public static <K, V> ArrayMap<K, V> empty() {
if (empty == null) {
empty = new ArrayMap<Object, Object>(new Object[0]);
}
return (ArrayMap<K, V>) empty;
}
@SuppressWarnings("unchecked")
public static <K, V> ArrayMap<K, V> of(K key, V value) {
return new ArrayMap<K, V>(key, value);
}
}
final class ArrayMapIterator<K, V> implements Iterator<Map.Entry<K, V>> {
final Object[] slots;
int index;
ArrayMapIterator(Object[] slots) {
this.slots = slots;
}
@Override
public boolean hasNext() {
return index < slots.length;
}
@SuppressWarnings("unchecked")
@Override
public Map.Entry<K, V> next() {
if (index >= slots.length) {
throw new NoSuchElementException();
}
final K key = (K) slots[index];
final V value = (V) slots[index + 1];
index += 2;
return new AbstractMap.SimpleImmutableEntry<K, V>(key, value);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/ArraySet.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.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Murmur3;
final class ArraySet<T> implements Debug {
final Object[] slots;
ArraySet(Object[] slots) {
this.slots = slots;
}
ArraySet(T elem) {
slots = new Object[1];
slots[0] = elem;
}
ArraySet(T elem0, T elem1) {
slots = new Object[2];
slots[0] = elem0;
slots[1] = elem1;
}
public boolean isEmpty() {
return slots.length == 0;
}
public int size() {
return slots.length;
}
public boolean contains(Object elem) {
final int n = slots.length;
for (int i = 0; i < n; i += 1) {
if (elem.equals(slots[i])) {
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
public T head() {
if (slots.length > 0) {
return (T) slots[0];
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public T next(Object elem) {
final int n = slots.length;
if (n > 0 && elem == null) {
return (T) slots[0];
}
for (int i = 0; i < n; i += 1) {
if (elem.equals(slots[i]) && i + 1 < n) {
return (T) slots[i + 1];
}
}
return null;
}
public ArraySet<T> added(T elem) {
final int n = slots.length;
for (int i = 0; i < n; i += 1) {
if (elem.equals(slots[i])) {
return this;
}
}
final Object[] newSlots = new Object[n + 1];
System.arraycopy(slots, 0, newSlots, 0, n);
newSlots[n] = elem;
return new ArraySet<T>(newSlots);
}
public ArraySet<T> removed(T elem) {
final int n = slots.length;
for (int i = 0; i < n; i += 1) {
if (elem.equals(slots[i])) {
if (n == 1) {
return empty();
} else {
final Object[] newSlots = new Object[n - 1];
System.arraycopy(slots, 0, newSlots, 0, i);
System.arraycopy(slots, i + 1, newSlots, i, (n - 1) - i);
return new ArraySet<T>(newSlots);
}
}
}
return this;
}
boolean isUnary() {
return slots.length == 1;
}
@SuppressWarnings("unchecked")
T unaryElem() {
return (T) slots[0];
}
@SuppressWarnings("unchecked")
T elemAt(int index) {
return (T) slots[index];
}
public Iterator<T> iterator() {
return new ArraySetIterator<T>(slots);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof ArraySet<?>) {
final ArraySet<T> that = (ArraySet<T>) other;
if (size() == that.size()) {
final Iterator<T> those = that.iterator();
while (those.hasNext()) {
if (!contains(those.next())) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(ArraySet.class);
}
int a = 0;
int b = 0;
int c = 1;
final Iterator<T> these = iterator();
while (these.hasNext()) {
final int h = Murmur3.hash(these.next());
a ^= h;
b += h;
if (h != 0) {
c *= h;
}
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, a), b), c));
}
@Override
public void debug(Output<?> output) {
output = output.write("ArraySet").write('.');
final Iterator<T> these = iterator();
if (these.hasNext()) {
output = output.write("of").write('(').debug(these.next());
while (these.hasNext()) {
output = output.write(", ").debug(these.next());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static ArraySet<Object> empty;
@SuppressWarnings("unchecked")
public static <T> ArraySet<T> empty() {
if (empty == null) {
empty = new ArraySet<Object>(new Object[0]);
}
return (ArraySet<T>) empty;
}
@SuppressWarnings("unchecked")
public static <T> ArraySet<T> of(T... elems) {
final int n = elems.length;
final Object[] slots = new Object[n];
System.arraycopy(elems, 0, slots, 0, n);
return new ArraySet<T>(slots);
}
}
final class ArraySetIterator<T> implements Iterator<T> {
final Object[] slots;
int index;
ArraySetIterator(Object[] slots) {
this.slots = slots;
}
@Override
public boolean hasNext() {
return index < slots.length;
}
@SuppressWarnings("unchecked")
@Override
public T next() {
if (index >= slots.length) {
throw new NoSuchElementException();
}
final T elem = (T) slots[index];
index += 1;
return elem;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/BTree.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.collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Cursor;
import swim.util.OrderedMap;
import swim.util.OrderedMapCursor;
/**
* Immutable {@link OrderedMap} backed by a B-tree.
*/
public class BTree<K, V> extends BTreeContext<K, V> implements OrderedMap<K, V>, Debug {
final BTreePage<K, V, ?> root;
protected BTree(BTreePage<K, V, ?> root) {
this.root = root;
}
@Override
public boolean isEmpty() {
return this.root.isEmpty();
}
@Override
public int size() {
return this.root.size();
}
@Override
public boolean containsKey(Object key) {
return this.root.containsKey(key, this);
}
@Override
public boolean containsValue(Object value) {
return this.root.containsValue(value);
}
@Override
public int indexOf(Object key) {
return this.root.indexOf(key, this);
}
@Override
public V get(Object key) {
return this.root.get(key, this);
}
@Override
public Entry<K, V> getEntry(Object key) {
return this.root.getEntry(key, this);
}
@Override
public Entry<K, V> getIndex(int index) {
return this.root.getIndex(index);
}
@Override
public Entry<K, V> firstEntry() {
return this.root.firstEntry();
}
@Override
public K firstKey() {
final Entry<K, V> entry = this.root.firstEntry();
if (entry != null) {
return entry.getKey();
} else {
return null;
}
}
@Override
public V firstValue() {
final Entry<K, V> entry = this.root.firstEntry();
if (entry != null) {
return entry.getValue();
} else {
return null;
}
}
@Override
public Entry<K, V> lastEntry() {
return this.root.lastEntry();
}
@Override
public K lastKey() {
final Entry<K, V> entry = this.root.lastEntry();
if (entry != null) {
return entry.getKey();
} else {
return null;
}
}
@Override
public V lastValue() {
final Entry<K, V> entry = this.root.lastEntry();
if (entry != null) {
return entry.getValue();
} else {
return null;
}
}
@Override
public Entry<K, V> nextEntry(K key) {
return this.root.nextEntry(key, this);
}
@Override
public K nextKey(K key) {
final Entry<K, V> entry = this.root.nextEntry(key, this);
if (entry != null) {
return entry.getKey();
} else {
return null;
}
}
@Override
public V nextValue(K key) {
final Entry<K, V> entry = this.root.nextEntry(key, this);
if (entry != null) {
return entry.getValue();
} else {
return null;
}
}
@Override
public Entry<K, V> previousEntry(K key) {
return this.root.previousEntry(key, this);
}
@Override
public K previousKey(K key) {
final Entry<K, V> entry = this.root.previousEntry(key, this);
if (entry != null) {
return entry.getKey();
} else {
return null;
}
}
@Override
public V previousValue(K key) {
final Entry<K, V> entry = this.root.previousEntry(key, this);
if (entry != null) {
return entry.getValue();
} else {
return null;
}
}
@Override
public V put(K key, V newValue) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException();
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
public BTree<K, V> drop(int lower) {
if (lower > 0 && this.root.size() > 0) {
if (lower < this.root.size()) {
return copy(this.root.drop(lower, this).balanced(this));
} else {
return empty();
}
}
return this;
}
public BTree<K, V> take(int upper) {
if (upper < this.root.size() && this.root.size() > 0) {
if (upper > 0) {
return copy(this.root.take(upper, this).balanced(this));
} else {
return empty();
}
}
return this;
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
public BTree<K, V> updated(K key, V newValue) {
final BTreePage<K, V, ?> oldRoot = this.root;
BTreePage<K, V, ?> newRoot = oldRoot.updated(key, newValue, this);
if (oldRoot != newRoot) {
if (newRoot.size() > oldRoot.size()) {
newRoot = newRoot.balanced(this);
}
return copy(newRoot);
} else {
return this;
}
}
public BTree<K, V> removed(K key) {
final BTreePage<K, V, ?> oldRoot = this.root;
final BTreePage<K, V, ?> newRoot = oldRoot.removed(key, this).balanced(this);
if (oldRoot != newRoot) {
return copy(newRoot);
} else {
return this;
}
}
public BTree<K, V> cleared() {
return empty();
}
@Override
public OrderedMapCursor<K, V> iterator() {
return this.root.iterator();
}
public Cursor<K> keyIterator() {
return this.root.keyIterator();
}
public Cursor<V> valueIterator() {
return this.root.valueIterator();
}
public OrderedMapCursor<K, V> lastIterator() {
return this.root.lastIterator();
}
public Cursor<K> lastKeyIterator() {
return this.root.lastKeyIterator();
}
public Cursor<V> lastValueIterator() {
return this.root.lastValueIterator();
}
protected BTree<K, V> copy(BTreePage<K, V, ?> root) {
return new BTree<K, V>(root);
}
@Override
public Comparator<? super K> comparator() {
return null;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Map<?, ?>) {
final Map<K, V> that = (Map<K, V>) other;
if (size() == that.size()) {
final Iterator<Entry<K, V>> those = that.entrySet().iterator();
while (those.hasNext()) {
final Entry<K, V> entry = those.next();
final V value = get(entry.getKey());
final V v = entry.getValue();
if (value == null ? v != null : !value.equals(v)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
int code = 0;
final Cursor<Entry<K, V>> these = iterator();
while (these.hasNext()) {
code += these.next().hashCode();
}
return code;
}
@Override
public void debug(Output<?> output) {
output = output.write("BTree").write('.');
final Cursor<Entry<K, V>> these = iterator();
if (these.hasNext()) {
Entry<K, V> entry = these.next();
output = output.write("of").write('(')
.debug(entry.getKey()).write(", ").debug(entry.getValue());
while (these.hasNext()) {
entry = these.next();
output = output.write(')').write('.').write("updated").write('(')
.debug(entry.getKey()).write(", ").debug(entry.getValue());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static BTree<Object, Object> empty;
@SuppressWarnings("unchecked")
public static <K, V> BTree<K, V> empty() {
if (empty == null) {
empty = new BTree<Object, Object>(BTreePage.empty());
}
return (BTree<K, V>) (BTree<?, ?>) empty;
}
public static <K, V> BTree<K, V> of(K key, V value) {
BTree<K, V> tree = empty();
tree = tree.updated(key, value);
return tree;
}
public static <K, V> BTree<K, V> from(Map<? extends K, ? extends V> map) {
BTree<K, V> tree = empty();
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
tree = tree.updated(entry.getKey(), entry.getValue());
}
return tree;
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/BTreeContext.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.collections;
public abstract class BTreeContext<K, V> {
@SuppressWarnings("unchecked")
protected int compareKey(Object x, Object y) {
return ((Comparable<Object>) x).compareTo(y);
}
protected int pageSplitSize() {
return 32;
}
protected boolean pageShouldSplit(BTreePage<K, V, ?> page) {
return page.arity() > pageSplitSize();
}
protected boolean pageShouldMerge(BTreePage<K, V, ?> page) {
return page.arity() < pageSplitSize() >>> 1;
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/BTreeLeaf.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.collections;
import java.util.AbstractMap;
import java.util.Map;
import swim.util.CombinerFunction;
import swim.util.OrderedMapCursor;
class BTreeLeaf<K, V, U> extends BTreePage<K, V, U> {
final Map.Entry<K, V>[] slots;
final U fold;
BTreeLeaf(Map.Entry<K, V>[] slots, U fold) {
this.slots = slots;
this.fold = fold;
}
@Override
public final boolean isEmpty() {
return this.slots.length == 0;
}
@Override
public final int size() {
return this.slots.length;
}
@Override
public final int arity() {
return this.slots.length;
}
@Override
public final U fold() {
return this.fold;
}
@Override
public final K minKey() {
return this.slots[0].getKey();
}
@Override
public final K maxKey() {
return this.slots[this.slots.length - 1].getKey();
}
@Override
public final boolean containsKey(Object key, BTreeContext<K, V> tree) {
return lookup(key, tree) >= 0;
}
@Override
public final boolean containsValue(Object value) {
final Map.Entry<K, V>[] slots = this.slots;
for (int i = 0, n = slots.length; i < n; i += 1) {
if (value.equals(slots[i].getValue())) {
return true;
}
}
return false;
}
@Override
public final int indexOf(Object key, BTreeContext<K, V> tree) {
return lookup(key, tree);
}
@Override
public final V get(Object key, BTreeContext<K, V> tree) {
final int x = lookup(key, tree);
if (x >= 0) {
return this.slots[x].getValue();
} else {
return null;
}
}
@Override
public final Map.Entry<K, V> getEntry(Object key, BTreeContext<K, V> tree) {
final int x = lookup(key, tree);
if (x >= 0) {
return this.slots[x];
} else {
return null;
}
}
@Override
public final Map.Entry<K, V> getIndex(int index) {
return this.slots[index];
}
@Override
public final Map.Entry<K, V> firstEntry() {
if (this.slots.length != 0) {
return this.slots[0];
} else {
return null;
}
}
@Override
public final Map.Entry<K, V> lastEntry() {
if (this.slots.length != 0) {
return this.slots[this.slots.length - 1];
} else {
return null;
}
}
@Override
public final Map.Entry<K, V> nextEntry(K key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
if (0 <= x && x < this.slots.length) {
return this.slots[x];
} else {
return null;
}
}
@Override
public final Map.Entry<K, V> previousEntry(K key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x -= 1;
} else {
x = -(x + 2);
}
if (0 <= x && x < this.slots.length) {
return this.slots[x];
} else {
return null;
}
}
@Override
public final BTreeLeaf<K, V, U> updated(K key, V newValue, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
return updatedSlot(x, key, newValue);
} else {
x = -(x + 1);
return insertedSlot(x, key, newValue);
}
}
@SuppressWarnings("unchecked")
private BTreeLeaf<K, V, U> updatedSlot(int x, K key, V newValue) {
final Map.Entry<K, V>[] oldSlots = this.slots;
if (newValue != oldSlots[x].getValue()) {
final Map.Entry<K, V>[] newSlots = (Map.Entry<K, V>[]) new Map.Entry<?, ?>[oldSlots.length];
System.arraycopy(oldSlots, 0, newSlots, 0, oldSlots.length);
newSlots[x] = new AbstractMap.SimpleImmutableEntry<K, V>(key, newValue);
return newLeaf(newSlots, null);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
private BTreeLeaf<K, V, U> insertedSlot(int x, K key, V newValue) {
final Map.Entry<K, V>[] oldSlots = this.slots;
final int n = oldSlots.length + 1;
final Map.Entry<K, V>[] newSlots = (Map.Entry<K, V>[]) new Map.Entry<?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, x);
newSlots[x] = new AbstractMap.SimpleImmutableEntry<K, V>(key, newValue);
System.arraycopy(oldSlots, x, newSlots, x + 1, n - (x + 1));
return newLeaf(newSlots, null);
}
@Override
public final BTreeLeaf<K, V, U> removed(Object key, BTreeContext<K, V> tree) {
final int x = lookup(key, tree);
if (x >= 0) {
if (this.slots.length > 1) {
return removedSlot(x);
} else {
return BTreeLeaf.empty();
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
private BTreeLeaf<K, V, U> removedSlot(int x) {
final Map.Entry<K, V>[] oldSlots = this.slots;
final int n = oldSlots.length - 1;
final Map.Entry<K, V>[] newSlots = (Map.Entry<K, V>[]) new Map.Entry<?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, x);
System.arraycopy(oldSlots, x + 1, newSlots, x, n - x);
return newLeaf(newSlots, null);
}
@SuppressWarnings("unchecked")
@Override
public final BTreeLeaf<K, V, U> drop(int lower, BTreeContext<K, V> tree) {
if (lower > 0) {
final Map.Entry<K, V>[] oldSlots = this.slots;
final int k = oldSlots.length;
if (lower < k) {
final int n = k - lower;
final Map.Entry<K, V>[] newSlots = (Map.Entry<K, V>[]) new Map.Entry<?, ?>[n];
System.arraycopy(oldSlots, lower, newSlots, 0, n);
return newLeaf(newSlots, null);
} else {
return BTreeLeaf.empty();
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public final BTreeLeaf<K, V, U> take(int upper, BTreeContext<K, V> tree) {
final Map.Entry<K, V>[] oldSlots = this.slots;
if (upper < oldSlots.length) {
if (upper > 0) {
final Map.Entry<K, V>[] newSlots = (Map.Entry<K, V>[]) new Map.Entry<?, ?>[upper];
System.arraycopy(oldSlots, 0, newSlots, 0, upper);
return newLeaf(newSlots, null);
} else {
return BTreeLeaf.empty();
}
} else {
return this;
}
}
@Override
public final BTreePage<K, V, U> balanced(BTreeContext<K, V> tree) {
final int n = this.slots.length;
if (n > 1 && tree.pageShouldSplit(this)) {
final int x = n >>> 1;
return split(x);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public final BTreeNode<K, V, U> split(int x) {
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[2];
final BTreeLeaf<K, V, U> newLeftPage = splitLeft(x);
final BTreeLeaf<K, V, U> newRightPage = splitRight(x);
newPages[0] = newLeftPage;
newPages[1] = newRightPage;
final K[] newKnots = (K[]) new Object[1];
newKnots[0] = newRightPage.minKey();
return newNode(newPages, newKnots, null, this.slots.length);
}
@SuppressWarnings("unchecked")
@Override
public final BTreeLeaf<K, V, U> splitLeft(int x) {
final Map.Entry<K, V>[] oldSlots = this.slots;
final Map.Entry<K, V>[] newSlots = (Map.Entry<K, V>[]) new Map.Entry<?, ?>[x];
System.arraycopy(oldSlots, 0, newSlots, 0, x);
return newLeaf(newSlots, null);
}
@SuppressWarnings("unchecked")
@Override
public final BTreeLeaf<K, V, U> splitRight(int x) {
final Map.Entry<K, V>[] oldSlots = this.slots;
final int y = oldSlots.length - x;
final Map.Entry<K, V>[] newSlots = (Map.Entry<K, V>[]) new Map.Entry<?, ?>[y];
System.arraycopy(oldSlots, x, newSlots, 0, y);
return newLeaf(newSlots, null);
}
@Override
public final BTreeLeaf<K, V, U> reduced(U identity, CombinerFunction<? super V, U> accumulator,
CombinerFunction<U, U> combiner) {
if (this.fold == null) {
final Map.Entry<K, V>[] slots = this.slots;
U fold = identity;
for (int i = 0, n = slots.length; i < n; i += 1) {
fold = accumulator.combine(fold, slots[i].getValue());
}
return newLeaf(slots, fold);
} else {
return this;
}
}
@Override
public final OrderedMapCursor<K, V> iterator() {
return new BTreeLeafCursor<K, V>(this.slots, 0, this.slots.length);
}
@Override
public final OrderedMapCursor<K, V> lastIterator() {
return new BTreeLeafCursor<K, V>(this.slots, this.slots.length, this.slots.length);
}
protected final int lookup(Object key, BTreeContext<K, V> tree) {
int lo = 0;
int hi = this.slots.length - 1;
while (lo <= hi) {
final int mid = (lo + hi) >>> 1;
final int order = tree.compareKey(key, this.slots[mid].getKey());
if (order > 0) {
lo = mid + 1;
} else if (order < 0) {
hi = mid - 1;
} else {
return mid;
}
}
return -(lo + 1);
}
protected BTreeLeaf<K, V, U> newLeaf(Map.Entry<K, V>[] slots, U fold) {
return new BTreeLeaf<K, V, U>(slots, fold);
}
protected BTreeNode<K, V, U> newNode(BTreePage<K, V, U>[] pages, K[] knots, U fold, int size) {
return new BTreeNode<K, V, U>(pages, knots, fold, size);
}
private static BTreeLeaf<Object, Object, Object> empty;
@SuppressWarnings("unchecked")
public static <K, V, U> BTreeLeaf<K, V, U> empty() {
if (empty == null) {
empty = new BTreeLeaf<Object, Object, Object>((Map.Entry<Object, Object>[]) new Map.Entry<?, ?>[0], null);
}
return (BTreeLeaf<K, V, U>) empty;
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/BTreeLeafCursor.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.collections;
import java.util.Map;
import java.util.NoSuchElementException;
import swim.util.OrderedMapCursor;
final class BTreeLeafCursor<K, V> implements OrderedMapCursor<K, V> {
final Map.Entry<K, V>[] array;
int index;
int limit;
BTreeLeafCursor(Map.Entry<K, V>[] array, int index, int limit) {
this.array = array;
this.index = index;
this.limit = limit;
}
@Override
public boolean isEmpty() {
return this.index >= this.limit;
}
@Override
public Map.Entry<K, V> head() {
if (this.index < this.limit) {
return this.array[this.index];
} else {
throw new NoSuchElementException();
}
}
@Override
public void step() {
if (this.index < this.limit) {
this.index = 1;
} else {
throw new UnsupportedOperationException();
}
}
@Override
public void skip(long count) {
this.index = (int) Math.max(0L, Math.min((long) this.index + count, (long) this.limit));
}
@Override
public boolean hasNext() {
return this.index < this.limit;
}
@Override
public long nextIndexLong() {
return (long) this.index;
}
@Override
public int nextIndex() {
return this.index;
}
@Override
public K nextKey() {
return this.array[this.index].getKey();
}
@Override
public Map.Entry<K, V> next() {
final int index = this.index;
if (index < this.limit) {
this.index = index + 1;
return this.array[index];
} else {
this.index = this.limit;
throw new NoSuchElementException();
}
}
@Override
public boolean hasPrevious() {
return this.index > 0;
}
@Override
public long previousIndexLong() {
return (long) (this.index - 1);
}
@Override
public int previousIndex() {
return this.index - 1;
}
@Override
public K previousKey() {
return this.array[this.index - 1].getKey();
}
@Override
public Map.Entry<K, V> previous() {
final int index = this.index - 1;
if (index >= 0) {
this.index = index;
return this.array[index];
} else {
this.index = 0;
throw new NoSuchElementException();
}
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/BTreeMap.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.collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.CombinerFunction;
import swim.util.Cursor;
import swim.util.OrderedMapCursor;
import swim.util.ReducedMap;
/**
* Mutable, thread-safe {@link Map} backed by a B-tree.
*/
public class BTreeMap<K, V, U> extends BTreeContext<K, V> implements ReducedMap<K, V, U>, Cloneable, Debug {
volatile BTreePage<K, V, U> root;
protected BTreeMap(BTreePage<K, V, U> root) {
this.root = root;
}
public BTreeMap() {
this(BTreePage.<K, V, U>empty());
}
@Override
public boolean isEmpty() {
return this.root.isEmpty();
}
@Override
public int size() {
return this.root.size();
}
@Override
public boolean containsKey(Object key) {
return this.root.containsKey(key, this);
}
@Override
public boolean containsValue(Object value) {
return this.root.containsValue(value);
}
@Override
public int indexOf(Object key) {
return this.root.indexOf(key, this);
}
@Override
public V get(Object key) {
return this.root.get(key, this);
}
@Override
public Entry<K, V> getEntry(Object key) {
return this.root.getEntry(key, this);
}
@Override
public Entry<K, V> getIndex(int index) {
return this.root.getIndex(index);
}
@Override
public Entry<K, V> firstEntry() {
return this.root.firstEntry();
}
@Override
public K firstKey() {
final Entry<K, V> entry = this.root.firstEntry();
if (entry != null) {
return entry.getKey();
} else {
return null;
}
}
@Override
public V firstValue() {
final Entry<K, V> entry = this.root.firstEntry();
if (entry != null) {
return entry.getValue();
} else {
return null;
}
}
@Override
public Entry<K, V> lastEntry() {
return this.root.lastEntry();
}
@Override
public K lastKey() {
final Entry<K, V> entry = this.root.lastEntry();
if (entry != null) {
return entry.getKey();
} else {
return null;
}
}
@Override
public V lastValue() {
final Entry<K, V> entry = this.root.lastEntry();
if (entry != null) {
return entry.getValue();
} else {
return null;
}
}
@Override
public Entry<K, V> nextEntry(K key) {
return this.root.nextEntry(key, this);
}
@Override
public K nextKey(K key) {
final Entry<K, V> entry = this.root.nextEntry(key, this);
if (entry != null) {
return entry.getKey();
} else {
return null;
}
}
@Override
public V nextValue(K key) {
final Entry<K, V> entry = this.root.nextEntry(key, this);
if (entry != null) {
return entry.getValue();
} else {
return null;
}
}
@Override
public Entry<K, V> previousEntry(K key) {
return this.root.previousEntry(key, this);
}
@Override
public K previousKey(K key) {
final Entry<K, V> entry = this.root.previousEntry(key, this);
if (entry != null) {
return entry.getKey();
} else {
return null;
}
}
@Override
public V previousValue(K key) {
final Entry<K, V> entry = this.root.previousEntry(key, this);
if (entry != null) {
return entry.getValue();
} else {
return null;
}
}
@Override
public V put(K key, V newValue) {
BTreePage<K, V, U> oldRoot;
do {
oldRoot = this.root;
BTreePage<K, V, U> newRoot = oldRoot.updated(key, newValue, this);
if (oldRoot != newRoot) {
if (newRoot.size() > oldRoot.size()) {
newRoot = newRoot.balanced(this);
}
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
break;
}
} else {
break;
}
} while (true);
return oldRoot.get(key, this);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public V remove(Object key) {
do {
final BTreePage<K, V, U> oldRoot = this.root;
final BTreePage<K, V, U> newRoot = oldRoot.removed(key, this).balanced(this);
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return oldRoot.get(key, this);
}
} else {
return null;
}
} while (true);
}
public BTreeMap<K, V, U> drop(int lower) {
do {
final BTreePage<K, V, U> oldRoot = this.root;
if (lower > 0 && oldRoot.size() > 0) {
final BTreePage<K, V, U> newRoot;
if (lower < oldRoot.size()) {
newRoot = oldRoot.drop(lower, this).balanced(this);
} else {
newRoot = BTreePage.empty();
}
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
break;
}
} else {
break;
}
} while (true);
return this;
}
public BTreeMap<K, V, U> take(int upper) {
do {
final BTreePage<K, V, U> oldRoot = this.root;
if (upper < oldRoot.size() && oldRoot.size() > 0) {
final BTreePage<K, V, U> newRoot;
if (upper > 0) {
newRoot = oldRoot.take(upper, this).balanced(this);
} else {
newRoot = BTreePage.<K, V, U>empty();
}
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
break;
}
} else {
break;
}
} while (true);
return this;
}
@Override
public void clear() {
do {
final BTreePage<K, V, U> oldRoot = this.root;
final BTreePage<K, V, U> newRoot = BTreePage.empty();
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
break;
}
} else {
break;
}
} while (true);
}
public BTreeMap<K, V, U> updated(K key, V newValue) {
final BTreePage<K, V, U> oldRoot = this.root;
BTreePage<K, V, U> newRoot = oldRoot.updated(key, newValue, this);
if (newRoot.size() > oldRoot.size()) {
newRoot = newRoot.balanced(this);
}
return copy(newRoot);
}
public BTreeMap<K, V, U> removed(K key) {
return copy(this.root.removed(key, this).balanced(this));
}
public BTreeMap<K, V, U> cleared() {
return copy(BTreePage.empty());
}
@Override
public U reduced(U identity, CombinerFunction<? super V, U> accumulator, CombinerFunction<U, U> combiner) {
BTreePage<K, V, U> newRoot;
do {
final BTreePage<K, V, U> oldRoot = this.root;
newRoot = oldRoot.reduced(identity, accumulator, combiner);
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
break;
}
} else {
break;
}
} while (true);
return newRoot.fold();
}
/**
* An immutable copy of this {@code BTreeMap}'s data.
*/
public BTree<K, V> snapshot() {
return new BTree<K, V>(this.root);
}
@Override
public OrderedMapCursor<K, V> iterator() {
return this.root.iterator();
}
public Cursor<K> keyIterator() {
return this.root.keyIterator();
}
public Cursor<V> valueIterator() {
return this.root.valueIterator();
}
public OrderedMapCursor<K, V> lastIterator() {
return this.root.lastIterator();
}
public Cursor<K> lastKeyIterator() {
return this.root.lastKeyIterator();
}
public Cursor<V> lastValueIterator() {
return this.root.lastValueIterator();
}
@Override
public BTreeMap<K, V, U> clone() {
return copy(this.root);
}
protected BTreeMap<K, V, U> copy(BTreePage<K, V, U> root) {
return new BTreeMap<K, V, U>(root);
}
@Override
public Comparator<? super K> comparator() {
return null;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Map<?, ?>) {
final Map<K, V> that = (Map<K, V>) other;
if (size() == that.size()) {
final Iterator<Entry<K, V>> those = that.entrySet().iterator();
while (those.hasNext()) {
final Entry<K, V> entry = those.next();
final V value = get(entry.getKey());
final V v = entry.getValue();
if (value == null ? v != null : !value.equals(v)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
int code = 0;
final Cursor<Entry<K, V>> these = iterator();
while (these.hasNext()) {
code += these.next().hashCode();
}
return code;
}
@Override
public void debug(Output<?> output) {
output = output.write("BTreeMap").write('.');
final Cursor<Entry<K, V>> these = iterator();
if (these.hasNext()) {
Entry<K, V> entry = these.next();
output = output.write("of").write('(')
.debug(entry.getKey()).write(", ").debug(entry.getValue());
while (these.hasNext()) {
entry = these.next();
output = output.write(')').write('.').write("updated").write('(')
.debug(entry.getKey()).write(", ").debug(entry.getValue());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
public static <K, V, U> BTreeMap<K, V, U> empty() {
return new BTreeMap<K, V, U>();
}
public static <K, V, U> BTreeMap<K, V, U> of(K key, V value) {
final BTreeMap<K, V, U> tree = new BTreeMap<K, V, U>();
tree.put(key, value);
return tree;
}
public static <K, V, U> BTreeMap<K, V, U> from(Map<? extends K, ? extends V> map) {
final BTreeMap<K, V, U> tree = new BTreeMap<K, V, U>();
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
tree.put(entry.getKey(), entry.getValue());
}
return tree;
}
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<BTreeMap, BTreePage> ROOT =
AtomicReferenceFieldUpdater.newUpdater(BTreeMap.class, BTreePage.class, "root");
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/BTreeNode.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.collections;
import java.util.Map;
import swim.util.CombinerFunction;
import swim.util.OrderedMapCursor;
class BTreeNode<K, V, U> extends BTreePage<K, V, U> {
final BTreePage<K, V, U>[] pages;
final K[] knots;
final U fold;
final int size;
BTreeNode(BTreePage<K, V, U>[] pages, K[] knots, U fold, int size) {
this.pages = pages;
this.knots = knots;
this.fold = fold;
this.size = size;
}
@Override
public final boolean isEmpty() {
return this.size == 0;
}
@Override
public final int size() {
return this.size;
}
@Override
public final int arity() {
return this.pages.length;
}
@Override
public final U fold() {
return this.fold;
}
@Override
public final K minKey() {
return this.pages[0].minKey();
}
@Override
public final K maxKey() {
return this.pages[this.pages.length - 1].maxKey();
}
@Override
public final boolean containsKey(Object key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x > 0) {
x += 1;
} else if (x < 0) {
x = -(x + 1);
} else {
return true;
}
return this.pages[x].containsKey(key, tree);
}
@Override
public final boolean containsValue(Object value) {
final BTreePage<K, V, U>[] pages = this.pages;
for (int i = 0, n = pages.length; i < n; i += 1) {
if (pages[i].containsValue(value)) {
return true;
}
}
return false;
}
@Override
public final int indexOf(Object key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
int count = 0;
for (int i = 0; i < x; i += 1) {
count += this.pages[x].size();
}
final int index = this.pages[x].indexOf(key, tree);
if (index >= 0) {
return count + index;
} else {
return index - count;
}
}
@Override
public final V get(Object key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
return this.pages[x].get(key, tree);
}
@Override
public final Map.Entry<K, V> getEntry(Object key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
return this.pages[x].getEntry(key, tree);
}
@Override
public final Map.Entry<K, V> getIndex(int index) {
final BTreePage<K, V, U>[] pages = this.pages;
for (int i = 0, n = pages.length; i < n; i += 1) {
final BTreePage<K, V, U> page = pages[i];
if (index < page.size()) {
return page.getIndex(index);
} else {
index -= page.size();
}
}
return null;
}
@Override
public final Map.Entry<K, V> firstEntry() {
final BTreePage<K, V, U>[] pages = this.pages;
if (pages.length != 0) {
return pages[0].firstEntry();
} else {
return null;
}
}
@Override
public final Map.Entry<K, V> lastEntry() {
final BTreePage<K, V, U>[] pages = this.pages;
if (pages.length != 0) {
return pages[pages.length - 1].lastEntry();
} else {
return null;
}
}
@Override
public final Map.Entry<K, V> nextEntry(K key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final BTreePage<K, V, U>[] pages = this.pages;
Map.Entry<K, V> entry = pages[x].nextEntry(key, tree);
if (entry == null && x + 1 < pages.length) {
entry = pages[x + 1].nextEntry(key, tree);
}
return entry;
}
@Override
public final Map.Entry<K, V> previousEntry(K key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final BTreePage<K, V, U>[] pages = this.pages;
Map.Entry<K, V> entry = pages[x].previousEntry(key, tree);
if (entry == null && x > 0) {
entry = pages[x - 1].previousEntry(key, tree);
}
return entry;
}
@Override
public final BTreeNode<K, V, U> updated(K key, V newValue, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final BTreePage<K, V, U> oldPage = this.pages[x];
final BTreePage<K, V, U> newPage = oldPage.updated(key, newValue, tree);
if (oldPage != newPage) {
if (oldPage.size() != newPage.size() && tree.pageShouldSplit(newPage)) {
return updatedPageSplit(x, newPage, oldPage);
} else {
return updatedPage(x, newPage, oldPage);
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
private BTreeNode<K, V, U> updatedPage(int x, BTreePage<K, V, U> newPage, BTreePage<K, V, U> oldPage) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final int n = oldPages.length;
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, 0, newPages, 0, n);
newPages[x] = newPage;
final K[] oldKnots = this.knots;
final K[] newKnots;
if (n - 1 > 0) {
newKnots = (K[]) new Object[n - 1];
System.arraycopy(oldKnots, 0, newKnots, 0, n - 1);
if (x > 0) {
newKnots[x - 1] = newPage.minKey();
}
} else {
newKnots = (K[]) new Object[0];
}
final int newSize = this.size - oldPage.size() + newPage.size();
return newNode(newPages, newKnots, null, newSize);
}
@SuppressWarnings("unchecked")
private BTreeNode<K, V, U> updatedPageSplit(int x, BTreePage<K, V, U> newPage, BTreePage<K, V, U> oldPage) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final int n = oldPages.length + 1;
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, 0, newPages, 0, x);
final int y = newPage.arity() >>> 1;
final BTreePage<K, V, U> newLeftPage = newPage.splitLeft(y);
final BTreePage<K, V, U> newRightPage = newPage.splitRight(y);
newPages[x] = newLeftPage;
newPages[x + 1] = newRightPage;
System.arraycopy(oldPages, x + 1, newPages, x + 2, n - (x + 2));
final K[] oldKnots = this.knots;
final K[] newKnots = (K[]) new Object[n - 1];
if (x > 0) {
System.arraycopy(oldKnots, 0, newKnots, 0, x - 1);
newKnots[x - 1] = newLeftPage.minKey();
newKnots[x] = newRightPage.minKey();
System.arraycopy(oldKnots, x, newKnots, x + 1, n - (x + 2));
} else {
newKnots[0] = newRightPage.minKey();
System.arraycopy(oldKnots, 0, newKnots, 1, n - 2);
}
final int newSize = this.size - oldPage.size() + newPage.size();
return newNode(newPages, newKnots, null, newSize);
}
@SuppressWarnings("unchecked")
private BTreeNode<K, V, U> updatedPageMerge(int x, BTreeNode<K, V, U> newPage, BTreePage<K, V, U> oldPage) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final BTreePage<K, V, U>[] midPages = newPage.pages;
final int k = midPages.length;
final int n = oldPages.length + (k - 1);
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, 0, newPages, 0, x);
System.arraycopy(midPages, 0, newPages, x, k);
System.arraycopy(oldPages, x + 1, newPages, x + k, n - (x + k));
final K[] oldKnots = this.knots;
final K[] midKnots = newPage.knots;
final K[] newKnots = (K[]) new Object[n - 1];
if (x > 0) {
System.arraycopy(oldKnots, 0, newKnots, 0, x - 1);
newKnots[x - 1] = midPages[0].minKey();
System.arraycopy(midKnots, 0, newKnots, x, k - 1);
System.arraycopy(oldKnots, x, newKnots, x + (k - 1), n - (x + k));
} else {
System.arraycopy(midKnots, 0, newKnots, 0, k - 1);
newKnots[midKnots.length] = oldPages[1].minKey();
System.arraycopy(oldKnots, 1, newKnots, k, n - k - 1);
}
final int newSize = this.size - oldPage.size() + newPage.size();
return newNode(newPages, newKnots, null, newSize);
}
@Override
public final BTreePage<K, V, U> removed(Object key, BTreeContext<K, V> tree) {
int x = lookup(key, tree);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final BTreePage<K, V, U> oldPage = this.pages[x];
final BTreePage<K, V, U> newPage = oldPage.removed(key, tree);
if (oldPage != newPage) {
return replacedPage(x, newPage, oldPage, tree);
} else {
return this;
}
}
private BTreePage<K, V, U> replacedPage(int x, BTreePage<K, V, U> newPage,
BTreePage<K, V, U> oldPage, BTreeContext<K, V> tree) {
if (!newPage.isEmpty()) {
if (newPage instanceof BTreeNode<?, ?, ?> && tree.pageShouldMerge(newPage)) {
return updatedPageMerge(x, (BTreeNode<K, V, U>) newPage, oldPage);
} else {
return updatedPage(x, newPage, oldPage);
}
} else if (this.pages.length > 2) {
return removedPage(x, newPage, oldPage);
} else if (this.pages.length > 1) {
if (x == 0) {
return this.pages[1];
} else {
return this.pages[0];
}
} else {
return BTreeLeaf.empty();
}
}
@SuppressWarnings("unchecked")
private BTreeNode<K, V, U> removedPage(int x, BTreePage<K, V, U> newPage, BTreePage<K, V, U> oldPage) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final int n = oldPages.length - 1;
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, 0, newPages, 0, x);
System.arraycopy(oldPages, x + 1, newPages, x, n - x);
final K[] oldKnots = this.knots;
final K[] newKnots = (K[]) new Object[n - 1];
if (x > 0) {
System.arraycopy(oldKnots, 0, newKnots, 0, x - 1);
System.arraycopy(oldKnots, x, newKnots, x - 1, n - x);
} else {
System.arraycopy(oldKnots, 1, newKnots, 0, n - 1);
}
final int newSize = this.size - oldPage.size();
return newNode(newPages, newKnots, null, newSize);
}
@SuppressWarnings("unchecked")
@Override
public final BTreePage<K, V, U> drop(int lower, BTreeContext<K, V> tree) {
if (lower > 0) {
int newSize = this.size;
if (lower < newSize) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final int k = oldPages.length;
int x = 0;
while (x < k) {
final int childSize = oldPages[x].size();
if (childSize <= lower) {
newSize -= childSize;
lower -= childSize;
x += 1;
} else {
break;
}
}
final int n = k - x;
if (n > 1) {
final BTreeNode<K, V, U> newNode;
if (x > 0) {
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, x, newPages, 0, n);
final K[] newKnots = (K[]) new Object[n - 1];
System.arraycopy(this.knots, x, newKnots, 0, n - 1);
for (int i = 0; i < newKnots.length; i += 1) {
newKnots[i] = this.knots[i + x];
}
newNode = newNode(newPages, newKnots, null, newSize);
} else {
newNode = this;
}
if (lower > 0) {
final BTreePage<K, V, U> oldPage = oldPages[x];
final BTreePage<K, V, U> newPage = oldPage.drop(lower, tree);
return newNode.replacedPage(0, newPage, oldPage, tree);
} else {
return newNode;
}
} else {
return oldPages[x].drop(lower, tree);
}
} else {
return BTreeLeaf.empty();
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public final BTreePage<K, V, U> take(int upper, BTreeContext<K, V> tree) {
if (upper < this.size) {
if (upper > 0) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final int k = oldPages.length;
int x = 0;
int newSize = 0;
while (x < k && upper > 0) {
final int childSize = oldPages[x].size();
newSize += childSize;
x += 1;
if (childSize <= upper) {
upper -= childSize;
} else {
break;
}
}
final int n = upper == 0 ? x : x + 1;
if (n > 1) {
final BTreeNode<K, V, U> newNode;
if (x < k) {
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[n];
System.arraycopy(oldPages, 0, newPages, 0, n);
final K[] newKnots = (K[]) new Object[n - 1];
System.arraycopy(this.knots, 0, newKnots, 0, n - 1);
newNode = newNode(newPages, newKnots, null, newSize);
} else {
newNode = this;
}
if (upper > 0) {
final BTreePage<K, V, U> oldPage = oldPages[x - 1];
final BTreePage<K, V, U> newPage = oldPage.take(upper, tree);
return newNode.replacedPage(x - 1, newPage, oldPage, tree);
} else {
return newNode;
}
} else if (upper > 0) {
return oldPages[0].take(upper, tree);
} else {
return oldPages[0];
}
} else {
return BTreeLeaf.empty();
}
} else {
return this;
}
}
@Override
public final BTreeNode<K, V, U> balanced(BTreeContext<K, V> tree) {
if (this.pages.length > 1 && tree.pageShouldSplit(this)) {
final int x = this.knots.length >>> 1;
return split(x);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public final BTreeNode<K, V, U> split(int x) {
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[2];
final BTreeNode<K, V, U> newLeftPage = splitLeft(x);
final BTreeNode<K, V, U> newRightPage = splitRight(x);
newPages[0] = newLeftPage;
newPages[1] = newRightPage;
final K[] newKnots = (K[]) new Object[1];
newKnots[0] = newRightPage.minKey();
return newNode(newPages, newKnots, null, this.size);
}
@SuppressWarnings("unchecked")
@Override
public final BTreeNode<K, V, U> splitLeft(int x) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[x + 1];
System.arraycopy(oldPages, 0, newPages, 0, x + 1);
final K[] oldKnots = this.knots;
final K[] newKnots = (K[]) new Object[x];
System.arraycopy(oldKnots, 0, newKnots, 0, x);
int newSize = 0;
for (int i = 0; i <= x; i += 1) {
newSize += newPages[i].size();
}
return newNode(newPages, newKnots, null, newSize);
}
@SuppressWarnings("unchecked")
@Override
public final BTreeNode<K, V, U> splitRight(int x) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final int y = oldPages.length - (x + 1);
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[y];
System.arraycopy(oldPages, x + 1, newPages, 0, y);
final K[] oldKnots = this.knots;
final K[] newKnots = (K[]) new Object[y - 1];
System.arraycopy(oldKnots, x + 1, newKnots, 0, y - 1);
int newSize = 0;
for (int i = 0; i < y; i += 1) {
newSize += newPages[i].size();
}
return newNode(newPages, newKnots, null, newSize);
}
@SuppressWarnings("unchecked")
@Override
public final BTreeNode<K, V, U> reduced(U identity, CombinerFunction<? super V, U> accumulator,
CombinerFunction<U, U> combiner) {
if (this.fold == null) {
final BTreePage<K, V, U>[] oldPages = this.pages;
final int n = oldPages.length;
final BTreePage<K, V, U>[] newPages = (BTreePage<K, V, U>[]) new BTreePage<?, ?, ?>[n];
for (int i = 0; i < n; i += 1) {
newPages[i] = oldPages[i].reduced(identity, accumulator, combiner);
}
// assert n > 0;
U fold = newPages[0].fold();
for (int i = 1; i < n; i += 1) {
fold = combiner.combine(fold, newPages[i].fold());
}
return newNode(newPages, this.knots, fold, this.size);
} else {
return this;
}
}
@Override
public final OrderedMapCursor<K, V> iterator() {
return new BTreeNodeCursor<K, V, U>(this.pages);
}
@Override
public final OrderedMapCursor<K, V> lastIterator() {
return new BTreeNodeCursor<K, V, U>(this.pages, this.size, this.pages.length);
}
protected final int lookup(Object key, BTreeContext<K, V> tree) {
int lo = 0;
int hi = this.knots.length - 1;
while (lo <= hi) {
final int mid = (lo + hi) >>> 1;
final int order = tree.compareKey(key, this.knots[mid]);
if (order > 0) {
lo = mid + 1;
} else if (order < 0) {
hi = mid - 1;
} else {
return mid;
}
}
return -(lo + 1);
}
protected BTreeNode<K, V, U> newNode(BTreePage<K, V, U>[] pages, K[] knots, U fold, int size) {
return new BTreeNode<K, V, U>(pages, knots, fold, size);
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/BTreeNodeCursor.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.collections;
import java.util.Map;
import java.util.NoSuchElementException;
import swim.util.OrderedMapCursor;
final class BTreeNodeCursor<K, V, U> implements OrderedMapCursor<K, V> {
final BTreePage<K, V, U>[] pages;
long index;
int pageIndex;
OrderedMapCursor<K, V> pageCursor;
BTreeNodeCursor(BTreePage<K, V, U>[] pages, long index, int pageIndex, OrderedMapCursor<K, V> pageCursor) {
this.pages = pages;
this.index = index;
this.pageIndex = pageIndex;
this.pageCursor = pageCursor;
}
BTreeNodeCursor(BTreePage<K, V, U>[] pages, long index, int pageIndex) {
this(pages, index, pageIndex, null);
}
BTreeNodeCursor(BTreePage<K, V, U>[] pages) {
this(pages, 0L, 0, null);
}
long pageSize(BTreePage<K, V, U> page) {
return page.size();
}
OrderedMapCursor<K, V> pageCursor(BTreePage<K, V, U> page) {
return page.iterator();
}
OrderedMapCursor<K, V> lastPageCursor(BTreePage<K, V, U> page) {
return page.lastIterator();
}
@Override
public boolean isEmpty() {
do {
if (this.pageCursor != null) {
if (!this.pageCursor.isEmpty()) {
return false;
} else {
this.pageCursor = null;
}
} else if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
return true;
}
} while (true);
}
@Override
public Map.Entry<K, V> head() {
do {
if (this.pageCursor != null) {
if (!this.pageCursor.isEmpty()) {
return this.pageCursor.head();
} else {
this.pageCursor = null;
}
} else {
if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
throw new NoSuchElementException();
}
}
} while (true);
}
@Override
public void step() {
do {
if (this.pageCursor != null) {
if (!this.pageCursor.isEmpty()) {
this.index += 1L;
return;
} else {
this.pageCursor = null;
}
} else {
if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
throw new UnsupportedOperationException();
}
}
} while (true);
}
@Override
public void skip(long count) {
while (count > 0L) {
if (this.pageCursor != null) {
if (this.pageCursor.hasNext()) {
this.index += 1L;
count -= 1L;
this.pageCursor.next();
} else {
this.pageCursor = null;
}
} else if (this.pageIndex < this.pages.length) {
final BTreePage<K, V, U> page = this.pages[this.pageIndex];
final long pageSize = pageSize(page);
this.pageIndex += 1;
if (pageSize < count) {
this.pageCursor = pageCursor(page);
if (count > 0L) {
this.index += count;
this.pageCursor.skip(count);
count = 0L;
}
break;
} else {
this.index += pageSize;
count -= pageSize;
}
} else {
break;
}
}
}
@Override
public boolean hasNext() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasNext()) {
return true;
} else {
this.pageCursor = null;
}
} else if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
return false;
}
} while (true);
}
@Override
public long nextIndexLong() {
return this.index;
}
@Override
public K nextKey() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasNext()) {
return this.pageCursor.nextKey();
} else {
this.pageCursor = null;
}
} else {
if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
throw new NoSuchElementException();
}
}
} while (true);
}
@Override
public Map.Entry<K, V> next() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasNext()) {
this.index += 1;
return this.pageCursor.next();
} else {
this.pageCursor = null;
}
} else {
if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
throw new NoSuchElementException();
}
}
} while (true);
}
@Override
public boolean hasPrevious() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasPrevious()) {
return true;
} else {
this.pageCursor = null;
}
} else if (this.pageIndex > 0) {
this.pageCursor = lastPageCursor(this.pages[this.pageIndex - 1]);
this.pageIndex -= 1;
} else {
this.pageIndex = 0;
return false;
}
} while (true);
}
@Override
public long previousIndexLong() {
return this.index - 1L;
}
@Override
public K previousKey() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasPrevious()) {
return this.pageCursor.previousKey();
} else {
this.pageCursor = null;
}
} else if (this.pageIndex > 0) {
this.pageCursor = lastPageCursor(this.pages[this.pageIndex - 1]);
this.pageIndex -= 1;
} else {
this.pageIndex = 0;
throw new NoSuchElementException();
}
} while (true);
}
@Override
public Map.Entry<K, V> previous() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasPrevious()) {
this.index -= 1;
return this.pageCursor.previous();
} else {
this.pageCursor = null;
}
} else if (this.pageIndex > 0) {
this.pageCursor = lastPageCursor(this.pages[this.pageIndex - 1]);
this.pageIndex -= 1;
} else {
this.pageIndex = 0;
throw new NoSuchElementException();
}
} while (true);
}
@Override
public void set(Map.Entry<K, V> newValue) {
this.pageCursor.set(newValue);
}
@Override
public void remove() {
this.pageCursor.remove();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/BTreePage.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.collections;
import java.util.Map;
import swim.util.CombinerFunction;
import swim.util.Cursor;
import swim.util.OrderedMapCursor;
public abstract class BTreePage<K, V, U> {
BTreePage() {
// stub
}
public abstract boolean isEmpty();
public abstract int size();
public abstract int arity();
public abstract U fold();
public abstract K minKey();
public abstract K maxKey();
public abstract boolean containsKey(Object key, BTreeContext<K, V> tree);
public abstract boolean containsValue(Object value);
public abstract int indexOf(Object key, BTreeContext<K, V> tree);
public abstract V get(Object key, BTreeContext<K, V> tree);
public abstract Map.Entry<K, V> getEntry(Object key, BTreeContext<K, V> tree);
public abstract Map.Entry<K, V> getIndex(int index);
public abstract Map.Entry<K, V> firstEntry();
public abstract Map.Entry<K, V> lastEntry();
public abstract Map.Entry<K, V> nextEntry(K key, BTreeContext<K, V> tree);
public abstract Map.Entry<K, V> previousEntry(K key, BTreeContext<K, V> tree);
public abstract BTreePage<K, V, U> updated(K key, V newValue, BTreeContext<K, V> tree);
public abstract BTreePage<K, V, U> removed(Object key, BTreeContext<K, V> tree);
public abstract BTreePage<K, V, U> drop(int lower, BTreeContext<K, V> tree);
public abstract BTreePage<K, V, U> take(int upper, BTreeContext<K, V> tree);
public abstract BTreePage<K, V, U> balanced(BTreeContext<K, V> tree);
public abstract BTreePage<K, V, U> split(int index);
public abstract BTreePage<K, V, U> splitLeft(int index);
public abstract BTreePage<K, V, U> splitRight(int index);
public abstract BTreePage<K, V, U> reduced(U identity, CombinerFunction<? super V, U> accumulator,
CombinerFunction<U, U> combiner);
public Cursor<K> keyIterator() {
return Cursor.keys(iterator());
}
public Cursor<V> valueIterator() {
return Cursor.values(iterator());
}
public abstract OrderedMapCursor<K, V> iterator();
public Cursor<K> lastKeyIterator() {
return Cursor.keys(lastIterator());
}
public Cursor<V> lastValueIterator() {
return Cursor.values(lastIterator());
}
public abstract OrderedMapCursor<K, V> lastIterator();
public static <K, V, U> BTreePage<K, V, U> empty() {
return BTreeLeaf.empty();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/FingerTrieSeq.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.collections;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Builder;
import swim.util.Murmur3;
public final class FingerTrieSeq<T> implements List<T>, Debug {
final Object[] prefix;
final FingerTrieSeq<Object[]> branch;
final Object[] suffix;
final int length;
FingerTrieSeq(Object[] prefix, FingerTrieSeq<Object[]> branch, Object[] suffix, int length) {
this.prefix = prefix;
this.branch = branch;
this.suffix = suffix;
this.length = length;
}
@SuppressWarnings("unchecked")
FingerTrieSeq() {
this.prefix = EMPTY_LEAF;
this.branch = (FingerTrieSeq<Object[]>) this;
this.suffix = EMPTY_LEAF;
this.length = 0;
}
@Override
public boolean isEmpty() {
return this.length == 0;
}
@Override
public int size() {
return this.length;
}
@Override
public boolean contains(Object elem) {
final Iterator<T> iter = iterator();
while (iter.hasNext()) {
final T next = iter.next();
if (elem == null ? next == null : elem.equals(next)) {
return true;
}
}
return false;
}
@Override
public boolean containsAll(Collection<?> elems) {
for (Object elem : elems) {
if (!contains(elem)) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public T get(int index) {
final Object[] prefix = this.prefix;
final int n = index - prefix.length;
if (n < 0) {
return (T) prefix[index];
} else {
final FingerTrieSeq<Object[]> branch = this.branch;
final int j = n - (branch.length << 5);
if (j < 0) {
return (T) branch.get(n >> 5)[n & 0x1F];
} else {
return (T) this.suffix[j];
}
}
}
@Override
public T set(int index, T nwElem) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(T newElem) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends T> newElems) {
throw new UnsupportedOperationException();
}
@Override
public void add(int index, T newElem) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(int index, Collection<? extends T> newElems) {
throw new UnsupportedOperationException();
}
@Override
public T remove(int index) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object elem) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> elems) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> elems) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public int indexOf(Object elem) {
for (int i = 0, n = length; i < n; i += 1) {
if (elem == null ? get(i) == null : elem.equals(get(i))) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object elem) {
for (int i = length - 1; i >= 0; i -= 1) {
if (elem == null ? get(i) == null : elem.equals(get(i))) {
return i;
}
}
return -1;
}
public FingerTrieSeq<T> updated(int index, T elem) {
final Object[] oldPrefix = this.prefix;
final int a = oldPrefix.length;
final int n = index - a;
if (n < 0) {
final Object[] newPrefix = new Object[a];
System.arraycopy(oldPrefix, 0, newPrefix, 0, a);
newPrefix[index] = elem;
return new FingerTrieSeq<T>(newPrefix, this.branch, this.suffix, this.length);
} else {
final FingerTrieSeq<Object[]> oldBranch = this.branch;
final int j = n - (oldBranch.length << 5);
if (j < 0) {
final Object[] oldInfix = oldBranch.get(n >> 5);
final Object[] newInfix = new Object[32];
System.arraycopy(oldInfix, 0, newInfix, 0, 32);
newInfix[n & 0x1F] = elem;
final FingerTrieSeq<Object[]> newBranch = oldBranch.updated(n >> 5, newInfix);
return new FingerTrieSeq<T>(oldPrefix, newBranch, this.suffix, this.length);
} else {
final Object[] oldSuffix = this.suffix;
final int b = oldSuffix.length;
final Object[] newSuffix = new Object[b];
System.arraycopy(oldSuffix, 0, newSuffix, 0, b);
newSuffix[j] = elem;
return new FingerTrieSeq<T>(oldPrefix, oldBranch, newSuffix, this.length);
}
}
}
@SuppressWarnings("unchecked")
public T head() {
if (this.length == 0) {
throw new NoSuchElementException();
}
return (T) this.prefix[0];
}
public FingerTrieSeq<T> tail() {
if (this.length == 0) {
throw new UnsupportedOperationException();
}
return drop(1);
}
public FingerTrieSeq<T> body() {
if (this.length == 0) {
throw new UnsupportedOperationException();
}
return take(this.length - 1);
}
@SuppressWarnings("unchecked")
public T foot() {
if (this.length == 0) {
throw new NoSuchElementException();
}
if (this.length <= 32) {
return (T) this.prefix[this.prefix.length - 1];
} else {
return (T) this.suffix[this.suffix.length - 1];
}
}
@SuppressWarnings("unchecked")
public FingerTrieSeq<T> drop(int lower) {
if (lower <= 0) {
return this;
} else if (lower >= this.length) {
return (FingerTrieSeq<T>) EMPTY;
} else {
final int n = lower - this.prefix.length;
final int k = this.length - lower;
final FingerTrieSeq<Object[]> oldBranch = this.branch;
if (n == 0) {
if (oldBranch.length > 0) {
return new FingerTrieSeq<T>(oldBranch.head(), oldBranch.tail(), this.suffix, k);
} else {
return new FingerTrieSeq<T>(this.suffix, EMPTY_NODE, EMPTY_LEAF, k);
}
} else if (n < 0) {
final Object[] newPrefix = new Object[-n];
System.arraycopy(this.prefix, lower, newPrefix, 0, -n);
return new FingerTrieSeq<T>(newPrefix, oldBranch, this.suffix, k);
} else {
final int j = n - (oldBranch.length << 5);
if (j < 0) {
final FingerTrieSeq<Object[]> split = oldBranch.drop(n >> 5);
final Object[] oldPrefix = split.head();
final Object[] newPrefix = new Object[oldPrefix.length - (n & 0x1F)];
System.arraycopy(oldPrefix, n & 0x1F, newPrefix, 0, newPrefix.length);
return new FingerTrieSeq<T>(newPrefix, split.tail(), this.suffix, k);
} else {
final Object[] newPrefix = new Object[k];
System.arraycopy(this.suffix, j, newPrefix, 0, k);
return new FingerTrieSeq<T>(newPrefix, EMPTY_NODE, EMPTY_LEAF, k);
}
}
}
}
@SuppressWarnings("unchecked")
public FingerTrieSeq<T> take(int upper) {
if (upper <= 0) {
return (FingerTrieSeq<T>) EMPTY;
} else if (upper >= this.length) {
return this;
} else {
final int n = upper - this.prefix.length;
if (n == 0) {
return new FingerTrieSeq<T>(this.prefix, EMPTY_NODE, EMPTY_LEAF, upper);
} else if (n < 0) {
final Object[] newPrefix = new Object[upper];
System.arraycopy(this.prefix, 0, newPrefix, 0, upper);
return new FingerTrieSeq<T>(newPrefix, EMPTY_NODE, EMPTY_LEAF, upper);
} else {
final FingerTrieSeq<Object[]> oldBranch = this.branch;
final int j = n - (oldBranch.length << 5);
if (j == 0) {
if (oldBranch.length > 0) {
return new FingerTrieSeq<T>(this.prefix, oldBranch.body(), oldBranch.foot(), upper);
} else {
return new FingerTrieSeq<T>(this.suffix, EMPTY_NODE, EMPTY_LEAF, upper);
}
} else if (j < 0) {
final FingerTrieSeq<Object[]> split = oldBranch.take(((n + 0x1F) & 0xFFFFFFE0) >> 5);
final Object[] oldSuffix = split.foot();
final Object[] newSuffix = new Object[((((n & 0x1F) ^ 0x1F) + 1) & 0x20) | (n & 0x1F)];
System.arraycopy(oldSuffix, 0, newSuffix, 0, newSuffix.length);
return new FingerTrieSeq<T>(this.prefix, split.body(), newSuffix, upper);
} else {
final Object[] newSuffix = new Object[j];
System.arraycopy(this.suffix, 0, newSuffix, 0, j);
return new FingerTrieSeq<T>(this.prefix, oldBranch, newSuffix, upper);
}
}
}
}
@SuppressWarnings("unchecked")
public FingerTrieSeq<T> slice(int lower, int upper) {
if (lower >= upper) {
return (FingerTrieSeq<T>) EMPTY;
} else {
return drop(lower).take(upper - Math.max(0, lower));
}
}
public FingerTrieSeq<T> appended(T elem) {
final int i = this.prefix.length;
final int j = this.suffix.length;
final int n = this.branch.length;
if (n == 0 && j == 0 && i < 32) {
final Object[] newPrefix = new Object[i + 1];
System.arraycopy(this.prefix, 0, newPrefix, 0, i);
newPrefix[i] = elem;
return new FingerTrieSeq<T>(newPrefix, EMPTY_NODE, EMPTY_LEAF, this.length + 1);
} else if (n == 0 && i + j < 32) {
final Object[] newPrefix = new Object[i + j + 1];
System.arraycopy(this.prefix, 0, newPrefix, 0, i);
System.arraycopy(this.suffix, 0, newPrefix, i, j);
newPrefix[i + j] = elem;
return new FingerTrieSeq<T>(newPrefix, EMPTY_NODE, EMPTY_LEAF, this.length + 1);
} else if (n == 0 && i + j < 64) {
final Object[] newPrefix = new Object[32];
System.arraycopy(this.prefix, 0, newPrefix, 0, i);
System.arraycopy(this.suffix, 0, newPrefix, i, 32 - i);
final Object[] newSuffix = new Object[i + j - 32 + 1];
System.arraycopy(this.suffix, 32 - i, newSuffix, 0, i + j - 32);
newSuffix[i + j - 32] = elem;
return new FingerTrieSeq<T>(newPrefix, EMPTY_NODE, newSuffix, this.length + 1);
} else if (j < 32) {
final Object[] newSuffix = new Object[j + 1];
System.arraycopy(this.suffix, 0, newSuffix, 0, j);
newSuffix[j] = elem;
return new FingerTrieSeq<T>(this.prefix, this.branch, newSuffix, this.length + 1);
} else {
final Object[] newSuffix = new Object[1];
newSuffix[0] = elem;
final FingerTrieSeq<Object[]> newBranch = this.branch.appended(this.suffix);
return new FingerTrieSeq<T>(this.prefix, newBranch, newSuffix, this.length + 1);
}
}
public FingerTrieSeq<T> appended(Collection<? extends T> elems) {
final FingerTrieSeqBuilder<T> builder = new FingerTrieSeqBuilder<T>(this);
builder.addAll(elems);
return builder.bind();
}
public FingerTrieSeq<T> prepended(T elem) {
final int i = this.prefix.length;
final int j = this.suffix.length;
final int n = this.branch.length;
if (n == 0 && j == 0 && i < 32) {
final Object[] newPrefix = new Object[1 + i];
newPrefix[0] = elem;
System.arraycopy(this.prefix, 0, newPrefix, 1, i);
return new FingerTrieSeq<T>(newPrefix, EMPTY_NODE, EMPTY_LEAF, 1 + this.length);
} else if (n == 0 && i + j < 32) {
final Object[] newPrefix = new Object[1 + i + j];
newPrefix[0] = elem;
System.arraycopy(this.prefix, 0, newPrefix, 1, i);
System.arraycopy(this.suffix, 0, newPrefix, 1 + i, j);
return new FingerTrieSeq<T>(newPrefix, EMPTY_NODE, EMPTY_LEAF, 1 + this.length);
} else if (n == 0 && i + j < 64) {
final Object[] newPrefix = new Object[1 + i + j - 32];
newPrefix[0] = elem;
System.arraycopy(this.prefix, 0, newPrefix, 1, i + j - 32);
final Object[] newSuffix = new Object[32];
System.arraycopy(this.prefix, i + j - 32, newSuffix, 0, 32 - j);
System.arraycopy(this.suffix, 0, newSuffix, 32 - j, j);
return new FingerTrieSeq<T>(newPrefix, EMPTY_NODE, newSuffix, 1 + this.length);
} else if (i < 32) {
final Object[] newPrefix = new Object[1 + i];
newPrefix[0] = elem;
System.arraycopy(this.prefix, 0, newPrefix, 1, i);
return new FingerTrieSeq<T>(newPrefix, this.branch, this.suffix, 1 + this.length);
} else {
final Object[] newPrefix = new Object[1];
newPrefix[0] = elem;
final FingerTrieSeq<Object[]> newBranch = this.branch.prepended(this.prefix);
return new FingerTrieSeq<T>(newPrefix, newBranch, this.suffix, 1 + this.length);
}
}
public FingerTrieSeq<T> prepended(Collection<? extends T> elems) {
final FingerTrieSeqBuilder<T> builder = new FingerTrieSeqBuilder<T>();
builder.addAll(elems);
builder.addAll(this);
return builder.bind();
}
public FingerTrieSeq<T> removed(int index) {
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException(String.valueOf(index));
}
if (index == 0) {
return drop(1);
} else {
final int newLength = length - 1;
if (index == newLength) {
return take(index);
} else if (index > 0) {
final FingerTrieSeqBuilder<T> builder = new FingerTrieSeqBuilder<T>(take(index));
do {
index += 1;
builder.add(get(index));
} while (index < newLength);
return builder.bind();
} else {
return this;
}
}
}
public FingerTrieSeq<T> removed(Object elem) {
final int index = indexOf(elem);
if (index >= 0) {
return removed(index);
} else {
return this;
}
}
@Override
public FingerTrieSeq<T> subList(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > length || fromIndex > toIndex) {
throw new IndexOutOfBoundsException(fromIndex + ", " + toIndex);
}
return drop(fromIndex).take(toIndex - fromIndex);
}
@Override
public Object[] toArray() {
final int n = length;
final Object[] array = new Object[n];
for (int i = 0; i < n; i += 1) {
array[i] = get(i);
}
return array;
}
@SuppressWarnings("unchecked")
@Override
public <T> T[] toArray(T[] array) {
final int n = length;
if (array.length < n) {
array = (T[]) Array.newInstance(array.getClass().getComponentType(), n);
}
for (int i = 0; i < n; i += 1) {
array[i] = (T) get(i);
}
if (array.length > n) {
array[n] = null;
}
return array;
}
@Override
public Iterator<T> iterator() {
return new FingerTrieSeqIterator<T>(this);
}
@Override
public ListIterator<T> listIterator() {
return new FingerTrieSeqIterator<T>(this);
}
@Override
public ListIterator<T> listIterator(int index) {
return new FingerTrieSeqIterator<T>(this, index);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof FingerTrieSeq<?>) {
final FingerTrieSeq<T> that = (FingerTrieSeq<T>) other;
if (this.length == that.length) {
final Iterator<T> these = iterator();
final Iterator<T> those = that.iterator();
while (these.hasNext() && those.hasNext()) {
final T x = these.next();
final T y = those.next();
if (x == null ? y != null : !x.equals(y)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(FingerTrieSeq.class);
}
int h = hashSeed;
final Iterator<T> these = iterator();
while (these.hasNext()) {
h = Murmur3.mix(h, Murmur3.hash(these.next()));
}
return Murmur3.mash(h);
}
@Override
public void debug(Output<?> output) {
output = output.write("FingerTrieSeq").write('.');
final Iterator<T> these = iterator();
if (these.hasNext()) {
output = output.write("of").write('(').debug(these.next());
while (these.hasNext()) {
output = output.write(", ").debug(these.next());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
static final Object[] EMPTY_LEAF = new Object[0];
static final FingerTrieSeq<?> EMPTY = new FingerTrieSeq<Object>();
@SuppressWarnings("unchecked")
static final FingerTrieSeq<Object[]> EMPTY_NODE = (FingerTrieSeq<Object[]>) EMPTY;
@SuppressWarnings("unchecked")
public static <T> FingerTrieSeq<T> empty() {
return (FingerTrieSeq<T>) EMPTY;
}
public static <T> FingerTrieSeq<T> of(T elem0, T elem1) {
final FingerTrieSeqBuilder<T> builder = new FingerTrieSeqBuilder<T>();
builder.add(elem0);
builder.add(elem1);
return builder.bind();
}
@SuppressWarnings("unchecked")
public static <T> FingerTrieSeq<T> of(T... elems) {
final FingerTrieSeqBuilder<T> builder = new FingerTrieSeqBuilder<T>();
for (T elem : elems) {
builder.add(elem);
}
return builder.bind();
}
public static <T> FingerTrieSeq<T> from(Iterable<? extends T> elems) {
final FingerTrieSeqBuilder<T> builder = new FingerTrieSeqBuilder<T>();
for (T elem : elems) {
builder.add(elem);
}
return builder.bind();
}
public static <T> Builder<T, FingerTrieSeq<T>> builder(FingerTrieSeq<? extends T> trie) {
return new FingerTrieSeqBuilder<T>(trie);
}
public static <T> Builder<T, FingerTrieSeq<T>> builder() {
return new FingerTrieSeqBuilder<T>();
}
}
final class FingerTrieSeqBuilder<T> implements Builder<T, FingerTrieSeq<T>> {
Object[] prefix;
FingerTrieSeqBuilder<Object[]> branch;
Object[] buffer;
int length;
FingerTrieSeqBuilder(FingerTrieSeq<? extends T> trie) {
if (trie.length > 32) {
this.prefix = trie.prefix;
if (trie.length > 64) {
this.branch = new FingerTrieSeqBuilder<Object[]>(trie.branch);
}
this.buffer = trie.suffix;
} else if (trie.length > 0) {
this.buffer = trie.prefix;
}
this.length = trie.length;
}
FingerTrieSeqBuilder() {
this.prefix = null;
this.branch = null;
this.buffer = null;
this.length = 0;
}
private int getSkew() {
return (this.prefix != null ? this.length - this.prefix.length : this.length) & 0x1F;
}
@Override
public boolean add(T elem) {
final int offset = getSkew();
if (offset == 0) {
if (this.buffer != null) {
if (this.prefix == null) {
this.prefix = this.buffer;
} else {
if (this.branch == null) {
this.branch = new FingerTrieSeqBuilder<Object[]>();
}
this.branch.add(this.buffer);
}
}
this.buffer = new Object[32];
} else if (this.buffer.length < 32) {
final Object[] newBuffer = new Object[32];
System.arraycopy(this.buffer, 0, newBuffer, 0, offset);
this.buffer = newBuffer;
}
this.buffer[offset] = elem;
this.length += 1;
return true;
}
@Override
public boolean addAll(Collection<? extends T> elems) {
if (elems instanceof FingerTrieSeq<?>) {
return addAll((FingerTrieSeq<? extends T>) elems);
} else {
for (T elem : elems) {
add(elem);
}
return true;
}
}
boolean addAll(FingerTrieSeq<? extends T> that) {
if (this.length == 0 && that.length != 0) {
if (that.length > 32) {
this.prefix = that.prefix;
if (that.length > 64) {
this.branch = new FingerTrieSeqBuilder<Object[]>(that.branch);
}
this.buffer = that.suffix;
} else {
this.buffer = that.prefix;
}
this.length = that.length;
} else if (that.length != 0) {
final int offset = getSkew();
if (((offset + that.prefix.length) & 0x1F) == 0) {
if (buffer.length < 32) {
final Object[] newBuffer = new Object[32];
System.arraycopy(this.buffer, 0, newBuffer, 0, offset);
this.buffer = newBuffer;
}
if (offset > 0) {
System.arraycopy(that.prefix, 0, this.buffer, offset, 32 - offset);
} else {
if (this.prefix == null) {
this.prefix = this.buffer;
} else {
if (this.branch == null) {
this.branch = new FingerTrieSeqBuilder<Object[]>();
}
this.branch.add(this.buffer);
}
this.buffer = that.prefix;
}
if (that.suffix.length > 0) {
if (this.branch == null) {
this.branch = new FingerTrieSeqBuilder<Object[]>();
}
this.branch.add(this.buffer);
this.branch.addAll(that.branch);
this.buffer = that.suffix;
}
this.length += that.length;
} else {
for (T elem : that) {
add(elem);
}
}
}
return true;
}
public void clear() {
this.prefix = null;
this.branch = null;
this.buffer = null;
this.length = 0;
}
@SuppressWarnings("unchecked")
@Override
public FingerTrieSeq<T> bind() {
if (this.length == 0) {
return (FingerTrieSeq<T>) FingerTrieSeq.EMPTY;
} else {
final int offset = getSkew();
if (offset != 0 && offset != this.buffer.length) {
final Object[] suffix = new Object[offset];
System.arraycopy(this.buffer, 0, suffix, 0, offset);
this.buffer = suffix;
}
if (prefix == null) {
return new FingerTrieSeq<T>(this.buffer, FingerTrieSeq.EMPTY_NODE,
FingerTrieSeq.EMPTY_LEAF, this.length);
} else if (branch == null) {
return new FingerTrieSeq<T>(this.prefix, FingerTrieSeq.EMPTY_NODE, this.buffer, this.length);
} else {
return new FingerTrieSeq<T>(this.prefix, this.branch.bind(), this.buffer, this.length);
}
}
}
}
final class FingerTrieSeqSegmenter implements ListIterator<Object[]> {
final Object[] prefix;
final FingerTrieSeq<Object[]> branch;
final Object[] suffix;
FingerTrieSeqSegmenter inner;
Object[] infix;
int infixIndex;
int index;
int phase;
FingerTrieSeqSegmenter(FingerTrieSeq<?> trie) {
this.prefix = trie.prefix;
this.branch = trie.branch;
this.suffix = trie.suffix;
this.phase = trie.length > 0 ? 0 : 3;
}
FingerTrieSeqSegmenter(FingerTrieSeq<?> trie, int index) {
this.prefix = trie.prefix;
this.branch = trie.branch;
this.suffix = trie.suffix;
this.index = index;
if (index == 0) {
this.phase = 0;
} else if (index - 1 < this.branch.length) {
this.inner = new FingerTrieSeqSegmenter(this.branch, (index - 1) >> 5);
this.infix = this.inner.next();
this.infixIndex = (index - 1) & 0x1F;
this.phase = 1;
} else if (index == 1 + this.branch.length && this.suffix.length > 0) {
this.phase = 2;
} else {
this.phase = 3;
}
}
@Override
public boolean hasNext() {
return this.phase < 3;
}
@Override
public int nextIndex() {
return this.index;
}
@Override
public Object[] next() {
switch (this.phase) {
case 0:
this.index += 1;
if (this.branch.length > 0) {
this.inner = new FingerTrieSeqSegmenter(this.branch);
this.infix = this.inner.next();
this.infixIndex = 0;
this.phase = 1;
} else if (this.suffix.length > 0) {
this.phase = 2;
} else {
this.phase = 3;
}
return this.prefix;
case 1:
final Object[] head = (Object[]) this.infix[this.infixIndex];
this.infixIndex += 1;
this.index += 1;
if (this.infixIndex >= this.infix.length) {
if (this.inner.hasNext()) {
this.infix = this.inner.next();
this.infixIndex = 0;
} else {
this.inner = null;
this.phase = 2;
}
}
return head;
case 2:
this.index += 1;
this.phase = 3;
return this.suffix;
default:
throw new NoSuchElementException();
}
}
@Override
public boolean hasPrevious() {
return this.phase > 0;
}
@Override
public int previousIndex() {
return this.index - 1;
}
@Override
public Object[] previous() {
switch (this.phase) {
case 1:
this.index -= 1;
if (this.infixIndex > 0) {
this.infixIndex -= 1;
return (Object[]) this.infix[this.infixIndex];
} else {
this.inner.previous();
if (this.inner.hasPrevious()) {
this.infix = this.inner.previous();
this.infixIndex = this.infix.length - 1;
this.inner.next();
return (Object[]) this.infix[this.infixIndex];
} else {
this.inner = null;
this.phase = 0;
return this.prefix;
}
}
case 2:
this.index -= 1;
if (this.branch.length > 0) {
if (this.inner == null) {
this.inner = new FingerTrieSeqSegmenter(this.branch, this.branch.length);
}
this.infix = this.inner.previous();
this.infixIndex = this.infix.length - 1;
this.inner.next();
this.phase = 1;
return (Object[]) this.infix[this.infixIndex];
} else {
this.phase = 0;
return this.prefix;
}
case 3:
this.index -= 1;
if (this.suffix.length > 0) {
this.phase = 2;
return this.suffix;
} else if (this.branch.length > 0) {
if (this.inner == null) {
this.inner = new FingerTrieSeqSegmenter(this.branch, this.branch.length);
}
this.infix = this.inner.previous();
this.infixIndex = this.infix.length - 1;
this.inner.next();
this.phase = 1;
return (Object[]) this.infix[this.infixIndex];
} else {
this.phase = 0;
return this.prefix;
}
default:
throw new NoSuchElementException();
}
}
@Override
public void add(Object[] segment) {
throw new UnsupportedOperationException();
}
@Override
public void set(Object[] segment) {
throw new UnsupportedOperationException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
final class FingerTrieSeqIterator<T> implements ListIterator<T> {
final FingerTrieSeqSegmenter segmenter;
Object[] page;
int pageIndex;
int index;
FingerTrieSeqIterator(FingerTrieSeq<T> trie) {
this.segmenter = new FingerTrieSeqSegmenter(trie);
if (this.segmenter.hasNext()) {
this.page = this.segmenter.next();
} else {
this.page = FingerTrieSeq.EMPTY_LEAF;
}
}
FingerTrieSeqIterator(FingerTrieSeq<T> trie, int index) {
final int n = index - trie.prefix.length;
if (n < 0) {
this.segmenter = new FingerTrieSeqSegmenter(trie, 1);
this.page = trie.prefix;
this.pageIndex = index;
} else if (index < trie.length) {
final int j = n - (trie.branch.length << 5);
if (j < 0) {
this.segmenter = new FingerTrieSeqSegmenter(trie, 1 + (n >> 5));
this.page = this.segmenter.next();
this.pageIndex = n & 0x1F;
} else {
this.segmenter = new FingerTrieSeqSegmenter(trie, 1 + trie.branch.length);
this.page = this.segmenter.next();
this.pageIndex = j;
}
} else {
this.segmenter = new FingerTrieSeqSegmenter(trie, trie.length);
this.page = FingerTrieSeq.EMPTY_LEAF;
this.pageIndex = 0;
}
this.index = index;
}
@Override
public boolean hasNext() {
return this.pageIndex < this.page.length;
}
@Override
public int nextIndex() {
return this.index;
}
@SuppressWarnings("unchecked")
@Override
public T next() {
if (this.pageIndex < this.page.length) {
final T head = (T) this.page[this.pageIndex];
this.pageIndex += 1;
this.index += 1;
if (this.pageIndex >= this.page.length) {
if (this.segmenter.hasNext()) {
this.page = this.segmenter.next();
} else {
this.page = FingerTrieSeq.EMPTY_LEAF;
}
this.pageIndex = 0;
}
return head;
} else {
throw new NoSuchElementException();
}
}
@Override
public boolean hasPrevious() {
return this.index > 0;
}
@Override
public int previousIndex() {
return this.index - 1;
}
@SuppressWarnings("unchecked")
@Override
public T previous() {
if (this.pageIndex > 0) {
this.index -= 1;
this.pageIndex -= 1;
return (T) this.page[this.pageIndex];
} else {
this.segmenter.previous();
if (this.segmenter.hasPrevious()) {
this.index -= 1;
this.page = this.segmenter.previous();
this.pageIndex = this.page.length - 1;
this.segmenter.next();
return (T) this.page[this.pageIndex];
} else {
throw new NoSuchElementException();
}
}
}
@Override
public void add(T elem) {
throw new UnsupportedOperationException();
}
@Override
public void set(T elem) {
throw new UnsupportedOperationException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/HashTrieMap.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.collections;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Murmur3;
public final class HashTrieMap<K, V> implements Iterable<Map.Entry<K, V>>, Map<K, V>, Debug {
final int treeMap;
final int leafMap;
final Object[] slots;
HashTrieMap(int treeMap, int leafMap, Object[] slots) {
this.treeMap = treeMap;
this.leafMap = leafMap;
this.slots = slots;
}
@Override
public boolean isEmpty() {
return slotMap() == 0;
}
@Override
public int size() {
int t = 0;
int i = 0;
int treeMap = this.treeMap;
int leafMap = this.leafMap;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
t += 1;
i += 1;
break;
case TREE:
t += treeAt(i).size();
i += 1;
break;
case KNOT:
t += knotAt(i).size();
i += 1;
break;
default:
throw new AssertionError();
}
treeMap >>>= 1;
leafMap >>>= 1;
}
return t;
}
@Override
public boolean containsKey(Object key) {
if (key != null) {
return containsKey(this, key, Murmur3.hash(key), 0);
} else {
return false;
}
}
@Override
public boolean containsValue(Object value) {
int i = 0;
int j = 0;
int treeMap = this.treeMap;
int leafMap = this.leafMap;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
final V v = valueAt(j);
if (value == null ? v == null : value.equals(v)) {
return true;
}
i += 1;
j += 1;
break;
case TREE:
if (treeAt(i).containsValue(value)) {
return true;
}
i += 1;
break;
case KNOT:
if (knotAt(i).containsValue(value)) {
return true;
}
i += 1;
break;
default:
throw new AssertionError();
}
treeMap >>>= 1;
leafMap >>>= 1;
}
return false;
}
public Entry<K, V> head() {
return head(this);
}
public K headKey() {
return headKey(this);
}
public V headValue() {
return headValue(this);
}
public Entry<K, V> next(Object key) {
Entry<K, V> next = next(key, Murmur3.hash(key), 0);
if (next == null) {
next = head(this);
}
return next;
}
public K nextKey(Object key) {
K next = nextKey(key, Murmur3.hash(key), 0);
if (next == null) {
next = headKey(this);
}
return next;
}
public V nextValue(Object key) {
V next = nextValue(key, Murmur3.hash(key), 0);
if (next == null) {
next = headValue(this);
}
return next;
}
@Override
public V get(Object key) {
if (key != null) {
return get(this, key, Murmur3.hash(key), 0);
} else {
return null;
}
}
@Override
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException();
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
public HashTrieMap<K, V> updated(K key, V value) {
if (key != null) {
return updated(key, Murmur3.hash(key), value, 0);
} else {
throw new NullPointerException();
}
}
public HashTrieMap<K, V> updated(Map<? extends K, ? extends V> map) {
HashTrieMap<K, V> these = this;
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
these = these.updated(entry.getKey(), entry.getValue());
}
return these;
}
public HashTrieMap<K, V> removed(Object key) {
if (key != null) {
return removed(key, Murmur3.hash(key), 0);
} else {
return this;
}
}
int slotMap() {
return treeMap | leafMap;
}
int choose(int hash, int shift) {
return 1 << ((hash >>> shift) & 0x1F);
}
int select(int branch) {
return Integer.bitCount(slotMap() & (branch - 1));
}
int lookup(int branch) {
return Integer.bitCount(leafMap & (branch - 1));
}
int follow(int branch) {
return ((leafMap & branch) != 0 ? 1 : 0) | ((treeMap & branch) != 0 ? 2 : 0);
}
@SuppressWarnings("unchecked")
K keyAt(int index) {
return (K) slots[index];
}
@SuppressWarnings("unchecked")
K getKey(int branch) {
return (K) slots[select(branch)];
}
@SuppressWarnings("unchecked")
V valueAt(int index) {
return (V) slots[slots.length - index - 1];
}
@SuppressWarnings("unchecked")
V getValue(int branch) {
return (V) slots[slots.length - lookup(branch) - 1];
}
HashTrieMap<K, V> setLeaf(int branch, K key, V value) {
slots[select(branch)] = key;
slots[slots.length - lookup(branch) - 1] = value;
return this;
}
@SuppressWarnings("unchecked")
HashTrieMap<K, V> treeAt(int index) {
return (HashTrieMap<K, V>) slots[index];
}
@SuppressWarnings("unchecked")
HashTrieMap<K, V> getTree(int branch) {
return (HashTrieMap<K, V>) slots[select(branch)];
}
HashTrieMap<K, V> setTree(int branch, HashTrieMap<K, V> tree) {
slots[select(branch)] = tree;
return this;
}
@SuppressWarnings("unchecked")
ArrayMap<K, V> knotAt(int index) {
return (ArrayMap<K, V>) slots[index];
}
@SuppressWarnings("unchecked")
ArrayMap<K, V> getKnot(int branch) {
return (ArrayMap<K, V>) slots[select(branch)];
}
HashTrieMap<K, V> setKnot(int branch, ArrayMap<K, V> knot) {
slots[select(branch)] = knot;
return this;
}
boolean isUnary() {
return treeMap == 0 && Integer.bitCount(leafMap) == 1;
}
@SuppressWarnings("unchecked")
K unaryKey() {
return (K) slots[0];
}
@SuppressWarnings("unchecked")
V unaryValue() {
return (V) slots[1];
}
HashTrieMap<K, V> remap(int treeMap, int leafMap) {
int oldLeafMap = this.leafMap;
int newLeafMap = leafMap;
int oldSlotMap = this.treeMap | this.leafMap;
int newSlotMap = treeMap | leafMap;
if (oldLeafMap == newLeafMap && oldSlotMap == newSlotMap) {
return new HashTrieMap<K, V>(treeMap, leafMap, slots.clone());
} else {
int i = 0;
int j = 0;
final Object[] newSlots = new Object[Integer.bitCount(newSlotMap) + Integer.bitCount(newLeafMap)];
while (newSlotMap != 0) {
if ((oldSlotMap & newSlotMap & 1) == 1) {
newSlots[j] = slots[i];
}
if ((oldSlotMap & 1) == 1) {
i += 1;
}
if ((newSlotMap & 1) == 1) {
j += 1;
}
oldSlotMap >>>= 1;
newSlotMap >>>= 1;
}
i = slots.length - 1;
j = newSlots.length - 1;
while (newLeafMap != 0) {
if ((oldLeafMap & newLeafMap & 1) == 1) {
newSlots[j] = slots[i];
}
if ((oldLeafMap & 1) == 1) {
i -= 1;
}
if ((newLeafMap & 1) == 1) {
j -= 1;
}
oldLeafMap >>>= 1;
newLeafMap >>>= 1;
}
return new HashTrieMap<K, V>(treeMap, leafMap, newSlots);
}
}
static boolean containsKey(HashTrieMap<?, ?> tree, Object key, int keyHash, int shift) {
while (true) {
final int branch = tree.choose(keyHash, shift);
switch (tree.follow(branch)) {
case VOID:
return false;
case LEAF:
return key.equals(tree.getKey(branch));
case TREE:
tree = tree.getTree(branch);
shift += 5;
break;
case KNOT:
return tree.getKnot(branch).containsKey(key);
default:
throw new AssertionError();
}
}
}
static <K, V> Entry<K, V> head(HashTrieMap<K, V> tree) {
loop: while (true) {
int treeMap = tree.treeMap;
int leafMap = tree.leafMap;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
return new AbstractMap.SimpleImmutableEntry<K, V>(tree.keyAt(0), tree.valueAt(0));
case TREE:
tree = tree.treeAt(0);
continue loop;
case KNOT:
return tree.knotAt(0).head();
default:
throw new AssertionError();
}
treeMap >>>= 1;
leafMap >>>= 1;
}
return null;
}
}
static <K> K headKey(HashTrieMap<K, ?> tree) {
loop: while (true) {
int treeMap = tree.treeMap;
int leafMap = tree.leafMap;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
return tree.keyAt(0);
case TREE:
tree = tree.treeAt(0);
continue loop;
case KNOT:
return tree.knotAt(0).headKey();
default:
throw new AssertionError();
}
treeMap >>>= 1;
leafMap >>>= 1;
}
return null;
}
}
static <V> V headValue(HashTrieMap<?, V> tree) {
loop: while (true) {
int treeMap = tree.treeMap;
int leafMap = tree.leafMap;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
return tree.valueAt(0);
case TREE:
tree = tree.treeAt(0);
continue loop;
case KNOT:
return tree.knotAt(0).headValue();
default:
throw new AssertionError();
}
treeMap >>>= 1;
leafMap >>>= 1;
}
return null;
}
}
Entry<K, V> next(Object key, int keyHash, int shift) {
final int block;
if (key == null) {
block = 0;
} else {
block = (keyHash >>> shift) & 0x1F;
}
int branch = 1 << block;
int treeMap = this.treeMap >>> block;
int leafMap = this.leafMap >>> block;
Map.Entry<K, V> next;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
if (key == null) {
return new AbstractMap.SimpleImmutableEntry<K, V>(getKey(branch), getValue(branch));
}
break;
case TREE:
next = getTree(branch).next(key, keyHash, shift + 5);
if (next != null) {
return next;
}
break;
case KNOT:
next = getKnot(branch).next(key);
if (next != null) {
return next;
}
break;
default:
throw new AssertionError();
}
key = null;
keyHash = 0;
treeMap >>>= 1;
leafMap >>>= 1;
branch <<= 1;
}
return null;
}
K nextKey(Object key, int keyHash, int shift) {
final int block;
if (key == null) {
block = 0;
} else {
block = (keyHash >>> shift) & 0x1F;
}
int branch = 1 << block;
int treeMap = this.treeMap >>> block;
int leafMap = this.leafMap >>> block;
K next;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
if (key == null) {
return getKey(branch);
}
break;
case TREE:
next = getTree(branch).nextKey(key, keyHash, shift + 5);
if (next != null) {
return next;
}
break;
case KNOT:
next = getKnot(branch).nextKey(key);
if (next != null) {
return next;
}
break;
default:
throw new AssertionError();
}
key = null;
keyHash = 0;
treeMap >>>= 1;
leafMap >>>= 1;
branch <<= 1;
}
return null;
}
V nextValue(Object key, int keyHash, int shift) {
final int block;
if (key == null) {
block = 0;
} else {
block = (keyHash >>> shift) & 0x1F;
}
int branch = 1 << block;
int treeMap = this.treeMap >>> block;
int leafMap = this.leafMap >>> block;
V next;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
if (key == null) {
return getValue(branch);
}
break;
case TREE:
next = getTree(branch).nextValue(key, keyHash, shift + 5);
if (next != null) {
return next;
}
break;
case KNOT:
next = getKnot(branch).nextValue(key);
if (next != null) {
return next;
}
break;
default:
throw new AssertionError();
}
key = null;
keyHash = 0;
treeMap >>>= 1;
leafMap >>>= 1;
branch <<= 1;
}
return null;
}
static <V> V get(HashTrieMap<?, V> tree, Object key, int keyHash, int shift) {
while (true) {
final int branch = tree.choose(keyHash, shift);
switch (tree.follow(branch)) {
case VOID:
return null;
case LEAF:
if (key.equals(tree.getKey(branch))) {
return tree.getValue(branch);
} else {
return null;
}
case TREE:
tree = tree.getTree(branch);
shift += 5;
break;
case KNOT:
return tree.getKnot(branch).get(key);
default:
throw new AssertionError();
}
}
}
HashTrieMap<K, V> updated(K key, int keyHash, V value, int shift) {
final int branch = choose(keyHash, shift);
switch (follow(branch)) {
case VOID:
return remap(treeMap, leafMap | branch).setLeaf(branch, key, value);
case LEAF:
final K leaf = getKey(branch);
final int leafHash = Murmur3.hash(leaf);
if (keyHash == leafHash && key.equals(leaf)) {
final V v = getValue(branch);
if (value == null ? v == null : value.equals(v)) {
return this;
} else {
return remap(treeMap, leafMap).setLeaf(branch, key, value);
}
} else if (keyHash != leafHash) {
return remap(treeMap | branch, leafMap ^ branch)
.setTree(branch, merge(leaf, leafHash, getValue(branch), key, keyHash, value, shift + 5));
} else {
return remap(treeMap | branch, leafMap)
.setKnot(branch, new ArrayMap<K, V>(leaf, getValue(branch), key, value));
}
case TREE:
final HashTrieMap<K, V> oldTree = getTree(branch);
final HashTrieMap<K, V> newTree = oldTree.updated(key, keyHash, value, shift + 5);
if (oldTree == newTree) {
return this;
} else {
return remap(treeMap, leafMap).setTree(branch, newTree);
}
case KNOT:
final ArrayMap<K, V> oldKnot = getKnot(branch);
final ArrayMap<K, V> newKnot = oldKnot.updated(key, value);
if (oldKnot == newKnot) {
return this;
} else {
return remap(treeMap, leafMap).setKnot(branch, newKnot);
}
default:
throw new AssertionError();
}
}
HashTrieMap<K, V> merge(K key0, int hash0, V value0, K key1, int hash1, V value1, int shift) {
// assume(hash0 != hash1)
final int branch0 = choose(hash0, shift);
final int branch1 = choose(hash1, shift);
final int slotMap = branch0 | branch1;
if (branch0 == branch1) {
final Object[] slots = new Object[1];
slots[0] = merge(key0, hash0, value0, key1, hash1, value1, shift + 5);
return new HashTrieMap<K, V>(slotMap, 0, slots);
} else {
final Object[] slots = new Object[4];
if (((branch0 - 1) & branch1) == 0) {
slots[0] = key0;
slots[1] = key1;
slots[2] = value1;
slots[3] = value0;
} else {
slots[0] = key1;
slots[1] = key0;
slots[2] = value0;
slots[3] = value1;
}
return new HashTrieMap<K, V>(0, slotMap, slots);
}
}
HashTrieMap<K, V> removed(Object key, int keyHash, int shift) {
final int branch = choose(keyHash, shift);
switch (follow(branch)) {
case VOID:
return this;
case LEAF:
if (!key.equals(getKey(branch))) {
return this;
} else {
return remap(treeMap, leafMap ^ branch);
}
case TREE:
final HashTrieMap<K, V> oldTree = getTree(branch);
final HashTrieMap<K, V> newTree = oldTree.removed(key, keyHash, shift + 5);
if (oldTree == newTree) {
return this;
} else if (newTree.isEmpty()) {
return remap(treeMap ^ branch, leafMap);
} else if (newTree.isUnary()) {
return remap(treeMap ^ branch, leafMap | branch)
.setLeaf(branch, newTree.unaryKey(), newTree.unaryValue());
} else {
return remap(treeMap, leafMap).setTree(branch, newTree);
}
case KNOT:
final ArrayMap<K, V> oldKnot = getKnot(branch);
final ArrayMap<K, V> newKnot = oldKnot.removed(key);
if (oldKnot == newKnot) {
return this;
} else if (newKnot.isEmpty()) {
return remap(treeMap ^ branch, leafMap);
} else if (newKnot.isUnary()) {
return remap(treeMap ^ branch, leafMap | branch)
.setLeaf(branch, newKnot.unaryKey(), newKnot.unaryValue());
} else {
return remap(treeMap, leafMap).setKnot(branch, newKnot);
}
default:
throw new AssertionError();
}
}
@Override
public Set<Entry<K, V>> entrySet() {
return new HashTrieMapEntrySet<K, V>(this);
}
@Override
public Set<K> keySet() {
return new HashTrieMapKeySet<K, V>(this);
}
@Override
public Collection<V> values() {
return new HashTrieMapValues<K, V>(this);
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new HashTrieMapEntryIterator<K, V>(this);
}
public Iterator<K> keyIterator() {
return new HashTrieMapKeyIterator<K, V>(this);
}
public Iterator<V> valueIterator() {
return new HashTrieMapValueIterator<K, V>(this);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof HashTrieMap<?, ?>) {
final HashTrieMap<K, V> that = (HashTrieMap<K, V>) other;
if (size() == that.size()) {
final Iterator<Entry<K, V>> those = that.iterator();
while (those.hasNext()) {
final Entry<K, V> entry = those.next();
final V value = get(entry.getKey());
final V v = entry.getValue();
if (value == null ? v != null : !value.equals(v)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(HashTrieMap.class);
}
int a = 0;
int b = 0;
int c = 1;
final Iterator<Entry<K, V>> these = iterator();
while (these.hasNext()) {
final Entry<K, V> entry = these.next();
final int h = Murmur3.mix(Murmur3.hash(entry.getKey()), Murmur3.hash(entry.getValue()));
a ^= h;
b += h;
if (h != 0) {
c *= h;
}
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, a), b), c));
}
@Override
public void debug(Output<?> output) {
output = output.write("HashTrieMap").write('.');
final Iterator<Entry<K, V>> these = iterator();
if (these.hasNext()) {
Entry<K, V> entry = these.next();
output = output.write("of").write('(')
.debug(entry.getKey()).write(", ").debug(entry.getValue());
while (these.hasNext()) {
entry = these.next();
output = output.write(')').write('.').write("updated").write('(')
.debug(entry.getKey()).write(", ").debug(entry.getValue());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
static final int VOID = 0;
static final int LEAF = 1;
static final int TREE = 2;
static final int KNOT = 3;
private static HashTrieMap<Object, Object> empty;
@SuppressWarnings("unchecked")
public static <K, V> HashTrieMap<K, V> empty() {
if (empty == null) {
empty = new HashTrieMap<Object, Object>(0, 0, new Object[0]);
}
return (HashTrieMap<K, V>) empty;
}
public static <K, V> HashTrieMap<K, V> of(K key, V value) {
return HashTrieMap.<K, V>empty().updated(key, value);
}
public static <K, V> HashTrieMap<K, V> from(Map<? extends K, ? extends V> map) {
HashTrieMap<K, V> trie = empty();
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
trie = trie.updated(entry.getKey(), entry.getValue());
}
return trie;
}
public static <K, V> HashTrieMap<K, HashTrieSet<V>> updated(HashTrieMap<K, HashTrieSet<V>> multimap, K key, V value) {
HashTrieSet<V> set = multimap.get(key);
if (set == null) {
set = HashTrieSet.empty();
}
set = set.added(value);
multimap = multimap.updated(key, set);
return multimap;
}
public static <K, V> HashTrieMap<K, HashTrieSet<V>> merged(HashTrieMap<K, HashTrieSet<V>> multimap, HashTrieMap<K, HashTrieSet<V>> that) {
final Iterator<Entry<K, HashTrieSet<V>>> entries = that.iterator();
while (entries.hasNext()) {
final Entry<K, HashTrieSet<V>> entry = entries.next();
HashTrieSet<V> these = multimap.get(entry.getKey());
if (these != null) {
these = these.merged(entry.getValue());
} else {
these = entry.getValue();
}
multimap = multimap.updated(entry.getKey(), these);
}
return multimap;
}
public static <K, V> HashTrieMap<K, HashTrieSet<V>> removed(HashTrieMap<K, HashTrieSet<V>> multimap, K key, V value) {
HashTrieSet<V> set = multimap.get(key);
if (set == null) {
return multimap;
}
set = set.removed(value);
if (set.isEmpty()) {
multimap = multimap.removed(key);
} else {
multimap = multimap.updated(key, set);
}
return multimap;
}
}
abstract class HashTrieMapIterator<K, V> {
final Object[] nodes;
int depth;
final int[] stack;
int stackPointer;
HashTrieMapIterator(HashTrieMap<K, V> tree) {
nodes = new Object[8];
depth = 0;
stack = new int[32];
stackPointer = 0;
setNode(tree);
setSlotIndex(0);
setLeafIndex(0);
setTreeMap(tree.treeMap);
setLeafMap(tree.leafMap);
}
final Object getNode() {
return nodes[depth];
}
final void setNode(Object node) {
nodes[depth] = node;
}
final int getSlotIndex() {
return stack[stackPointer];
}
final void setSlotIndex(int index) {
stack[stackPointer] = index;
}
final int getLeafIndex() {
return stack[stackPointer + 1];
}
final void setLeafIndex(int index) {
stack[stackPointer + 1] = index;
}
final int getTreeMap() {
return stack[stackPointer + 2];
}
final void setTreeMap(int treeMap) {
stack[stackPointer + 2] = treeMap;
}
final int getLeafMap() {
return stack[stackPointer + 3];
}
final void setLeafMap(int leafMap) {
stack[stackPointer + 3] = leafMap;
}
final int follow(int treeMap, int leafMap) {
return leafMap & 1 | (treeMap & 1) << 1;
}
final void push(HashTrieMap<K, V> tree) {
depth += 1;
setNode(tree);
stackPointer += 4;
setSlotIndex(0);
setLeafIndex(0);
setTreeMap(tree.treeMap);
setLeafMap(tree.leafMap);
}
final void push(ArrayMap<K, V> knot) {
depth += 1;
setNode(knot);
stackPointer += 4;
setSlotIndex(0);
}
final void pop() {
setNode(null);
depth -= 1;
setSlotIndex(0);
setLeafIndex(0);
setTreeMap(0);
setLeafMap(0);
stackPointer -= 4;
setSlotIndex(getSlotIndex() + 1);
setTreeMap(getTreeMap() >>> 1);
setLeafMap(getLeafMap() >>> 1);
}
@SuppressWarnings("unchecked")
public boolean hasNext() {
while (true) {
final Object node = getNode();
if (node instanceof HashTrieMap<?, ?>) {
final HashTrieMap<K, V> tree = (HashTrieMap<K, V>) node;
final int treeMap = getTreeMap();
final int leafMap = getLeafMap();
if ((treeMap | leafMap) != 0) {
switch (follow(treeMap, leafMap)) {
case HashTrieMap.VOID:
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
break;
case HashTrieMap.LEAF:
return true;
case HashTrieMap.TREE:
push(tree.treeAt(getSlotIndex()));
break;
case HashTrieMap.KNOT:
push(tree.knotAt(getSlotIndex()));
break;
default:
throw new AssertionError();
}
} else if (depth > 0) {
pop();
} else {
return false;
}
} else if (node instanceof ArrayMap<?, ?>) {
final ArrayMap<K, V> knot = (ArrayMap<K, V>) node;
if (getSlotIndex() < knot.size()) {
return true;
} else {
pop();
}
} else {
throw new AssertionError();
}
}
}
@SuppressWarnings("unchecked")
protected Map.Entry<K, V> nextEntry() {
while (true) {
final Object node = getNode();
if (node instanceof HashTrieMap<?, ?>) {
final HashTrieMap<K, V> tree = (HashTrieMap<K, V>) node;
final int treeMap = getTreeMap();
final int leafMap = getLeafMap();
final int slotMap = treeMap | leafMap;
if (slotMap != 0) {
switch (follow(treeMap, leafMap)) {
case HashTrieMap.VOID:
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
break;
case HashTrieMap.LEAF:
final int slotIndex = getSlotIndex();
final int leafIndex = getLeafIndex();
final K key = tree.keyAt(slotIndex);
final V value = tree.valueAt(leafIndex);
setSlotIndex(slotIndex + 1);
setLeafIndex(leafIndex + 1);
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
return new AbstractMap.SimpleImmutableEntry<K, V>(key, value);
case HashTrieMap.TREE:
push(tree.treeAt(getSlotIndex()));
break;
case HashTrieMap.KNOT:
push(tree.knotAt(getSlotIndex()));
break;
default:
throw new AssertionError();
}
} else if (depth > 0) {
pop();
} else {
throw new NoSuchElementException();
}
} else if (node instanceof ArrayMap<?, ?>) {
final ArrayMap<K, V> knot = (ArrayMap<K, V>) node;
final int slotIndex = getSlotIndex();
if (slotIndex < knot.size()) {
final K key = knot.keyAt(slotIndex);
final V value = knot.valueAt(slotIndex);
setSlotIndex(slotIndex + 1);
return new AbstractMap.SimpleImmutableEntry<K, V>(key, value);
} else {
pop();
}
} else {
throw new AssertionError();
}
}
}
@SuppressWarnings("unchecked")
protected K nextKey() {
while (true) {
final Object node = getNode();
if (node instanceof HashTrieMap<?, ?>) {
final HashTrieMap<K, V> tree = (HashTrieMap<K, V>) node;
final int treeMap = getTreeMap();
final int leafMap = getLeafMap();
final int slotMap = treeMap | leafMap;
if (slotMap != 0) {
switch (follow(treeMap, leafMap)) {
case HashTrieMap.VOID:
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
break;
case HashTrieMap.LEAF:
final int slotIndex = getSlotIndex();
final K key = tree.keyAt(slotIndex);
setSlotIndex(slotIndex + 1);
setLeafIndex(getLeafIndex() + 1);
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
return key;
case HashTrieMap.TREE:
push(tree.treeAt(getSlotIndex()));
break;
case HashTrieMap.KNOT:
push(tree.knotAt(getSlotIndex()));
break;
default:
throw new AssertionError();
}
} else if (depth > 0) {
pop();
} else {
throw new NoSuchElementException();
}
} else if (node instanceof ArrayMap<?, ?>) {
final ArrayMap<K, V> knot = (ArrayMap<K, V>) node;
final int slotIndex = getSlotIndex();
if (slotIndex < knot.size()) {
final K key = knot.keyAt(slotIndex);
setSlotIndex(slotIndex + 1);
return key;
} else {
pop();
}
} else {
throw new AssertionError();
}
}
}
@SuppressWarnings("unchecked")
protected V nextValue() {
while (true) {
final Object node = getNode();
if (node instanceof HashTrieMap<?, ?>) {
final HashTrieMap<K, V> tree = (HashTrieMap<K, V>) node;
final int treeMap = getTreeMap();
final int leafMap = getLeafMap();
final int slotMap = treeMap | leafMap;
if (slotMap != 0) {
switch (follow(treeMap, leafMap)) {
case HashTrieMap.VOID:
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
break;
case HashTrieMap.LEAF:
final int leafIndex = getLeafIndex();
final V value = tree.valueAt(leafIndex);
setSlotIndex(getSlotIndex() + 1);
setLeafIndex(leafIndex + 1);
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
return value;
case HashTrieMap.TREE:
push(tree.treeAt(getSlotIndex()));
break;
case HashTrieMap.KNOT:
push(tree.knotAt(getSlotIndex()));
break;
default:
throw new AssertionError();
}
} else if (depth > 0) {
pop();
} else {
throw new NoSuchElementException();
}
} else if (node instanceof ArrayMap<?, ?>) {
final ArrayMap<K, V> knot = (ArrayMap<K, V>) node;
final int slotIndex = getSlotIndex();
if (slotIndex < knot.size()) {
final V value = knot.valueAt(slotIndex);
setSlotIndex(slotIndex + 1);
return value;
} else {
pop();
}
} else {
throw new AssertionError();
}
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
final class HashTrieMapEntryIterator<K, V> extends HashTrieMapIterator<K, V> implements Iterator<Map.Entry<K, V>> {
HashTrieMapEntryIterator(HashTrieMap<K, V> tree) {
super(tree);
}
@Override
public Map.Entry<K, V> next() {
return nextEntry();
}
}
final class HashTrieMapKeyIterator<K, V> extends HashTrieMapIterator<K, V> implements Iterator<K> {
HashTrieMapKeyIterator(HashTrieMap<K, V> tree) {
super(tree);
}
@Override
public K next() {
return nextKey();
}
}
final class HashTrieMapValueIterator<K, V> extends HashTrieMapIterator<K, V> implements Iterator<V> {
HashTrieMapValueIterator(HashTrieMap<K, V> tree) {
super(tree);
}
@Override
public V next() {
return nextValue();
}
}
final class HashTrieMapEntrySet<K, V> extends AbstractSet<Map.Entry<K, V>> {
final HashTrieMap<K, V> map;
HashTrieMapEntrySet(HashTrieMap<K, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return map.iterator();
}
}
final class HashTrieMapKeySet<K, V> extends AbstractSet<K> {
final HashTrieMap<K, V> map;
HashTrieMapKeySet(HashTrieMap<K, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public Iterator<K> iterator() {
return map.keyIterator();
}
}
final class HashTrieMapValues<K, V> extends AbstractCollection<V> {
final HashTrieMap<K, V> map;
HashTrieMapValues(HashTrieMap<K, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public Iterator<V> iterator() {
return map.valueIterator();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/HashTrieSet.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.collections;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Murmur3;
public final class HashTrieSet<T> implements Set<T>, Debug {
final int treeMap;
final int leafMap;
final Object[] slots;
HashTrieSet(int treeMap, int leafMap, Object[] slots) {
this.treeMap = treeMap;
this.leafMap = leafMap;
this.slots = slots;
}
@Override
public boolean isEmpty() {
return slotMap() == 0;
}
@Override
public int size() {
int t = 0;
int i = 0;
int treeMap = this.treeMap;
int leafMap = this.leafMap;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
t += 1;
i += 1;
break;
case TREE:
t += treeAt(i).size();
i += 1;
break;
case KNOT:
t += knotAt(i).size();
i += 1;
break;
default:
throw new AssertionError();
}
treeMap >>>= 1;
leafMap >>>= 1;
}
return t;
}
@Override
public boolean contains(Object elem) {
if (elem != null) {
return contains(this, elem, Murmur3.hash(elem), 0);
} else {
return false;
}
}
@Override
public boolean containsAll(Collection<?> elems) {
for (Object elem : elems) {
if (!contains(elem)) {
return false;
}
}
return true;
}
public T head() {
return head(this);
}
public T next(Object elem) {
T next = next(elem, Murmur3.hash(elem), 0);
if (next == null) {
next = head(this);
}
return next;
}
@Override
public boolean add(T elem) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends T> elems) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object elem) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> elems) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> elems) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
public HashTrieSet<T> added(T elem) {
return updated(elem, Murmur3.hash(elem), 0);
}
public HashTrieSet<T> added(Collection<? extends T> elems) {
HashTrieSet<T> these = this;
for (T elem : elems) {
these = these.added(elem);
}
return these;
}
public HashTrieSet<T> merged(HashTrieSet<T> elems) {
HashTrieSet<T> these = this;
final Iterator<T> iter = elems.iterator();
while (iter.hasNext()) {
these = these.added(iter.next());
}
return these;
}
public HashTrieSet<T> removed(T elem) {
if (elem != null) {
return removed(elem, Murmur3.hash(elem), 0);
} else {
return this;
}
}
int slotMap() {
return treeMap | leafMap;
}
int choose(int hash, int shift) {
return 1 << ((hash >>> shift) & 0x1F);
}
int select(int branch) {
return Integer.bitCount(slotMap() & (branch - 1));
}
int follow(int branch) {
return ((leafMap & branch) != 0 ? 1 : 0) | ((treeMap & branch) != 0 ? 2 : 0);
}
@SuppressWarnings("unchecked")
T leafAt(int index) {
return (T) slots[index];
}
@SuppressWarnings("unchecked")
T getLeaf(int branch) {
return (T) slots[select(branch)];
}
HashTrieSet<T> setLeaf(int branch, T leaf) {
slots[select(branch)] = leaf;
return this;
}
@SuppressWarnings("unchecked")
HashTrieSet<T> treeAt(int index) {
return (HashTrieSet<T>) slots[index];
}
@SuppressWarnings("unchecked")
HashTrieSet<T> getTree(int branch) {
return (HashTrieSet<T>) slots[select(branch)];
}
HashTrieSet<T> setTree(int branch, HashTrieSet<T> tree) {
slots[select(branch)] = tree;
return this;
}
@SuppressWarnings("unchecked")
ArraySet<T> knotAt(int index) {
return (ArraySet<T>) slots[index];
}
@SuppressWarnings("unchecked")
ArraySet<T> getKnot(int branch) {
return (ArraySet<T>) slots[select(branch)];
}
HashTrieSet<T> setKnot(int branch, ArraySet<T> knot) {
slots[select(branch)] = knot;
return this;
}
boolean isUnary() {
return treeMap == 0 && Integer.bitCount(leafMap) == 1;
}
@SuppressWarnings("unchecked")
T unaryElem() {
return (T) slots[0];
}
HashTrieSet<T> remap(int treeMap, int leafMap) {
int oldSlotMap = this.treeMap | this.leafMap;
int newSlotMap = treeMap | leafMap;
if (oldSlotMap == newSlotMap) {
return new HashTrieSet<T>(treeMap, leafMap, slots.clone());
} else {
int i = 0;
int j = 0;
final Object[] newSlots = new Object[Integer.bitCount(newSlotMap)];
while (newSlotMap != 0) {
if ((oldSlotMap & newSlotMap & 1) == 1) {
newSlots[j] = slots[i];
}
if ((oldSlotMap & 1) == 1) {
i += 1;
}
if ((newSlotMap & 1) == 1) {
j += 1;
}
oldSlotMap >>>= 1;
newSlotMap >>>= 1;
}
return new HashTrieSet<T>(treeMap, leafMap, newSlots);
}
}
static boolean contains(HashTrieSet<?> tree, Object elem, int elemHash, int shift) {
while (true) {
final int branch = tree.choose(elemHash, shift);
switch (tree.follow(branch)) {
case VOID:
return false;
case LEAF:
return elem.equals(tree.getLeaf(branch));
case TREE:
tree = tree.getTree(branch);
shift += 5;
break;
case KNOT:
return tree.getKnot(branch).contains(elem);
default:
throw new AssertionError();
}
}
}
static <T> T head(HashTrieSet<T> tree) {
loop: while (true) {
int treeMap = tree.treeMap;
int leafMap = tree.leafMap;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
return tree.leafAt(0);
case TREE:
tree = tree.treeAt(0);
continue loop;
case KNOT:
return tree.knotAt(0).head();
default:
throw new AssertionError();
}
treeMap >>>= 1;
leafMap >>>= 1;
}
return null;
}
}
T next(Object elem, int elemHash, int shift) {
final int block;
if (elem == null) {
block = 0;
} else {
block = (elemHash >>> shift) & 0x1F;
}
int branch = 1 << block;
int treeMap = this.treeMap >>> block;
int leafMap = this.leafMap >>> block;
T next;
while ((treeMap | leafMap) != 0) {
switch (leafMap & 1 | (treeMap & 1) << 1) {
case VOID:
break;
case LEAF:
if (elem == null) {
return getLeaf(branch);
}
break;
case TREE:
next = getTree(branch).next(elem, elemHash, shift + 5);
if (next != null) {
return next;
}
break;
case KNOT:
next = getKnot(branch).next(elem);
if (next != null) {
return next;
}
break;
default:
throw new AssertionError();
}
elem = null;
elemHash = 0;
treeMap >>>= 1;
leafMap >>>= 1;
branch <<= 1;
}
return null;
}
HashTrieSet<T> updated(T elem, int elemHash, int shift) {
final int branch = choose(elemHash, shift);
switch (follow(branch)) {
case VOID:
return remap(treeMap, leafMap | branch).setLeaf(branch, elem);
case LEAF:
final T leaf = getLeaf(branch);
final int leafHash = Murmur3.hash(leaf);
if (elemHash == leafHash && elem.equals(leaf)) {
return this;
} else if (elemHash != leafHash) {
return remap(treeMap | branch, leafMap ^ branch)
.setTree(branch, merge(leaf, leafHash, elem, elemHash, shift + 5));
} else {
return remap(treeMap | branch, leafMap)
.setKnot(branch, new ArraySet<T>(leaf, elem));
}
case TREE:
final HashTrieSet<T> oldTree = getTree(branch);
final HashTrieSet<T> newTree = oldTree.updated(elem, elemHash, shift + 5);
if (oldTree == newTree) {
return this;
} else {
return remap(treeMap, leafMap).setTree(branch, newTree);
}
case KNOT:
final ArraySet<T> oldKnot = getKnot(branch);
final ArraySet<T> newKnot = oldKnot.added(elem);
if (oldKnot == newKnot) {
return this;
} else {
return remap(treeMap, leafMap).setKnot(branch, newKnot);
}
default:
throw new AssertionError();
}
}
HashTrieSet<T> merge(T elem0, int hash0, T elem1, int hash1, int shift) {
// assume(hash0 != hash1)
final int branch0 = choose(hash0, shift);
final int branch1 = choose(hash1, shift);
final int slotMap = branch0 | branch1;
if (branch0 == branch1) {
final Object[] slots = new Object[1];
slots[0] = merge(elem0, hash0, elem1, hash1, shift + 5);
return new HashTrieSet<T>(slotMap, 0, slots);
} else {
final Object[] slots = new Object[2];
if (((branch0 - 1) & branch1) == 0) {
slots[0] = elem0;
slots[1] = elem1;
} else {
slots[0] = elem1;
slots[1] = elem0;
}
return new HashTrieSet<T>(0, slotMap, slots);
}
}
HashTrieSet<T> removed(T elem, int elemHash, int shift) {
final int branch = choose(elemHash, shift);
switch (follow(branch)) {
case VOID:
return this;
case LEAF:
if (!elem.equals(getLeaf(branch))) {
return this;
} else {
return remap(treeMap, leafMap ^ branch);
}
case TREE:
final HashTrieSet<T> oldTree = getTree(branch);
final HashTrieSet<T> newTree = oldTree.removed(elem, elemHash, shift + 5);
if (oldTree == newTree) {
return this;
} else if (newTree.isEmpty()) {
return remap(treeMap ^ branch, leafMap);
} else if (newTree.isUnary()) {
return remap(treeMap ^ branch, leafMap | branch).setLeaf(branch, newTree.unaryElem());
} else {
return remap(treeMap, leafMap).setTree(branch, newTree);
}
case KNOT:
final ArraySet<T> oldKnot = getKnot(branch);
final ArraySet<T> newKnot = oldKnot.removed(elem);
if (oldKnot == newKnot) {
return this;
} else if (newKnot.isEmpty()) {
return remap(treeMap ^ branch, leafMap);
} else if (newKnot.isUnary()) {
return remap(treeMap ^ branch, leafMap | branch).setLeaf(branch, newKnot.unaryElem());
} else {
return remap(treeMap, leafMap).setKnot(branch, newKnot);
}
default:
throw new AssertionError();
}
}
@Override
public Object[] toArray() {
int i = 0;
final Object[] array = new Object[size()];
final Iterator<T> iter = iterator();
while (iter.hasNext()) {
array[i] = iter.next();
i += 1;
}
return array;
}
@SuppressWarnings("unchecked")
@Override
public <U> U[] toArray(U[] array) {
int i = 0;
final int n = size();
if (array.length < n) {
array = (U[]) Array.newInstance(array.getClass().getComponentType(), n);
}
final Iterator<T> iter = iterator();
while (iter.hasNext()) {
array[i] = (U) iter.next();
i += 1;
}
if (array.length > n) {
array[n] = null;
}
return array;
}
@Override
public Iterator<T> iterator() {
return new HashTrieSetIterator<T>(this);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Set<?>) {
final Set<?> that = (Set<?>) other;
if (size() == that.size()) {
final Iterator<?> those = that.iterator();
while (those.hasNext()) {
if (!contains(those.next())) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
int code = 0;
final Iterator<T> these = iterator();
while (these.hasNext()) {
final T next = these.next();
code += next == null ? 0 : next.hashCode();
}
return code;
}
@Override
public void debug(Output<?> output) {
output = output.write("HashTrieSet").write('.');
final Iterator<T> these = iterator();
if (these.hasNext()) {
output = output.write("of").write('(').debug(these.next());
while (these.hasNext()) {
output = output.write(", ").debug(these.next());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
static final int VOID = 0;
static final int LEAF = 1;
static final int TREE = 2;
static final int KNOT = 3;
private static HashTrieSet<Object> empty;
@SuppressWarnings("unchecked")
public static <T> HashTrieSet<T> empty() {
if (empty == null) {
empty = new HashTrieSet<Object>(0, 0, new Object[0]);
}
return (HashTrieSet<T>) empty;
}
@SuppressWarnings("unchecked")
public static <T> HashTrieSet<T> of(T... elems) {
HashTrieSet<T> trie = empty();
for (T elem : elems) {
trie = trie.added(elem);
}
return trie;
}
public static <T> HashTrieSet<T> from(Iterable<? extends T> elems) {
HashTrieSet<T> trie = empty();
for (T elem : elems) {
trie = trie.added(elem);
}
return trie;
}
}
final class HashTrieSetIterator<T> implements Iterator<T> {
final Object[] nodes;
int depth;
final int[] stack;
int stackPointer;
HashTrieSetIterator(HashTrieSet<T> tree) {
nodes = new Object[8];
depth = 0;
stack = new int[24];
stackPointer = 0;
setNode(tree);
setSlotIndex(0);
setTreeMap(tree.treeMap);
setLeafMap(tree.leafMap);
}
Object getNode() {
return nodes[depth];
}
void setNode(Object node) {
nodes[depth] = node;
}
int getSlotIndex() {
return stack[stackPointer];
}
void setSlotIndex(int index) {
stack[stackPointer] = index;
}
int getTreeMap() {
return stack[stackPointer + 1];
}
void setTreeMap(int treeMap) {
stack[stackPointer + 1] = treeMap;
}
int getLeafMap() {
return stack[stackPointer + 2];
}
void setLeafMap(int leafMap) {
stack[stackPointer + 2] = leafMap;
}
int follow(int treeMap, int leafMap) {
return leafMap & 1 | (treeMap & 1) << 1;
}
void push(HashTrieSet<T> tree) {
depth += 1;
setNode(tree);
stackPointer += 3;
setSlotIndex(0);
setTreeMap(tree.treeMap);
setLeafMap(tree.leafMap);
}
void push(ArraySet<T> knot) {
depth += 1;
setNode(knot);
stackPointer += 3;
setSlotIndex(0);
}
void pop() {
setNode(null);
depth -= 1;
setSlotIndex(0);
setTreeMap(0);
setLeafMap(0);
stackPointer -= 3;
setSlotIndex(getSlotIndex() + 1);
setTreeMap(getTreeMap() >>> 1);
setLeafMap(getLeafMap() >>> 1);
}
@SuppressWarnings("unchecked")
@Override
public boolean hasNext() {
while (true) {
final Object node = getNode();
if (node instanceof HashTrieSet<?>) {
final HashTrieSet<T> tree = (HashTrieSet<T>) node;
final int treeMap = getTreeMap();
final int leafMap = getLeafMap();
if ((treeMap | leafMap) != 0) {
switch (follow(treeMap, leafMap)) {
case HashTrieSet.VOID:
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
break;
case HashTrieSet.LEAF:
return true;
case HashTrieSet.TREE:
push(tree.treeAt(getSlotIndex()));
break;
case HashTrieSet.KNOT:
push(tree.knotAt(getSlotIndex()));
break;
default:
throw new AssertionError();
}
} else if (depth > 0) {
pop();
} else {
return false;
}
} else if (node instanceof ArraySet<?>) {
final ArraySet<T> knot = (ArraySet<T>) node;
if (getSlotIndex() < knot.size()) {
return true;
} else {
pop();
}
} else {
throw new AssertionError();
}
}
}
@SuppressWarnings("unchecked")
@Override
public T next() {
while (true) {
final Object node = getNode();
if (node instanceof HashTrieSet<?>) {
final HashTrieSet<T> tree = (HashTrieSet<T>) node;
final int treeMap = getTreeMap();
final int leafMap = getLeafMap();
final int slotMap = treeMap | leafMap;
if (slotMap != 0) {
switch (follow(treeMap, leafMap)) {
case HashTrieSet.VOID:
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
break;
case HashTrieSet.LEAF:
final int slotIndex = getSlotIndex();
final T elem = tree.leafAt(slotIndex);
setSlotIndex(slotIndex + 1);
setTreeMap(treeMap >>> 1);
setLeafMap(leafMap >>> 1);
return elem;
case HashTrieSet.TREE:
push(tree.treeAt(getSlotIndex()));
break;
case HashTrieSet.KNOT:
push(tree.knotAt(getSlotIndex()));
break;
default:
throw new AssertionError();
}
} else if (depth > 0) {
pop();
} else {
throw new NoSuchElementException();
}
} else if (node instanceof ArraySet<?>) {
final ArraySet<T> knot = (ArraySet<T>) node;
final int slotIndex = getSlotIndex();
if (slotIndex < knot.size()) {
final T elem = knot.elemAt(slotIndex);
setSlotIndex(slotIndex + 1);
return elem;
} else {
pop();
}
} else {
throw new AssertionError();
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/STree.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.collections;
import java.lang.reflect.Array;
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ThreadLocalRandom;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Cursor;
import swim.util.KeyedList;
import swim.util.Murmur3;
public class STree<T> extends STreeContext<T> implements KeyedList<T>, Cloneable, Debug {
STreePage<T> root;
protected STree(STreePage<T> root) {
this.root = root;
}
public STree() {
this(STreePage.<T>empty());
}
@Override
public boolean isEmpty() {
return this.root.isEmpty();
}
@Override
public int size() {
return this.root.size();
}
@Override
public boolean contains(Object value) {
return this.root.contains(value);
}
@Override
public boolean containsAll(Collection<?> values) {
final STreePage<T> root = this.root;
for (Object value : values) {
if (!root.contains(value)) {
return false;
}
}
return true;
}
@Override
public int indexOf(Object value) {
return this.root.indexOf(value);
}
@Override
public int lastIndexOf(Object value) {
return this.root.lastIndexOf(value);
}
@Override
public T get(int index) {
return get(index, null);
}
@Override
public T get(int index, Object key) {
if (key != null) {
index = lookup(index, key);
if (index < 0) {
return null;
}
}
return this.root.get(index);
}
@Override
public Map.Entry<Object, T> getEntry(int index) {
return getEntry(index, null);
}
@Override
public Map.Entry<Object, T> getEntry(int index, Object key) {
if (key != null) {
index = lookup(index, key);
if (index < 0) {
return null;
}
}
return this.root.getEntry(index);
}
@Override
public T set(int index, T newValue) {
return set(index, newValue, null);
}
@Override
public T set(int index, T newValue, Object key) {
if (key != null) {
index = lookup(index, key);
if (index < 0) {
throw new NoSuchElementException(key.toString());
}
}
final STreePage<T> oldRoot = this.root;
if (index < 0 || index >= oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
final STreePage<T> newRoot = oldRoot.updated(index, newValue, this);
if (oldRoot != newRoot) {
this.root = newRoot;
return oldRoot.get(index);
} else {
return null;
}
}
@Override
public boolean add(T newValue) {
return add(newValue, null);
}
@Override
public boolean add(T newValue, Object key) {
this.root = this.root.appended(newValue, key, this).balanced(this);
return true;
}
@Override
public boolean addAll(Collection<? extends T> newValues) {
boolean modified = false;
for (T newValue : newValues) {
add(newValue);
modified = true;
}
return modified;
}
@Override
public void add(int index, T newValue) {
add(index, newValue, null);
}
@Override
public void add(int index, T newValue, Object key) {
final STreePage<T> oldRoot = this.root;
if (index < 0 || index > oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
this.root = oldRoot.inserted(index, newValue, key, this).balanced(this);
}
@Override
public boolean addAll(int index, Collection<? extends T> newValues) {
boolean modified = false;
for (T newValue : newValues) {
add(index, newValue);
index += 1;
modified = true;
}
return modified;
}
@Override
public T remove(int index) {
return remove(index, null);
}
@Override
public T remove(int index, Object key) {
if (key != null) {
index = lookup(index, key);
if (index < 0) {
return null;
}
}
final STreePage<T> oldRoot = this.root;
if (index < 0 || index > oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
final STreePage<T> newRoot = oldRoot.removed(index, this);
if (oldRoot != newRoot) {
this.root = newRoot;
return oldRoot.get(index);
} else {
return null;
}
}
@Override
public boolean remove(Object value) {
final STreePage<T> oldRoot = this.root;
final STreePage<T> newRoot = oldRoot.removed(value, this);
if (oldRoot != newRoot) {
this.root = newRoot;
return true;
} else {
return false;
}
}
@Override
public boolean removeAll(Collection<?> values) {
final STreePage<T> oldRoot = this.root;
STreePage<T> newRoot = oldRoot;
int n = newRoot.size();
int i = 0;
while (i < n) {
final T value = newRoot.get(i);
if (values.contains(value)) {
newRoot = newRoot.removed(i, this);
n -= 1;
} else {
i += 1;
}
}
if (oldRoot != newRoot) {
this.root = newRoot;
return true;
} else {
return false;
}
}
@Override
public boolean retainAll(Collection<?> values) {
final STreePage<T> oldRoot = this.root;
STreePage<T> newRoot = oldRoot;
int n = newRoot.size();
int i = 0;
while (i < n) {
final T value = newRoot.get(i);
if (!values.contains(value)) {
newRoot = newRoot.removed(i, this);
n -= 1;
} else {
i += 1;
}
}
if (oldRoot != newRoot) {
this.root = newRoot;
return true;
} else {
return false;
}
}
@Override
public void move(int fromIndex, int toIndex) {
move(fromIndex, toIndex, null);
}
@Override
public void move(int fromIndex, int toIndex, Object key) {
if (key != null) {
fromIndex = lookup(fromIndex, key);
if (fromIndex < 0) {
throw new NoSuchElementException(key.toString());
}
}
final STreePage<T> oldRoot = this.root;
if (fromIndex < 0 || fromIndex >= oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(fromIndex));
}
if (toIndex < 0 || toIndex >= oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(toIndex));
}
if (fromIndex != toIndex) {
final Map.Entry<Object, T> entry = oldRoot.getEntry(fromIndex);
this.root = oldRoot.removed(fromIndex, this)
.inserted(toIndex, entry.getValue(), entry.getKey(), this)
.balanced(this);
}
}
public void drop(int lower) {
final STreePage<T> oldRoot = this.root;
if (lower > 0 && oldRoot.size() > 0) {
if (lower < oldRoot.size()) {
this.root = oldRoot.drop(lower, this);
} else {
this.root = STreePage.empty();
}
}
}
public void take(int upper) {
final STreePage<T> oldRoot = this.root;
if (upper < oldRoot.size() && oldRoot.size() > 0) {
if (upper > 0) {
this.root = oldRoot.take(upper, this);
} else {
this.root = STreePage.empty();
}
}
}
public void clear() {
this.root = STreePage.empty();
}
@Override
public Object[] toArray() {
final STreePage<T> root = this.root;
final int n = root.size();
final Object[] array = new Object[n];
root.copyToArray(array, 0);
return array;
}
@SuppressWarnings("unchecked")
@Override
public <U> U[] toArray(U[] array) {
final STreePage<T> root = this.root;
final int n = root.size();
if (array.length < n) {
array = (U[]) Array.newInstance(array.getClass().getComponentType(), n);
}
root.copyToArray(array, 0);
if (array.length > n) {
array[n] = null;
}
return array;
}
@Override
public Cursor<T> iterator() {
return this.root.iterator();
}
@Override
public Cursor<T> listIterator() {
return this.root.iterator();
}
@Override
public Cursor<T> listIterator(int index) {
final Cursor<T> cursor = listIterator();
cursor.skip(index);
return cursor;
}
@Override
public Cursor<Object> keyIterator() {
return this.root.keyIterator();
}
@Override
public Cursor<Map.Entry<Object, T>> entryIterator() {
return this.root.entryIterator();
}
public Cursor<T> reverseIterator() {
return this.root.reverseIterator();
}
public Cursor<Object> reverseKeyIterator() {
return this.root.reverseKeyIterator();
}
public Cursor<Map.Entry<Object, T>> reverseEntryIterator() {
return this.root.reverseEntryIterator();
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
return new STreeSubList<T>(this, fromIndex, toIndex);
}
public STree<T> clone() {
return copy(this.root);
}
protected STree<T> copy(STreePage<T> root) {
return new STree<T>(root);
}
@SuppressWarnings("unchecked")
protected Object identify(T value) {
return ThreadLocalRandom.current().nextLong();
}
@SuppressWarnings("unchecked")
protected int compare(Object x, Object y) {
return ((Comparable<Object>) x).compareTo(y);
}
protected int pageSplitSize() {
return 32;
}
protected boolean pageShouldSplit(STreePage<T> page) {
return page.arity() > pageSplitSize();
}
protected boolean pageShouldMerge(STreePage<T> page) {
return page.arity() < pageSplitSize() >>> 1;
}
protected int lookup(int start, Object key) {
final STreePage<T> root = this.root;
start = Math.min(Math.max(0, start), root.size() - 1);
if (start > -1) { // when root.size() is 0
int index = start;
do {
final Map.Entry<Object, T> entry = root.getEntry(index);
if (entry != null && compare(entry.getKey(), key) == 0) {
return index;
}
index = (index + 1) % root.size();
} while (index != start);
}
return -1;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof STree<?>) {
final STree<T> that = (STree<T>) other;
if (this.size() == that.size()) {
final Cursor<T> these = iterator();
final Cursor<T> those = that.iterator();
while (these.hasNext() && those.hasNext()) {
final T x = these.next();
final T y = those.next();
if (x == null ? y != null : !x.equals(y)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(STree.class);
}
int h = hashSeed;
final Cursor<T> these = iterator();
while (these.hasNext()) {
h = Murmur3.mix(h, Murmur3.hash(these.next()));
}
return Murmur3.mash(h);
}
@Override
public void debug(Output<?> output) {
output = output.write("STree").write('.');
final Cursor<T> these = iterator();
if (these.hasNext()) {
output = output.write("of").write('(').debug(these.next());
while (these.hasNext()) {
output = output.write(", ").debug(these.next());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static <T> STree<T> empty() {
return new STree<T>();
}
@SuppressWarnings("unchecked")
public static <T> STree<T> of(T... values) {
final STree<T> tree = new STree<T>();
for (T value : values) {
tree.add(value);
}
return tree;
}
}
final class STreeSubList<T> extends AbstractList<T> {
final STree<T> inner;
final int fromIndex;
final int toIndex;
STreeSubList(STree<T> inner, int fromIndex, int toIndex) {
this.inner = inner;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
}
@Override
public int size() {
return this.toIndex - this.fromIndex;
}
@Override
public T get(int index) {
final int i = this.fromIndex + index;
if (i < this.fromIndex || i >= this.toIndex) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
return this.inner.get(i);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
fromIndex += this.fromIndex;
toIndex += this.fromIndex;
if (toIndex > this.toIndex) {
throw new IndexOutOfBoundsException();
}
return new STreeSubList<T>(this.inner, fromIndex, toIndex);
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/STreeContext.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.collections;
import java.util.concurrent.ThreadLocalRandom;
public abstract class STreeContext<T> {
@SuppressWarnings("unchecked")
protected Object identify(T value) {
final byte[] bytes = new byte[6];
ThreadLocalRandom.current().nextBytes(bytes);
return bytes;
}
@SuppressWarnings("unchecked")
protected int compare(Object x, Object y) {
return ((Comparable<Object>) x).compareTo(y);
}
protected int pageSplitSize() {
return 32;
}
protected boolean pageShouldSplit(STreePage<T> page) {
return page.arity() > pageSplitSize();
}
protected boolean pageShouldMerge(STreePage<T> page) {
return page.arity() < pageSplitSize() >>> 1;
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/STreeLeaf.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.collections;
import java.util.AbstractMap;
import java.util.Map;
import swim.util.Cursor;
final class STreeLeaf<T> extends STreePage<T> {
final Map.Entry<Object, T>[] slots;
STreeLeaf(Map.Entry<Object, T>[] slots) {
this.slots = slots;
}
@Override
public boolean isEmpty() {
return this.slots.length == 0;
}
@Override
public int size() {
return this.slots.length;
}
@Override
public int arity() {
return this.slots.length;
}
@Override
public boolean contains(Object value) {
final Map.Entry<Object, T>[] slots = this.slots;
for (int i = 0, n = slots.length; i < n; i += 1) {
if (value.equals(slots[i])) {
return true;
}
}
return false;
}
@Override
public int indexOf(Object value) {
final Map.Entry<Object, T>[] slots = this.slots;
for (int i = 0, n = slots.length; i < n; i += 1) {
if (value.equals(slots[i])) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object value) {
final Map.Entry<Object, T>[] slots = this.slots;
for (int i = slots.length - 1; i >= 0; i -= 1) {
if (value.equals(slots[i])) {
return i;
}
}
return -1;
}
@Override
public T get(int index) {
final Map.Entry<Object, T> slot = this.slots[index];
if (slot != null) {
return slot.getValue();
} else {
return null;
}
}
@Override
public Map.Entry<Object, T> getEntry(int index) {
return this.slots[index];
}
@Override
public STreeLeaf<T> updated(int index, T newValue, STreeContext<T> tree) {
if (index < 0 || index >= this.slots.length) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
return updatedSlot(index, newValue);
}
@SuppressWarnings("unchecked")
private STreeLeaf<T> updatedSlot(int index, T newValue) {
final Map.Entry<Object, T>[] oldSlots = this.slots;
final Map.Entry<Object, T> oldSlot = oldSlots[index];
if (newValue != oldSlot.getValue()) {
final int n = oldSlots.length;
final Map.Entry<Object, T>[] newSlots = (Map.Entry<Object, T>[]) new Map.Entry<?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, n);
newSlots[index] = new AbstractMap.SimpleImmutableEntry<Object, T>(oldSlot.getKey(), newValue);
return new STreeLeaf<T>(newSlots);
} else {
return this;
}
}
@Override
public STreeLeaf<T> inserted(int index, T newValue, Object id, STreeContext<T> tree) {
if (index < 0 || index > this.slots.length) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
return insertedSlot(index, newValue, id, tree);
}
@SuppressWarnings("unchecked")
private STreeLeaf<T> insertedSlot(int index, T newValue, Object id, STreeContext<T> tree) {
if (id == null) {
id = tree.identify(newValue);
}
final Map.Entry<Object, T>[] oldSlots = this.slots;
final int n = oldSlots.length + 1;
final Map.Entry<Object, T>[] newSlots = (Map.Entry<Object, T>[]) new Map.Entry<?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, index);
newSlots[index] = new AbstractMap.SimpleImmutableEntry<Object, T>(id, newValue);
System.arraycopy(oldSlots, index, newSlots, index + 1, n - (index + 1));
return new STreeLeaf<T>(newSlots);
}
@Override
public STreeLeaf<T> removed(int index, STreeContext<T> tree) {
if (index < 0 || index >= this.slots.length) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
if (this.slots.length > 1) {
return removedSlot(index);
} else {
return STreeLeaf.empty();
}
}
@SuppressWarnings("unchecked")
private STreeLeaf<T> removedSlot(int index) {
final Map.Entry<Object, T>[] oldSlots = this.slots;
final int n = oldSlots.length - 1;
final Map.Entry<Object, T>[] newSlots = (Map.Entry<Object, T>[]) new Map.Entry<?, ?>[n];
System.arraycopy(oldSlots, 0, newSlots, 0, index);
System.arraycopy(oldSlots, index + 1, newSlots, index, n - index);
return new STreeLeaf<T>(newSlots);
}
@Override
public STreeLeaf<T> removed(Object object, STreeContext<T> tree) {
final int index = indexOf(object);
if (index >= 0) {
if (this.slots.length > 1) {
return removedSlot(index);
} else {
return STreeLeaf.empty();
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public STreeLeaf<T> drop(int lower, STreeContext<T> tree) {
if (lower > 0) {
final Map.Entry<Object, T>[] oldSlots = this.slots;
final int k = oldSlots.length;
if (lower < k) {
final int n = k - lower;
final Map.Entry<Object, T>[] newSlots = (Map.Entry<Object, T>[]) new Map.Entry<?, ?>[n];
System.arraycopy(oldSlots, lower, newSlots, 0, n);
return new STreeLeaf<T>(newSlots);
} else {
return STreeLeaf.empty();
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public STreeLeaf<T> take(int upper, STreeContext<T> tree) {
final Map.Entry<Object, T>[] oldSlots = this.slots;
if (upper < oldSlots.length) {
if (upper > 0) {
final Map.Entry<Object, T>[] newSlots = (Map.Entry<Object, T>[]) new Map.Entry<?, ?>[upper];
System.arraycopy(oldSlots, 0, newSlots, 0, upper);
return new STreeLeaf<T>(newSlots);
} else {
return STreeLeaf.empty();
}
} else {
return this;
}
}
@Override
public STreePage<T> balanced(STreeContext<T> tree) {
final int n = this.slots.length;
if (n > 1 && tree.pageShouldSplit(this)) {
final int x = n >>> 1;
return split(x);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public STreeNode<T> split(int x) {
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[2];
final STreeLeaf<T> newLeftPage = splitLeft(x);
final STreeLeaf<T> newRightPage = splitRight(x);
newPages[0] = newLeftPage;
newPages[1] = newRightPage;
final int[] newKnots = new int[1];
newKnots[0] = x;
return new STreeNode<T>(newPages, newKnots, this.slots.length);
}
@SuppressWarnings("unchecked")
@Override
public STreeLeaf<T> splitLeft(int x) {
final Map.Entry<Object, T>[] oldSlots = this.slots;
final Map.Entry<Object, T>[] newSlots = (Map.Entry<Object, T>[]) new Map.Entry<?, ?>[x];
System.arraycopy(oldSlots, 0, newSlots, 0, x);
return new STreeLeaf<T>(newSlots);
}
@SuppressWarnings("unchecked")
@Override
public STreeLeaf<T> splitRight(int x) {
final Map.Entry<Object, T>[] oldSlots = this.slots;
final int y = oldSlots.length - x;
final Map.Entry<Object, T>[] newSlots = (Map.Entry<Object, T>[]) new Map.Entry<?, ?>[y];
System.arraycopy(oldSlots, x, newSlots, 0, y);
return new STreeLeaf<T>(newSlots);
}
@Override
public void copyToArray(Object[] array, int offset) {
final Map.Entry<Object, T>[] slots = this.slots;
for (int i = 0, n = slots.length; i < n; i += 1) {
array[offset + i] = slots[i].getValue();
}
}
@Override
public Cursor<Map.Entry<Object, T>> entryIterator() {
return Cursor.array(this.slots);
}
@Override
public Cursor<Map.Entry<Object, T>> reverseEntryIterator() {
return Cursor.array(this.slots, this.slots.length);
}
private static STreeLeaf<Object> empty;
@SuppressWarnings("unchecked")
public static <T> STreeLeaf<T> empty() {
if (empty == null) {
empty = new STreeLeaf<Object>((Map.Entry<Object, Object>[]) new Map.Entry<?, ?>[0]);
}
return (STreeLeaf<T>) empty;
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/STreeList.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.collections;
import java.lang.reflect.Array;
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Cursor;
import swim.util.KeyedList;
import swim.util.Murmur3;
/**
* Mutable, thread-safe {@link KeyedList} backed by an S-Tree.
*/
public class STreeList<T> extends STreeContext<T> implements KeyedList<T>, Cloneable, Debug {
volatile STreePage<T> root;
protected STreeList(STreePage<T> root) {
this.root = root;
}
public STreeList() {
this(STreePage.<T>empty());
}
@Override
public boolean isEmpty() {
return this.root.isEmpty();
}
@Override
public int size() {
return this.root.size();
}
@Override
public boolean contains(Object value) {
return this.root.contains(value);
}
@Override
public boolean containsAll(Collection<?> values) {
final STreePage<T> root = this.root;
for (Object value : values) {
if (!root.contains(value)) {
return false;
}
}
return true;
}
@Override
public int indexOf(Object value) {
return this.root.indexOf(value);
}
@Override
public int lastIndexOf(Object value) {
return this.root.lastIndexOf(value);
}
@Override
public T get(int index) {
return get(index, null);
}
@Override
public T get(int index, Object key) {
if (key != null) {
index = lookup(index, key);
if (index < 0) {
return null;
}
}
return this.root.get(index);
}
@Override
public Map.Entry<Object, T> getEntry(int index) {
return getEntry(index, null);
}
@Override
public Map.Entry<Object, T> getEntry(int index, Object key) {
if (key != null) {
index = lookup(index, key);
if (index < 0) {
return null;
}
}
return size() <= index ? null : this.root.getEntry(index);
}
@Override
public T set(int index, T newValue) {
return set(index, newValue, null);
}
@Override
public T set(int index, T newValue, Object key) {
if (key != null) {
index = lookup(index, key);
if (index < 0) {
throw new NoSuchElementException(key.toString());
}
}
do {
final STreePage<T> oldRoot = this.root;
if (index < 0 || index >= oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
final STreePage<T> newRoot = oldRoot.updated(index, newValue, this);
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return oldRoot.get(index);
}
} else {
return null;
}
} while (true);
}
@Override
public boolean add(T newValue) {
return add(newValue, null);
}
@Override
public boolean add(T newValue, Object key) {
do {
final STreePage<T> oldRoot = this.root;
final STreePage<T> newRoot = oldRoot.appended(newValue, key, this).balanced(this);
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return true;
}
} while (true);
}
@Override
public boolean addAll(Collection<? extends T> newValues) {
boolean modified = false;
for (T newValue : newValues) {
add(newValue);
modified = true;
}
return modified;
}
@Override
public void add(int index, T newValue) {
add(index, newValue, null);
}
@Override
public void add(int index, T newValue, Object key) {
do {
final STreePage<T> oldRoot = this.root;
if (index < 0 || index > oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
final STreePage<T> newRoot = oldRoot.inserted(index, newValue, key, this).balanced(this);
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return;
}
} while (true);
}
@Override
public boolean addAll(int index, Collection<? extends T> newValues) {
boolean modified = false;
for (T newValue : newValues) {
add(index, newValue);
index += 1;
modified = true;
}
return modified;
}
@Override
public T remove(int index) {
return remove(index, null);
}
@Override
public T remove(int index, Object key) {
if (key != null) {
index = lookup(index, key);
if (index < 0) {
return null;
}
}
do {
final STreePage<T> oldRoot = this.root;
if (index < 0 || index > oldRoot.size()) {
return null;
}
final STreePage<T> newRoot = oldRoot.removed(index, this);
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return oldRoot.get(index);
}
} else {
return null;
}
} while (true);
}
@Override
public boolean remove(Object value) {
do {
final STreePage<T> oldRoot = this.root;
final STreePage<T> newRoot = oldRoot.removed(value, this);
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return true;
}
} else {
return false;
}
} while (true);
}
@Override
public boolean removeAll(Collection<?> values) {
do {
final STreePage<T> oldRoot = this.root;
STreePage<T> newRoot = oldRoot;
int n = newRoot.size();
int i = 0;
while (i < n) {
final T value = newRoot.get(i);
if (values.contains(value)) {
newRoot = newRoot.removed(i, this);
n -= 1;
} else {
i += 1;
}
}
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return true;
}
} else {
return false;
}
} while (true);
}
@Override
public boolean retainAll(Collection<?> values) {
do {
final STreePage<T> oldRoot = this.root;
STreePage<T> newRoot = oldRoot;
int n = newRoot.size();
int i = 0;
while (i < n) {
final T value = newRoot.get(i);
if (!values.contains(value)) {
newRoot = newRoot.removed(i, this);
n -= 1;
} else {
i += 1;
}
}
if (oldRoot != newRoot) {
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
return true;
}
} else {
return false;
}
} while (true);
}
@Override
public void move(int fromIndex, int toIndex) {
move(fromIndex, toIndex, null);
}
@Override
public void move(int fromIndex, int toIndex, Object key) {
if (key != null) {
fromIndex = lookup(fromIndex, key);
if (fromIndex < 0) {
throw new NoSuchElementException(key.toString());
}
}
do {
final STreePage<T> oldRoot = this.root;
if (fromIndex < 0 || fromIndex >= oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(fromIndex));
}
if (toIndex < 0 || toIndex >= oldRoot.size()) {
throw new IndexOutOfBoundsException(Integer.toString(toIndex));
}
if (fromIndex != toIndex) {
final Map.Entry<Object, T> entry = oldRoot.getEntry(fromIndex);
final STreePage<T> newRoot = oldRoot.removed(fromIndex, this)
.inserted(toIndex, entry.getValue(), entry.getKey(), this)
.balanced(this);
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
break;
}
} else {
break;
}
} while (true);
}
public void drop(int lower) {
do {
final STreePage<T> oldRoot = this.root;
if (lower > 0 && oldRoot.size() > 0) {
final STreePage<T> newRoot;
if (lower < oldRoot.size()) {
newRoot = oldRoot.drop(lower, this);
} else {
newRoot = STreePage.<T>empty();
}
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
break;
}
} else {
break;
}
} while (true);
}
public void take(int keep) {
do {
final STreePage<T> oldRoot = this.root;
if (keep < oldRoot.size() && oldRoot.size() > 0) {
final STreePage<T> newRoot;
if (keep > 0) {
newRoot = oldRoot.take(keep, this);
} else {
newRoot = STreePage.<T>empty();
}
if (ROOT.compareAndSet(this, oldRoot, newRoot)) {
break;
}
} else {
break;
}
} while (true);
}
public void clear() {
STreePage<T> oldRoot;
do {
oldRoot = this.root;
} while (!ROOT.compareAndSet(this, oldRoot, STreePage.<T>empty()));
}
@Override
public Object[] toArray() {
final STreePage<T> root = this.root;
final int n = root.size();
final Object[] array = new Object[n];
root.copyToArray(array, 0);
return array;
}
@SuppressWarnings("unchecked")
@Override
public <U> U[] toArray(U[] array) {
final STreePage<T> root = this.root;
final int n = root.size();
if (array.length < n) {
array = (U[]) Array.newInstance(array.getClass().getComponentType(), n);
}
root.copyToArray(array, 0);
if (array.length > n) {
array[n] = null;
}
return array;
}
@Override
public Cursor<T> iterator() {
return this.root.iterator();
}
@Override
public Cursor<T> listIterator() {
return this.root.iterator();
}
@Override
public Cursor<T> listIterator(int index) {
final Cursor<T> cursor = listIterator();
cursor.skip(index);
return cursor;
}
@Override
public Cursor<Object> keyIterator() {
return this.root.keyIterator();
}
@Override
public Cursor<Map.Entry<Object, T>> entryIterator() {
return this.root.entryIterator();
}
public Cursor<T> reverseIterator() {
return this.root.reverseIterator();
}
public Cursor<Object> reverseKeyIterator() {
return this.root.reverseKeyIterator();
}
public Cursor<Map.Entry<Object, T>> reverseEntryIterator() {
return this.root.reverseEntryIterator();
}
public STree<T> snapshot() {
return new STree<T>(this.root);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
return new STreeListSubList<T>(this, fromIndex, toIndex);
}
public STree<T> clone() {
return copy(this.root);
}
protected STree<T> copy(STreePage<T> root) {
return new STree<T>(root);
}
protected int lookup(int start, Object key) {
final STreePage<T> root = this.root;
start = Math.min(Math.max(0, start), root.size() - 1);
if (start > -1) { // when root.size() is 0
int index = start;
do {
final Map.Entry<Object, T> entry = root.getEntry(index);
if (entry != null && compare(entry.getKey(), key) == 0) {
return index;
}
index = (index + 1) % root.size();
} while (index != start);
}
return -1;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof STree<?>) {
final STree<T> that = (STree<T>) other;
if (this.size() == that.size()) {
final Cursor<T> these = iterator();
final Cursor<T> those = that.iterator();
while (these.hasNext() && those.hasNext()) {
final T x = these.next();
final T y = those.next();
if (x == null ? y != null : !x.equals(y)) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(STree.class);
}
int h = hashSeed;
final Cursor<T> these = iterator();
while (these.hasNext()) {
h = Murmur3.mix(h, Murmur3.hash(these.next()));
}
return Murmur3.mash(h);
}
@Override
public void debug(Output<?> output) {
output = output.write("STreeList").write('.');
final Cursor<T> these = iterator();
if (these.hasNext()) {
output = output.write("of").write('(').debug(these.next());
while (these.hasNext()) {
output = output.write(", ").debug(these.next());
}
} else {
output = output.write("empty").write('(');
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static <T> STreeList<T> empty() {
return new STreeList<T>();
}
@SuppressWarnings("unchecked")
public static <T> STree<T> of(T... values) {
final STree<T> tree = new STree<T>();
for (T value : values) {
tree.add(value);
}
return tree;
}
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<STreeList, STreePage> ROOT =
AtomicReferenceFieldUpdater.newUpdater(STreeList.class, STreePage.class, "root");
}
final class STreeListSubList<T> extends AbstractList<T> {
final STreeList<T> inner;
final int fromIndex;
final int toIndex;
STreeListSubList(STreeList<T> inner, int fromIndex, int toIndex) {
this.inner = inner;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
}
@Override
public int size() {
return this.toIndex - this.fromIndex;
}
@Override
public T get(int index) {
final int i = this.fromIndex + index;
if (i < this.fromIndex || i >= this.toIndex) {
throw new IndexOutOfBoundsException(Integer.toString(index));
}
return this.inner.get(i);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
if (fromIndex > toIndex) {
throw new IllegalArgumentException();
}
fromIndex += this.fromIndex;
toIndex += this.fromIndex;
if (toIndex > this.toIndex) {
throw new IndexOutOfBoundsException();
}
return new STreeListSubList<T>(this.inner, fromIndex, toIndex);
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/STreeNode.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.collections;
import java.util.Map;
import swim.util.Cursor;
final class STreeNode<T> extends STreePage<T> {
final STreePage<T>[] pages;
final int[] knots;
final int size;
STreeNode(STreePage<T>[] pages, int[] knots, int size) {
this.pages = pages;
if (knots == null || size < 0) {
knots = new int[pages.length - 1];
size = 0;
for (int i = 0, n = knots.length; i < n; i += 1) {
size += pages[i].size();
knots[i] = size;
}
size += pages[knots.length].size();
}
this.knots = knots;
this.size = size;
}
STreeNode(STreePage<T>[] pages) {
this(pages, null, -1);
}
@Override
public boolean isEmpty() {
return this.size == 0;
}
@Override
public int size() {
return this.size;
}
@Override
public int arity() {
return this.pages.length;
}
@Override
public boolean contains(Object value) {
final STreePage<T>[] pages = this.pages;
for (int i = 0, n = pages.length; i < n; i += 1) {
if (pages[i].contains(value)) {
return true;
}
}
return false;
}
@Override
public int indexOf(Object object) {
final STreePage<T>[] pages = this.pages;
int k = 0;
for (int x = 0, n = pages.length; x < n; x += 1) {
final STreePage<T> page = pages[x];
final int i = page.indexOf(object);
if (i >= 0) {
return k + i;
}
k += page.size();
}
return -1;
}
@Override
public int lastIndexOf(Object object) {
final STreePage<T>[] pages = this.pages;
int k = this.size;
for (int x = pages.length - 1; x >= 0; x -= 1) {
final STreePage<T> page = pages[x];
final int i = page.lastIndexOf(object);
k -= page.size();
if (i >= 0) {
return k + 1;
}
}
return -1;
}
@Override
public T get(int index) {
int x = lookup(index);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final int i = x == 0 ? index : index - this.knots[x - 1];
return this.pages[x].get(i);
}
@Override
public Map.Entry<Object, T> getEntry(int index) {
int x = lookup(index);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final int i = x == 0 ? index : index - this.knots[x - 1];
return this.pages[x].getEntry(i);
}
@Override
public STreeNode<T> updated(int index, T newValue, STreeContext<T> tree) {
int x = lookup(index);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final int i = x == 0 ? index : index - this.knots[x - 1];
final STreePage<T> oldPage = this.pages[x];
final STreePage<T> newPage = oldPage.updated(i, newValue, tree);
if (oldPage != newPage) {
if (oldPage.size() != newPage.size() && tree.pageShouldSplit(newPage)) {
return updatedPageSplit(x, newPage, oldPage);
} else {
return updatedPage(x, newPage, oldPage);
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
private STreeNode<T> updatedPage(int x, STreePage<T> newPage, STreePage<T> oldPage) {
final STreePage<T>[] oldPages = this.pages;
final int n = oldPages.length;
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[n];
System.arraycopy(oldPages, 0, newPages, 0, n);
newPages[x] = newPage;
final int[] oldKnots = this.knots;
final int[] newKnots;
int newSize;
if (n - 1 > 0) {
newKnots = new int[n - 1];
if (x > 0) {
System.arraycopy(oldKnots, 0, newKnots, 0, x);
newSize = oldKnots[x - 1];
} else {
newSize = 0;
}
for (int i = x; i < n - 1; i += 1) {
newSize += newPages[i].size();
newKnots[i] = newSize;
}
newSize += newPages[n - 1].size();
} else {
newKnots = new int[0];
newSize = 0;
}
return new STreeNode<T>(newPages, newKnots, newSize);
}
@SuppressWarnings("unchecked")
private STreeNode<T> updatedPageSplit(int x, STreePage<T> newPage, STreePage<T> oldPage) {
final STreePage<T>[] oldPages = this.pages;
final int n = oldPages.length + 1;
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[n];
System.arraycopy(oldPages, 0, newPages, 0, x);
final int y = newPage.arity() >>> 1;
final STreePage<T> newLeftPage = newPage.splitLeft(y);
final STreePage<T> newRightPage = newPage.splitRight(y);
newPages[x] = newLeftPage;
newPages[x + 1] = newRightPage;
System.arraycopy(oldPages, x + 1, newPages, x + 2, n - (x + 2));
return new STreeNode<T>(newPages);
}
@SuppressWarnings("unchecked")
private STreeNode<T> updatedPageMerge(int x, STreeNode<T> newPage, STreePage<T> oldPage) {
final STreePage<T>[] oldPages = this.pages;
final STreePage<T>[] midPages = newPage.pages;
final int k = midPages.length;
final int n = oldPages.length + (k - 1);
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[n];
System.arraycopy(oldPages, 0, newPages, 0, x);
System.arraycopy(midPages, 0, newPages, x, k);
System.arraycopy(oldPages, x + 1, newPages, x + k, n - (x + k));
return new STreeNode<T>(newPages);
}
@Override
public STreeNode<T> inserted(int index, T newValue, Object id, STreeContext<T> tree) {
int x = lookup(index);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final int i = x == 0 ? index : index - this.knots[x - 1];
final STreePage<T> oldPage = this.pages[x];
final STreePage<T> newPage = oldPage.inserted(i, newValue, id, tree);
if (oldPage != newPage) {
if (tree.pageShouldSplit(newPage)) {
return updatedPageSplit(x, newPage, oldPage);
} else {
return updatedPage(x, newPage, oldPage);
}
} else {
return this;
}
}
@Override
public STreePage<T> removed(int index, STreeContext<T> tree) {
int x = lookup(index);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final int i = x == 0 ? index : index - this.knots[x - 1];
final STreePage<T> oldPage = this.pages[x];
final STreePage<T> newPage = oldPage.removed(i, tree);
if (oldPage != newPage) {
return replacedPage(x, newPage, oldPage, tree);
} else {
return this;
}
}
private STreePage<T> replacedPage(int x, STreePage<T> newPage,
STreePage<T> oldPage, STreeContext<T> tree) {
if (!newPage.isEmpty()) {
if (newPage instanceof STreeNode<?> && tree.pageShouldMerge(newPage)) {
return updatedPageMerge(x, (STreeNode<T>) newPage, oldPage);
} else {
return updatedPage(x, newPage, oldPage);
}
} else if (this.pages.length > 2) {
return removedPage(x, newPage, oldPage);
} else if (this.pages.length > 1) {
if (x == 0) {
return this.pages[1];
} else {
return this.pages[0];
}
} else {
return STreeLeaf.empty();
}
}
@SuppressWarnings("unchecked")
private STreeNode<T> removedPage(int x, STreePage<T> newPage, STreePage<T> oldPage) {
final STreePage<T>[] oldPages = this.pages;
final int n = oldPages.length - 1;
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[n];
System.arraycopy(oldPages, 0, newPages, 0, x);
System.arraycopy(oldPages, x + 1, newPages, x, n - x);
final int[] oldKnots = this.knots;
final int[] newKnots = new int[n - 1];
int newSize;
if (x > 0) {
System.arraycopy(oldKnots, 0, newKnots, 0, x);
newSize = oldKnots[x - 1];
} else {
newSize = 0;
}
for (int i = x; i < n - 1; i += 1) {
newSize += newPages[i].size();
newKnots[i] = newSize;
}
newSize += newPages[n - 1].size();
return new STreeNode<T>(newPages, newKnots, newSize);
}
@Override
public STreePage<T> removed(Object value, STreeContext<T> tree) {
final STreePage<T>[] pages = this.pages;
for (int x = 0, n = pages.length; x < n; x += 1) {
final STreePage<T> oldPage = pages[x];
final STreePage<T> newPage = oldPage.removed(value, tree);
if (oldPage != newPage) {
return replacedPage(x, newPage, oldPage, tree);
}
}
return this;
}
@SuppressWarnings("unchecked")
@Override
public STreePage<T> drop(int lower, STreeContext<T> tree) {
if (lower > 0) {
if (lower < this.size) {
int x = lookup(lower);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final int i = x == 0 ? lower : lower - this.knots[x - 1];
final STreePage<T>[] oldPages = this.pages;
final int k = oldPages.length;
final int n = k - x;
if (n > 1) {
final STreeNode<T> newNode;
if (x > 0) {
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[n];
System.arraycopy(oldPages, x, newPages, 0, n);
newNode = new STreeNode<T>(newPages);
} else {
newNode = this;
}
if (i > 0) {
final STreePage<T> oldPage = oldPages[x];
final STreePage<T> newPage = oldPage.drop(i, tree);
return newNode.replacedPage(0, newPage, oldPage, tree);
} else {
return newNode;
}
} else {
return oldPages[x].drop(i, tree);
}
} else {
return STreeLeaf.empty();
}
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public STreePage<T> take(int upper, STreeContext<T> tree) {
if (upper < this.size) {
if (upper > 0) {
int x = lookup(upper);
if (x >= 0) {
x += 1;
} else {
x = -(x + 1);
}
final int i = x == 0 ? upper : upper - this.knots[x - 1];
final STreePage<T>[] oldPages = this.pages;
final int k = oldPages.length;
final int n = i == 0 ? x : x + 1;
if (n > 1) {
final STreeNode<T> newNode;
if (x < k) {
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[n];
System.arraycopy(oldPages, 0, newPages, 0, n);
final int[] newKnots = new int[n - 1];
System.arraycopy(this.knots, 0, newKnots, 0, n - 1);
final int newSize = newKnots[n - 2] + newPages[n - 1].size();
newNode = new STreeNode<T>(newPages, newKnots, newSize);
} else {
newNode = this;
}
if (i > 0) {
final STreePage<T> oldPage = oldPages[x];
final STreePage<T> newPage = oldPage.take(i, tree);
return newNode.replacedPage(x, newPage, oldPage, tree);
} else {
return newNode;
}
} else if (i > 0) {
return oldPages[0].take(i, tree);
} else {
return oldPages[0];
}
} else {
return STreeLeaf.empty();
}
} else {
return this;
}
}
@Override
public STreeNode<T> balanced(STreeContext<T> tree) {
if (this.pages.length > 1 && tree.pageShouldSplit(this)) {
final int x = this.knots.length >>> 1;
return split(x);
} else {
return this;
}
}
@SuppressWarnings("unchecked")
@Override
public STreeNode<T> split(int x) {
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[2];
final STreeNode<T> newLeftPage = splitLeft(x);
final STreeNode<T> newRightPage = splitRight(x);
newPages[0] = newLeftPage;
newPages[1] = newRightPage;
final int[] newKnots = new int[1];
newKnots[0] = newLeftPage.size();
return new STreeNode<T>(newPages, newKnots, this.size);
}
@SuppressWarnings("unchecked")
@Override
public STreeNode<T> splitLeft(int x) {
final STreePage<T>[] oldPages = this.pages;
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[x + 1];
System.arraycopy(oldPages, 0, newPages, 0, x + 1);
final int[] oldKnots = this.knots;
final int[] newKnots = new int[x];
System.arraycopy(oldKnots, 0, newKnots, 0, x);
int newSize = 0;
for (int i = 0; i <= x; i += 1) {
newSize += newPages[i].size();
}
return new STreeNode<T>(newPages, newKnots, newSize);
}
@SuppressWarnings("unchecked")
@Override
public STreeNode<T> splitRight(int x) {
final STreePage<T>[] oldPages = this.pages;
final int y = oldPages.length - (x + 1);
final STreePage<T>[] newPages = (STreePage<T>[]) new STreePage<?>[y];
System.arraycopy(oldPages, x + 1, newPages, 0, y);
final int[] newKnots = new int[y - 1];
int newSize;
if (y > 0) {
newSize = newPages[0].size();
for (int i = 1; i < y; i += 1) {
newKnots[i - 1] = newSize;
newSize += newPages[i].size();
}
} else {
newSize = 0;
}
return new STreeNode<T>(newPages, newKnots, newSize);
}
@Override
public void copyToArray(Object[] array, int offset) {
final STreePage<T>[] pages = this.pages;
for (int x = 0, n = pages.length; x < n; x += 1) {
final STreePage<T> page = pages[x];
page.copyToArray(array, offset);
offset += page.size();
}
}
@Override
public Cursor<Map.Entry<Object, T>> entryIterator() {
return new STreeNodeCursor<T>(this.pages);
}
@Override
public Cursor<Map.Entry<Object, T>> reverseEntryIterator() {
return new STreeNodeCursor<T>(this.pages, this.size, this.pages.length);
}
private int lookup(int index) {
int lo = 0;
int hi = this.knots.length - 1;
while (lo <= hi) {
final int mid = (lo + hi) >>> 1;
if (index > this.knots[mid]) {
lo = mid + 1;
} else if (index < this.knots[mid]) {
hi = mid - 1;
} else {
return mid;
}
}
return -(lo + 1);
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/STreeNodeCursor.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.collections;
import java.util.Map;
import java.util.NoSuchElementException;
import swim.util.Cursor;
final class STreeNodeCursor<T> implements Cursor<Map.Entry<Object, T>> {
final STreePage<T>[] pages;
long index;
int pageIndex;
Cursor<Map.Entry<Object, T>> pageCursor;
STreeNodeCursor(STreePage<T>[] pages, long index, int pageIndex, Cursor<Map.Entry<Object, T>> pageCursor) {
this.pages = pages;
this.index = index;
this.pageIndex = pageIndex;
this.pageCursor = pageCursor;
}
STreeNodeCursor(STreePage<T>[] pages, long index, int pageIndex) {
this(pages, index, pageIndex, null);
}
STreeNodeCursor(STreePage<T>[] pages) {
this(pages, 0L, 0, null);
}
long pageSize(STreePage<T> page) {
return page.size();
}
Cursor<Map.Entry<Object, T>> pageCursor(STreePage<T> page) {
return page.entryIterator();
}
Cursor<Map.Entry<Object, T>> reversePageCursor(STreePage<T> page) {
return page.reverseEntryIterator();
}
@Override
public boolean isEmpty() {
do {
if (this.pageCursor != null) {
if (!this.pageCursor.isEmpty()) {
return false;
} else {
this.pageCursor = null;
}
} else if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
return true;
}
} while (true);
}
@Override
public Map.Entry<Object, T> head() {
do {
if (this.pageCursor != null) {
if (!this.pageCursor.isEmpty()) {
return this.pageCursor.head();
} else {
this.pageCursor = null;
}
} else {
if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
throw new NoSuchElementException();
}
}
} while (true);
}
@Override
public void step() {
do {
if (this.pageCursor != null) {
if (!this.pageCursor.isEmpty()) {
this.index += 1L;
return;
} else {
this.pageCursor = null;
}
} else {
if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
throw new UnsupportedOperationException();
}
}
} while (true);
}
@Override
public void skip(long count) {
while (count > 0L) {
if (this.pageCursor != null) {
if (this.pageCursor.hasNext()) {
this.index += 1L;
count -= 1L;
this.pageCursor.next();
} else {
this.pageCursor = null;
}
} else if (this.pageIndex < this.pages.length) {
final STreePage<T> page = this.pages[this.pageIndex];
final long pageSize = pageSize(page);
this.pageIndex += 1;
if (pageSize < count) {
this.pageCursor = pageCursor(page);
if (count > 0L) {
this.index += count;
this.pageCursor.skip(count);
count = 0L;
}
break;
} else {
this.index += pageSize;
count -= pageSize;
}
} else {
break;
}
}
}
@Override
public boolean hasNext() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasNext()) {
return true;
} else {
this.pageCursor = null;
}
} else if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
return false;
}
} while (true);
}
@Override
public long nextIndexLong() {
return this.index;
}
@Override
public Map.Entry<Object, T> next() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasNext()) {
this.index += 1;
return this.pageCursor.next();
} else {
this.pageCursor = null;
}
} else {
if (this.pageIndex < this.pages.length) {
this.pageCursor = pageCursor(this.pages[this.pageIndex]);
this.pageIndex += 1;
} else {
this.pageIndex = this.pages.length;
throw new NoSuchElementException();
}
}
} while (true);
}
@Override
public boolean hasPrevious() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasPrevious()) {
return true;
} else {
this.pageCursor = null;
}
} else if (this.pageIndex > 0) {
this.pageCursor = reversePageCursor(this.pages[this.pageIndex - 1]);
this.pageIndex -= 1;
} else {
this.pageIndex = 0;
return false;
}
} while (true);
}
@Override
public long previousIndexLong() {
return this.index - 1L;
}
@Override
public Map.Entry<Object, T> previous() {
do {
if (this.pageCursor != null) {
if (this.pageCursor.hasPrevious()) {
this.index -= 1;
return this.pageCursor.previous();
} else {
this.pageCursor = null;
}
} else if (this.pageIndex > 0) {
this.pageCursor = reversePageCursor(this.pages[this.pageIndex - 1]);
this.pageIndex -= 1;
} else {
this.pageIndex = 0;
throw new NoSuchElementException();
}
} while (true);
}
@Override
public void set(Map.Entry<Object, T> newValue) {
this.pageCursor.set(newValue);
}
@Override
public void remove() {
this.pageCursor.remove();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/STreePage.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.collections;
import java.util.Map;
import swim.util.Cursor;
public abstract class STreePage<T> {
public abstract boolean isEmpty();
public abstract int size();
public abstract int arity();
public abstract boolean contains(Object value);
public abstract int indexOf(Object value);
public abstract int lastIndexOf(Object value);
public abstract T get(int index);
public abstract Map.Entry<Object, T> getEntry(int index);
public abstract STreePage<T> updated(int index, T newValue, STreeContext<T> tree);
public abstract STreePage<T> inserted(int index, T newValue, Object id, STreeContext<T> tree);
public STreePage<T> appended(T newValue, Object id, STreeContext<T> tree) {
return inserted(size(), newValue, id, tree);
}
public STreePage<T> prepended(T newValue, Object id, STreeContext<T> tree) {
return inserted(0, newValue, id, tree);
}
public abstract STreePage<T> removed(int index, STreeContext<T> tree);
public abstract STreePage<T> removed(Object value, STreeContext<T> tree);
public abstract STreePage<T> drop(int lower, STreeContext<T> tree);
public abstract STreePage<T> take(int upper, STreeContext<T> tree);
public abstract STreePage<T> balanced(STreeContext<T> tree);
public abstract STreePage<T> split(int index);
public abstract STreePage<T> splitLeft(int index);
public abstract STreePage<T> splitRight(int index);
public abstract void copyToArray(Object[] array, int offset);
public Cursor<T> iterator() {
return Cursor.values(this.entryIterator());
}
public Cursor<Object> keyIterator() {
return Cursor.keys(this.entryIterator());
}
public abstract Cursor<Map.Entry<Object, T>> entryIterator();
public Cursor<T> reverseIterator() {
return Cursor.values(this.reverseEntryIterator());
}
public Cursor<Object> reverseKeyIterator() {
return Cursor.keys(this.reverseEntryIterator());
}
public abstract Cursor<Map.Entry<Object, T>> reverseEntryIterator();
public static <T> STreePage<T> empty() {
return STreeLeaf.empty();
}
}
|
0 | java-sources/ai/swim/swim-collections/3.10.0/swim | java-sources/ai/swim/swim-collections/3.10.0/swim/collections/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.
/**
* Immutable, structure sharing collections.
*/
package swim.collections;
|
0 | java-sources/ai/swim/swim-concurrent | java-sources/ai/swim/swim-concurrent/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.
/**
* Lightweight timers, tasks, and continuations.
*/
module swim.concurrent {
requires transitive swim.structure;
exports swim.concurrent;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.