index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriFragment.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.uri; import swim.codec.Debug; import swim.codec.Display; import swim.codec.Format; import swim.codec.Output; import swim.util.HashGenCacheMap; import swim.util.Murmur3; public class UriFragment implements Comparable<UriFragment>, Debug, Display { protected final String identifier; String string; protected UriFragment(String identifier) { this.identifier = identifier; } public final boolean isDefined() { return this.identifier != null; } public String identifier() { return this.identifier; } @Override public final int compareTo(UriFragment that) { return toString().compareTo(that.toString()); } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriFragment) { final UriFragment that = (UriFragment) other; return this.identifier == null ? that.identifier == null : this.identifier.equals(that.identifier); } return false; } @Override public int hashCode() { return this.identifier == null ? 0 : Murmur3.seed(this.identifier); } @Override public void debug(Output<?> output) { output = output.write("UriFragment").write('.'); if (isDefined()) { output = output.write("parse").write('(').write('"').display(this).write('"').write(')'); } else { output = output.write("undefined").write('(').write(')'); } } @Override public void display(Output<?> output) { if (this.string != null) { output = output.write(this.string); } else if (this.identifier != null) { Uri.writeFragment(this.identifier, output); } } @Override public String toString() { if (this.string == null) { this.string = Format.display(this); } return this.string; } private static UriFragment undefined; private static HashGenCacheMap<String, UriFragment> cache; public static UriFragment undefined() { if (undefined == null) { undefined = new UriFragment(null); } return undefined; } public static UriFragment from(String identifier) { if (identifier != null) { final HashGenCacheMap<String, UriFragment> cache = cache(); final UriFragment fragment = cache.get(identifier); if (fragment != null) { return fragment; } else { return cache.put(identifier, new UriFragment(identifier)); } } else { return undefined(); } } public static UriFragment parse(String string) { return Uri.standardParser().parseFragmentString(string); } static HashGenCacheMap<String, UriFragment> cache() { if (cache == null) { int cacheSize; try { cacheSize = Integer.parseInt(System.getProperty("swim.uri.fragment.cache.size")); } catch (NumberFormatException e) { cacheSize = 32; } cache = new HashGenCacheMap<String, UriFragment>(cacheSize); } return cache; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriFragmentLiteral.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.uri; import swim.collections.HashTrieMap; final class UriFragmentLiteral extends UriFragmentPattern { final UriFragment fragment; final UriTerminalPattern rest; UriFragmentLiteral(UriFragment fragment, UriTerminalPattern rest) { this.fragment = fragment; this.rest = rest; } @Override public boolean isUri() { return this.rest.isUri(); } @Override public Uri toUri() { return this.rest.toUri(); } @Override Uri apply(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, String[] args, int index) { return this.rest.apply(scheme, authority, path, query, this.fragment, args, index); } @Override HashTrieMap<String, String> unapply(UriFragment fragment, HashTrieMap<String, String> args) { return this.rest.unapply(args); } @Override boolean matches(UriFragment fragment) { if (this.fragment.equals(fragment)) { return this.rest.matches(); } else { return false; } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriFragmentMapper.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.uri; abstract class UriFragmentMapper<T> extends UriQueryMapper<T> { abstract T get(UriFragment fragment); @Override T get(UriQuery query, UriFragment fragment) { return get(fragment); } abstract UriFragmentMapper<T> merged(UriFragmentMapper<T> that); @Override UriQueryMapper<T> merged(UriQueryMapper<T> that) { if (that instanceof UriFragmentMapper<?>) { return merged((UriFragmentMapper<T>) that); } else { return that; } } abstract UriFragmentMapper<T> removed(UriFragment fragment); @Override UriQueryMapper<T> removed(UriQuery query, UriFragment fragment) { return removed(fragment); } abstract UriFragmentMapper<T> unmerged(UriFragmentMapper<T> that); @Override UriQueryMapper<T> unmerged(UriQueryMapper<T> that) { if (that instanceof UriFragmentMapper<?>) { return unmerged((UriFragmentMapper<T>) that); } else { return this; } } static <T> UriFragmentMapper<T> compile(Uri pattern, UriFragment fragment, T value) { return UriTerminalMapper.compile(pattern, value); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriFragmentParser.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.uri; import swim.codec.Base16; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Output; import swim.codec.Parser; import swim.codec.Utf8; final class UriFragmentParser extends Parser<UriFragment> { final UriParser uri; final Output<String> output; final int c1; final int step; UriFragmentParser(UriParser uri, Output<String> output, int c1, int step) { this.uri = uri; this.output = output; this.c1 = c1; this.step = step; } UriFragmentParser(UriParser uri) { this(uri, null, 0, 1); } @Override public Parser<UriFragment> feed(Input input) { return parse(input, this.uri, this.output, this.c1, this.step); } static Parser<UriFragment> parse(Input input, UriParser uri, Output<String> output, int c1, int step) { int c = 0; if (output == null) { output = Utf8.decodedString(); } do { if (step == 1) { while (input.isCont()) { c = input.head(); if (Uri.isFragmentChar(c)) { input = input.step(); output = output.write(c); } else { break; } } if (input.isCont() && c == '%') { input = input.step(); step = 2; } else if (!input.isEmpty()) { return done(uri.fragment(output.bind())); } } if (step == 2) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); c1 = c; step = 3; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 3) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); output = output.write((Base16.decodeDigit(c1) << 4) | Base16.decodeDigit(c)); c1 = 0; step = 1; continue; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } break; } while (true); if (input.isError()) { return error(input.trap()); } return new UriFragmentParser(uri, output, c1, step); } static Parser<UriFragment> parse(Input input, UriParser uri) { return parse(input, uri, null, 0, 1); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriFragmentPattern.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.uri; import swim.collections.HashTrieMap; abstract class UriFragmentPattern extends UriQueryPattern { abstract HashTrieMap<String, String> unapply(UriFragment fragment, HashTrieMap<String, String> args); @Override HashTrieMap<String, String> unapply(UriQuery query, UriFragment fragment, HashTrieMap<String, String> args) { return unapply(fragment, args); } abstract boolean matches(UriFragment fragment); @Override boolean matches(UriQuery query, UriFragment fragment) { if (!query.isDefined()) { return matches(fragment); } else { return false; } } static UriFragmentPattern compile(Uri pattern, UriFragment fragment) { if (fragment.isDefined()) { return new UriFragmentLiteral(fragment, UriTerminalPattern.compile(pattern)); } else { return UriTerminalPattern.compile(pattern); } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriHost.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.uri; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import swim.codec.Debug; import swim.codec.Display; import swim.codec.Output; import swim.util.HashGenCacheMap; import swim.util.Murmur3; public abstract class UriHost implements Comparable<UriHost>, Debug, Display { protected UriHost() { // stub } public boolean isDefined() { return true; } public abstract String address(); public String name() { return null; } public String ipv4() { return null; } public String ipv6() { return null; } public InetAddress inetAddress() throws UnknownHostException { return InetAddress.getByName(address()); } @Override public final int compareTo(UriHost that) { return toString().compareTo(that.toString()); } @Override public final boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriHost) { return toString().equals(((UriHost) other).toString()); } return false; } @Override public final int hashCode() { return Murmur3.seed(toString()); } @Override public abstract void debug(Output<?> output); @Override public abstract void display(Output<?> output); @Override public abstract String toString(); private static UriHost undefined; private static HashGenCacheMap<String, UriHost> cache; public static UriHost undefined() { if (undefined == null) { undefined = new UriHostUndefined(); } return undefined; } public static UriHost name(String address) { if (address == null) { throw new NullPointerException(); } final HashGenCacheMap<String, UriHost> cache = cache(); final UriHost host = cache.get(address); if (host instanceof UriHostName) { return host; } else { return cache.put(address, new UriHostName(address)); } } public static UriHost ipv4(String address) { if (address == null) { throw new NullPointerException(); } final HashGenCacheMap<String, UriHost> cache = cache(); final UriHost host = cache.get(address); if (host instanceof UriHostIPv4) { return host; } else { return cache.put(address, new UriHostIPv4(address)); } } public static UriHost ipv6(String address) { if (address == null) { throw new NullPointerException(); } final HashGenCacheMap<String, UriHost> cache = cache(); final UriHost host = cache.get(address); if (host instanceof UriHostIPv6) { return host; } else { return cache.put(address, new UriHostIPv6(address)); } } public static UriHost inetAddress(InetAddress address) { if (address == null) { throw new NullPointerException(); } if (address instanceof Inet4Address) { return ipv4(address.getHostAddress()); } else if (address instanceof Inet6Address) { return ipv6(address.getHostAddress()); } else { return name(address.getHostName()); } } public static UriHost parse(String string) { return Uri.standardParser().parseHostString(string); } static HashGenCacheMap<String, UriHost> cache() { if (cache == null) { int cacheSize; try { cacheSize = Integer.parseInt(System.getProperty("swim.uri.host.cache.size")); } catch (NumberFormatException e) { cacheSize = 16; } cache = new HashGenCacheMap<String, UriHost>(cacheSize); } return cache; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriHostAddressParser.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.uri; import swim.codec.Base10; import swim.codec.Base16; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Output; import swim.codec.Parser; import swim.codec.Utf8; final class UriHostAddressParser extends Parser<UriHost> { final UriParser uri; final Output<String> output; final int c1; final int x; final int step; UriHostAddressParser(UriParser uri, Output<String> output, int c1, int x, int step) { this.uri = uri; this.output = output; this.c1 = c1; this.x = x; this.step = step; } UriHostAddressParser(UriParser uri) { this(uri, null, 0, 0, 1); } @Override public Parser<UriHost> feed(Input input) { return parse(input, this.uri, this.output, this.c1, this.x, this.step); } static Parser<UriHost> parse(Input input, UriParser uri, Output<String> output, int c1, int x, int step) { int c = 0; if (output == null) { output = Utf8.decodedString(); } while (step <= 4) { while (input.isCont()) { c = input.head(); if (Base10.isDigit(c)) { input = input.step(); output = output.write(c); x = 10 * x + Base10.decodeDigit(c); } else { break; } } if (input.isCont()) { if (c == '.' && step < 4 && x <= 255) { input = input.step(); output = output.write(c); x = 0; step += 1; } else if (!Uri.isHostChar(c) && c != '%' && step == 4 && x <= 255) { return done(uri.hostIPv4(output.bind())); } else { x = 0; step = 5; break; } } else if (!input.isEmpty()) { if (step == 4 && x <= 255) { return done(uri.hostIPv4(output.bind())); } else { return done(uri.hostName(output.bind())); } } else { break; } } do { if (step == 5) { while (input.isCont()) { c = input.head(); if (Uri.isHostChar(c)) { input = input.step(); output = output.write(Character.toLowerCase(c)); } else { break; } } if (input.isCont() && c == '%') { input = input.step(); step = 6; } else if (!input.isEmpty()) { return done(uri.hostName(output.bind())); } } if (step == 6) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); c1 = c; step = 7; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 7) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); output = output.write((Base16.decodeDigit(c1) << 4) | Base16.decodeDigit(c)); c1 = 0; step = 5; continue; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } break; } while (true); if (input.isError()) { return error(input.trap()); } return new UriHostAddressParser(uri, output, c1, x, step); } static Parser<UriHost> parse(Input input, UriParser uri) { return parse(input, uri, null, 0, 0, 1); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriHostIPv4.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.uri; import swim.codec.Output; final class UriHostIPv4 extends UriHost { final String address; UriHostIPv4(String address) { this.address = address; } @Override public String address() { return this.address; } @Override public String ipv4() { return this.address; } @Override public void debug(Output<?> output) { output = output.write("UriHost").write('.').write("ipv4").write('(').debug(this.address).write(')'); } @Override public void display(Output<?> output) { Uri.writeHost(this.address, output); } @Override public String toString() { return this.address; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriHostIPv6.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.uri; import swim.codec.Output; final class UriHostIPv6 extends UriHost { final String address; String string; UriHostIPv6(String address) { this.address = address; } @Override public String address() { return this.address; } @Override public String ipv6() { return this.address; } @Override public void debug(Output<?> output) { output = output.write("UriHost").write('.').write("ipv6").write('(').debug(this.address).write(')'); } @Override public void display(Output<?> output) { if (this.string != null) { output = output.write(this.string); } else { output = output.write('['); Uri.writeHostLiteral(this.address, output); output = output.write(']'); } } @Override public String toString() { if (this.string == null) { this.string = new StringBuilder(1 + this.address.length() + 1) .append('[').append(this.address).append(']').toString(); } return this.string; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriHostLiteralParser.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.uri; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Output; import swim.codec.Parser; import swim.codec.Utf8; final class UriHostLiteralParser extends Parser<UriHost> { final UriParser uri; final Output<String> output; final int step; UriHostLiteralParser(UriParser uri, Output<String> output, int step) { this.uri = uri; this.output = output; this.step = step; } UriHostLiteralParser(UriParser uri) { this(uri, null, 1); } @Override public Parser<UriHost> feed(Input input) { return parse(input, this.uri, this.output, this.step); } static Parser<UriHost> parse(Input input, UriParser uri, Output<String> output, int step) { int c = 0; if (step == 1) { if (input.isCont() && input.head() == '[') { input = input.step(); step = 2; } else if (!input.isEmpty()) { return error(Diagnostic.expected('[', input)); } } if (step == 2) { if (output == null) { output = Utf8.decodedString(); } while (input.isCont()) { c = input.head(); if (Uri.isHostChar(c) || c == ':') { input = input.step(); output = output.write(Character.toLowerCase(c)); } else { break; } } if (input.isCont() && c == ']') { input = input.step(); return done(uri.hostIPv6(output.bind())); } else if (!input.isEmpty()) { return error(Diagnostic.expected(']', input)); } } if (input.isError()) { return error(input.trap()); } return new UriHostLiteralParser(uri, output, step); } static Parser<UriHost> parse(Input input, UriParser uri) { return parse(input, uri, null, 1); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriHostName.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.uri; import swim.codec.Output; final class UriHostName extends UriHost { final String address; UriHostName(String address) { this.address = address; } @Override public String address() { return this.address; } @Override public String name() { return this.address; } @Override public void debug(Output<?> output) { output = output.write("UriHost").write('.').write("name").write('(').debug(this.address).write(')'); } @Override public void display(Output<?> output) { Uri.writeHost(this.address, output); } @Override public String toString() { return this.address; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriHostParser.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.uri; import swim.codec.Input; import swim.codec.Parser; final class UriHostParser extends Parser<UriHost> { final UriParser uri; UriHostParser(UriParser uri) { this.uri = uri; } @Override public Parser<UriHost> feed(Input input) { return parse(input, this.uri); } static Parser<UriHost> parse(Input input, UriParser uri) { if (input.isCont()) { final int c = input.head(); if (c == '[') { return uri.parseHostLiteral(input); } else { return uri.parseHostAddress(input); } } else if (input.isDone()) { return done(uri.hostName("")); } else if (input.isError()) { return error(input.trap()); } return new UriHostParser(uri); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriHostUndefined.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.uri; import swim.codec.Output; final class UriHostUndefined extends UriHost { @Override public boolean isDefined() { return false; } @Override public String address() { return ""; } @Override public void debug(Output<?> output) { output = output.write("UriHost").write('.').write("undefined").write('(').write(')'); } @Override public void display(Output<?> output) { // nop } @Override public String toString() { return ""; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriMapper.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.uri; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import swim.codec.Debug; import swim.codec.Format; import swim.codec.Output; public abstract class UriMapper<T> implements Iterable<Map.Entry<Uri, T>>, Map<Uri, T>, Debug { UriMapper() { // stub } @Override public abstract boolean isEmpty(); @Override public abstract int size(); @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public abstract boolean containsValue(Object value); public abstract T get(Uri uri); public T get(String uri) { return get(Uri.parse(uri)); } @Override public T get(Object key) { if (key instanceof Uri) { return get((Uri) key); } else if (key instanceof String) { return get((String) key); } else { return null; } } @Override public T put(Uri pattern, T value) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends Uri, ? extends T> map) { throw new UnsupportedOperationException(); } @Override public T remove(Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } public abstract UriMapper<T> merged(UriMapper<T> that); public UriMapper<T> updated(Uri pattern, T value) { return merged(from(pattern, value)); } public UriMapper<T> updated(UriPattern pattern, T value) { return updated(pattern.toUri(), value); } public UriMapper<T> updated(String pattern, T value) { return updated(Uri.parse(pattern), value); } public abstract UriMapper<T> removed(Uri pattern); public UriMapper<T> removed(UriPattern pattern) { return removed(pattern.toUri()); } public UriMapper<T> removed(String pattern) { return removed(Uri.parse(pattern)); } public abstract UriMapper<T> unmerged(UriMapper<T> that); @Override public Set<Entry<Uri, T>> entrySet() { return new UriMapperEntrySet<T>(this); } @Override public Set<Uri> keySet() { return new UriMapperKeySet<T>(this); } @Override public Collection<T> values() { return new UriMapperValues<T>(this); } @Override public abstract Iterator<Entry<Uri, T>> iterator(); public abstract Iterator<Uri> keyIterator(); public abstract Iterator<T> valueIterator(); @Override public void debug(Output<?> output) { output = output.write("UriMapper").write('.').write("empty").write('(').write(')'); for (Entry<Uri, T> from : this) { output = output.write('.').write("updated").write('(') .debug(from.getKey().toString()).write(", ") .debug(from.getValue()).write(')'); } } @Override public String toString() { return Format.debug(this); } private static UriMapper<Object> empty; @SuppressWarnings("unchecked") public static <T> UriMapper<T> empty() { if (empty == null) { empty = new UriEmptyMapping<Object>(); } return (UriMapper<T>) empty; } public static <T> UriMapper<T> from(Uri pattern, T value) { return UriSchemeMapper.compile(pattern, pattern.scheme(), pattern.authority(), pattern.path(), pattern.query(), pattern.fragment(), value); } public static <T> UriMapper<T> from(UriPattern pattern, T value) { return from(pattern.toUri(), value); } public static <T> UriMapper<T> from(String uriString, T value) { return from(Uri.parse(uriString), value); } } final class UriMapperEntrySet<T> extends AbstractSet<Map.Entry<Uri, T>> { final UriMapper<T> mapper; UriMapperEntrySet(UriMapper<T> mapper) { this.mapper = mapper; } @Override public boolean isEmpty() { return this.mapper.isEmpty(); } @Override public int size() { return this.mapper.size(); } @Override public Iterator<Map.Entry<Uri, T>> iterator() { return this.mapper.iterator(); } } final class UriMapperKeySet<T> extends AbstractSet<Uri> { final UriMapper<T> mapper; UriMapperKeySet(UriMapper<T> mapper) { this.mapper = mapper; } @Override public boolean isEmpty() { return this.mapper.isEmpty(); } @Override public int size() { return this.mapper.size(); } @Override public Iterator<Uri> iterator() { return this.mapper.keyIterator(); } } final class UriMapperValues<T> extends AbstractCollection<T> { final UriMapper<T> mapper; UriMapperValues(UriMapper<T> mapper) { this.mapper = mapper; } @Override public boolean isEmpty() { return this.mapper.isEmpty(); } @Override public int size() { return this.mapper.size(); } @Override public Iterator<T> iterator() { return this.mapper.valueIterator(); } } final class UriEmptyMapping<T> extends UriTerminalMapper<T> { @Override public boolean isEmpty() { return true; } @Override public int size() { return 0; } @Override public boolean containsValue(Object value) { return false; } @Override public T get() { return null; } @Override public Set<Entry<Uri, T>> entrySet() { return Collections.emptySet(); } @Override public Set<Uri> keySet() { return Collections.emptySet(); } @Override public Collection<T> values() { return Collections.emptyList(); } @Override public Iterator<Entry<Uri, T>> iterator() { return Collections.emptyIterator(); } @Override public Iterator<Uri> keyIterator() { return Collections.emptyIterator(); } @Override public Iterator<T> valueIterator() { return Collections.emptyIterator(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriParser.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.uri; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Parser; import swim.codec.Unicode; public class UriParser { public Uri absolute(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment) { return Uri.from(scheme, authority, path, query, fragment); } public UriScheme scheme(String name) { return UriScheme.from(name); } public UriAuthority authority(UriUser user, UriHost host, UriPort port) { return UriAuthority.from(user, host, port); } public UriUser user(String username, String password) { return UriUser.from(username, password); } public UriHost hostName(String address) { return UriHost.name(address); } public UriHost hostIPv4(String address) { return UriHost.ipv4(address); } public UriHost hostIPv6(String address) { return UriHost.ipv6(address); } public UriPort port(int number) { return UriPort.from(number); } public UriPath pathEmpty() { return UriPath.empty(); } public UriPathBuilder pathBuilder() { return new UriPathBuilder(); } public UriQueryBuilder queryBuilder() { return new UriQueryBuilder(); } public UriFragment fragment(String identifier) { return UriFragment.from(identifier); } public Parser<Uri> absoluteParser() { return new UriAbsoluteParser(this); } public Parser<Uri> parseAbsolute(Input input) { return UriAbsoluteParser.parse(input, this); } public Uri parseAbsoluteString(String string) { final Input input = Unicode.stringInput(string); Parser<Uri> parser = parseAbsolute(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } if (!parser.isDone()) { System.out.println(parser); } return parser.bind(); } public Parser<UriScheme> schemeParser() { return new UriSchemeParser(this); } public Parser<UriScheme> parseScheme(Input input) { return UriSchemeParser.parse(input, this); } public UriScheme parseSchemeString(String string) { final Input input = Unicode.stringInput(string); Parser<UriScheme> parser = parseScheme(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } return parser.bind(); } public Parser<UriAuthority> authorityParser() { return new UriAuthorityParser(this); } public Parser<UriAuthority> parseAuthority(Input input) { return UriAuthorityParser.parse(input, this); } public UriAuthority parseAuthorityString(String string) { final Input input = Unicode.stringInput(string); Parser<UriAuthority> parser = parseAuthority(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } return parser.bind(); } public Parser<UriUser> userParser() { return new UriUserParser(this); } public Parser<UriUser> parseUser(Input input) { return UriUserParser.parse(input, this); } public UriUser parseUserString(String string) { final Input input = Unicode.stringInput(string); Parser<UriUser> parser = parseUser(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } return parser.bind(); } public Parser<UriHost> hostParser() { return new UriHostParser(this); } public Parser<UriHost> parseHost(Input input) { return UriHostParser.parse(input, this); } public UriHost parseHostString(String string) { final Input input = Unicode.stringInput(string); Parser<UriHost> parser = parseHost(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } return parser.bind(); } public Parser<UriHost> hostAddressParser() { return new UriHostAddressParser(this); } public Parser<UriHost> parseHostAddress(Input input) { return UriHostAddressParser.parse(input, this); } public Parser<UriHost> hostLiteralParser() { return new UriHostLiteralParser(this); } public Parser<UriHost> parseHostLiteral(Input input) { return UriHostLiteralParser.parse(input, this); } public Parser<UriPort> portParser() { return new UriPortParser(this); } public Parser<UriPort> parsePort(Input input) { return UriPortParser.parse(input, this); } public UriPort parsePortString(String string) { final Input input = Unicode.stringInput(string); Parser<UriPort> parser = parsePort(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } return parser.bind(); } public Parser<UriPath> pathParser(UriPathBuilder builder) { return new UriPathParser(this, builder); } public Parser<UriPath> pathParser() { return new UriPathParser(this); } public Parser<UriPath> parsePath(Input input, UriPathBuilder builder) { return UriPathParser.parse(input, this, builder); } public Parser<UriPath> parsePath(Input input) { return UriPathParser.parse(input, this); } public UriPath parsePathString(String string) { final Input input = Unicode.stringInput(string); Parser<UriPath> parser = parsePath(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } return parser.bind(); } public Parser<UriQuery> queryParser(UriQueryBuilder builder) { return new UriQueryParser(this, builder); } public Parser<UriQuery> queryParser() { return new UriQueryParser(this); } public Parser<UriQuery> parseQuery(Input input, UriQueryBuilder builder) { return UriQueryParser.parse(input, this, builder); } public Parser<UriQuery> parseQuery(Input input) { return UriQueryParser.parse(input, this); } public UriQuery parseQueryString(String string) { final Input input = Unicode.stringInput(string); Parser<UriQuery> parser = parseQuery(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } return parser.bind(); } public Parser<UriFragment> fragmentParser() { return new UriFragmentParser(this); } public Parser<UriFragment> parseFragment(Input input) { return UriFragmentParser.parse(input, this); } public UriFragment parseFragmentString(String string) { final Input input = Unicode.stringInput(string); Parser<UriFragment> parser = parseFragment(input); if (input.isCont() && !parser.isError()) { parser = Parser.error(Diagnostic.unexpected(input)); } return parser.bind(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPath.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.uri; import java.lang.reflect.Array; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import swim.codec.Debug; import swim.codec.Display; import swim.codec.Output; import swim.structure.Form; import swim.structure.Kind; import swim.util.HashGenCacheSet; import swim.util.Murmur3; public abstract class UriPath implements Collection<String>, Comparable<UriPath>, Debug, Display { UriPath() { // sealed } public abstract boolean isDefined(); public abstract boolean isAbsolute(); public abstract boolean isRelative(); @Override public abstract boolean isEmpty(); @Override public int size() { return UriPath.size(this); } private static int size(UriPath path) { int n = 0; while (!path.isEmpty()) { n += 1; path = path.tail(); } return n; } public abstract String head(); public abstract UriPath tail(); abstract void setTail(UriPath tail); abstract UriPath dealias(); public abstract UriPath parent(); public abstract UriPath base(); public String name() { return UriPath.name(this); } private static String name(UriPath path) { if (path.isEmpty()) { return ""; } do { final UriPath tail = path.tail(); if (tail.isEmpty()) { return path.isRelative() ? path.head() : ""; } else { path = tail; } } while (true); } public UriPath name(String name) { final UriPathBuilder builder = new UriPathBuilder(); builder.addPath(base()); builder.addSegment(name); return builder.bind(); } public UriPath foot() { return UriPath.foot(this); } private static UriPath foot(UriPath path) { if (path.isEmpty()) { return path; } do { final UriPath tail = path.tail(); if (tail.isEmpty()) { return path; } else { path = tail; } } while (true); } public boolean isSubpathOf(UriPath b) { return UriPath.isSubpathOf(this, b); } private static boolean isSubpathOf(UriPath a, UriPath b) { while (!a.isEmpty() && !b.isEmpty()) { if (!a.head().equals(b.head())) { return false; } a = a.tail(); b = b.tail(); } return b.isEmpty(); } @Override public boolean contains(Object component) { if (component instanceof String) { return UriPath.contains(this, (String) component); } return false; } private static boolean contains(UriPath path, String component) { while (!path.isEmpty()) { if (component.equals(path.head())) { return true; } path = path.tail(); } return false; } @Override public boolean containsAll(Collection<?> components) { if (components == null) { throw new NullPointerException(); } return UriPath.containsAll(this, new HashSet<Object>(components)); } private static boolean containsAll(UriPath path, HashSet<?> missing) { while (!path.isEmpty() && !missing.isEmpty()) { missing.remove(path.head()); path = path.tail(); } return missing.isEmpty(); } @Override public boolean add(String component) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends String> components) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object component) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> components) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> components) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } public UriPath appended(String component) { if (component == null) { throw new NullPointerException(); } if (component.equals("/")) { return appendedSlash(); } else { return appendedSegment(component); } } public UriPath appended(String... components) { return appended(UriPath.from(components)); } public UriPath appended(Collection<? extends String> components) { if (!components.isEmpty()) { final UriPathBuilder builder = new UriPathBuilder(); builder.addPath(this); builder.addAll(components); return builder.bind(); } else { return this; } } public UriPath appendedSlash() { final UriPathBuilder builder = new UriPathBuilder(); builder.addPath(this); builder.addSlash(); return builder.bind(); } public UriPath appendedSegment(String segment) { final UriPathBuilder builder = new UriPathBuilder(); builder.addPath(this); builder.addSegment(segment); return builder.bind(); } public UriPath prepended(String component) { if (component == null) { throw new NullPointerException(); } if (component.equals("/")) { return prependedSlash(); } else { return prependedSegment(component); } } public UriPath prepended(String... components) { return prepended(UriPath.from(components)); } public UriPath prepended(Collection<? extends String> components) { if (!components.isEmpty()) { final UriPathBuilder builder = new UriPathBuilder(); builder.addAll(components); builder.addPath(this); return builder.bind(); } else { return this; } } public UriPath prependedSlash() { return UriPath.slash(this); } public UriPath prependedSegment(String segment) { if (this.isEmpty() || this.isAbsolute()) { return UriPath.segment(segment, this); } else { return UriPath.segment(segment, UriPath.slash(this)); } } public UriPath resolve(UriPath that) { if (that.isEmpty()) { return this; } else if (that.isAbsolute() || this.isEmpty()) { return that.removeDotSegments(); } else { return merge(that).removeDotSegments(); } } public UriPath removeDotSegments() { return UriPath.removeDotSegments(this, new UriPathBuilder()); } private static UriPath removeDotSegments(UriPath path, UriPathBuilder builder) { while (!path.isEmpty()) { final String head = path.head(); if (head.equals(".") || head.equals("..")) { path = path.tail(); if (!path.isEmpty()) { path = path.tail(); } } else if (path.isAbsolute()) { final UriPath rest = path.tail(); if (!rest.isEmpty()) { final String next = rest.head(); if (next.equals(".")) { path = rest.tail(); if (path.isEmpty()) { path = UriPath.slash(); } } else if (next.equals("..")) { path = rest.tail(); if (path.isEmpty()) { path = UriPath.slash(); } if (!builder.isEmpty() && !builder.pop().isAbsolute()) { if (!builder.isEmpty()) { builder.pop(); } } } else { builder.add(head); builder.add(next); path = rest.tail(); } } else { builder.add(path.head()); path = path.tail(); } } else { builder.add(path.head()); path = path.tail(); } } return builder.bind(); } public UriPath merge(UriPath that) { if (that == null) { throw new NullPointerException(); } if (!isEmpty()) { return UriPath.merge(this, that); } else { return that; } } static UriPath merge(UriPath prev, UriPath that) { final UriPathBuilder builder = new UriPathBuilder(); do { final UriPath next = prev.tail(); if (!next.isEmpty()) { if (prev.isAbsolute()) { builder.addSlash(); } else { builder.addSegment(prev.head()); } prev = next; } else { if (prev.isAbsolute()) { builder.addSlash(); } break; } } while (true); builder.addPath(that); return builder.bind(); } public UriPath unmerge(UriPath that) { return UriPath.unmerge(this, that, that); } private static UriPath unmerge(UriPath base, UriPath relative, UriPath root) { do { if (base.isEmpty()) { if (!relative.isEmpty() && !relative.tail().isEmpty()) { return relative.tail(); } else { return relative; } } else if (base.isRelative()) { return relative; } else if (relative.isRelative()) { return UriPath.slash(relative); } else { UriPath a = base.tail(); UriPath b = relative.tail(); if (!a.isEmpty() && b.isEmpty()) { return UriPath.slash(); } else if (a.isEmpty() || b.isEmpty() || !a.head().equals(b.head())) { return b; } else { a = a.tail(); b = b.tail(); if (!a.isEmpty() && b.isEmpty()) { return root; } else { base = a; relative = b; } } } } while (true); } @Override public Object[] toArray() { final Object[] array = new Object[size()]; UriPath.toArray(this, array); return array; } @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] array) { final int n = size(); if (array.length < n) { array = (T[]) Array.newInstance(array.getClass().getComponentType(), n); } UriPath.toArray(this, array); if (array.length > n) { array[n] = null; } return array; } private static void toArray(UriPath path, Object[] array) { int i = 0; while (!path.isEmpty()) { array[i] = path.head(); path = path.tail(); i += 1; } } @Override public Iterator<String> iterator() { return new UriPathIterator(this); } @Override public final int compareTo(UriPath that) { return toString().compareTo(that.toString()); } @Override public final boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriPath) { return toString().equals(((UriPath) other).toString()); } return false; } @Override public final int hashCode() { return Murmur3.seed(toString()); } @Override public abstract void debug(Output<?> output); @Override public abstract void display(Output<?> output); static void display(UriPath path, Output<?> output) { while (!path.isEmpty()) { if (path.isAbsolute()) { output = output.write('/'); } else { Uri.writePathSegment(path.head(), output); } path = path.tail(); } } @Override public abstract String toString(); private static UriPath empty; private static UriPath slash; private static HashGenCacheSet<String> segmentCache; public static UriPathBuilder builder() { return new UriPathBuilder(); } public static UriPath empty() { if (empty == null) { empty = new UriPathEmpty(); } return empty; } public static UriPath slash() { if (slash == null) { slash = new UriPathSlash(UriPath.empty()); } return slash; } public static UriPath segment(String segment) { return UriPath.segment(segment, UriPath.empty()); } static UriPath slash(UriPath tail) { if (tail == empty) { return UriPath.slash(); } else { return new UriPathSlash(tail); } } static UriPath segment(String segment, UriPath tail) { if (segment == null) { throw new NullPointerException("segment"); } segment = UriPath.cacheSegment(segment); return new UriPathSegment(segment, tail); } public static UriPath from(String... components) { if (components == null) { throw new NullPointerException(); } final UriPathBuilder builder = new UriPathBuilder(); for (int i = 0, n = components.length; i < n; i += 1) { builder.add(components[i]); } return builder.bind(); } public static UriPath from(Collection<? extends String> components) { if (components == null) { throw new NullPointerException(); } if (components instanceof UriPath) { return (UriPath) components; } else { final UriPathBuilder builder = new UriPathBuilder(); builder.addAll(components); return builder.bind(); } } public static UriPath parse(String string) { return Uri.standardParser().parsePathString(string); } static HashGenCacheSet<String> segmentCache() { if (segmentCache == null) { int segmentCacheSize; try { segmentCacheSize = Integer.parseInt(System.getProperty("swim.uri.segment.cache.size")); } catch (NumberFormatException e) { segmentCacheSize = 64; } segmentCache = new HashGenCacheSet<String>(segmentCacheSize); } return segmentCache; } static String cacheSegment(String segment) { if (segment.length() <= 32) { return segmentCache().put(segment); } else { return segment; } } private static Form<UriPath> pathForm; @Kind public static Form<UriPath> pathForm() { if (pathForm == null) { pathForm = new UriPathForm(UriPath.empty()); } return pathForm; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathBuilder.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.uri; import java.util.Collection; import java.util.NoSuchElementException; import swim.util.Builder; public final class UriPathBuilder implements Builder<String, UriPath> { UriPath first; UriPath last; int size; int aliased; public UriPathBuilder() { this.first = UriPath.empty(); this.last = null; this.size = 0; this.aliased = 0; } boolean isEmpty() { return this.size == 0; } @Override public boolean add(String component) { if (component == null) { throw new NullPointerException(); } if (component.equals("/")) { return addSlash(); } else { return addSegment(component); } } @Override public boolean addAll(Collection<? extends String> components) { if (components == null) { throw new NullPointerException(); } if (components instanceof UriPath) { return addPath((UriPath) components); } else { boolean modified = false; for (String component : components) { modified = add(component) || modified; } return modified; } } @Override public UriPath bind() { this.aliased = 0; return this.first; } public boolean addSlash() { final UriPath tail = UriPath.slash().dealias(); final int size = this.size; if (size == 0) { this.first = tail; } else { dealias(size - 1).setTail(tail); } this.last = tail; this.size = size + 1; this.aliased += 1; return true; } public boolean addSegment(String segment) { segment = UriPath.cacheSegment(segment); final UriPath tail = UriPath.segment(segment, UriPath.empty()); final int size = this.size; if (size == 0) { this.first = tail; } else { dealias(size - 1).setTail(tail); } this.last = tail; this.size = size + 1; this.aliased += 1; return true; } public boolean addPath(UriPath path) { if (!path.isEmpty()) { int size = this.size; if (size == 0) { this.first = path; } else { dealias(size - 1).setTail(path); } size += 1; do { final UriPath tail = path.tail(); if (!tail.isEmpty()) { path = tail; size += 1; } else { break; } } while (true); this.last = path; this.size = size; return true; } return false; } public UriPath pop() { final int size = this.size; final int aliased = this.aliased; if (size == 0) { throw new NoSuchElementException(); } else if (size == 1) { final UriPath first = this.first; this.first = first.tail(); if (first.tail().isEmpty()) { this.last = null; } this.size = size - 1; if (aliased > 0) { this.aliased = aliased - 1; } return first; } else { final UriPath last = dealias(size - 2); last.setTail(UriPath.empty()); this.last = last; this.size = size - 1; this.aliased = aliased - 1; return last.tail(); } } UriPath dealias(int n) { int i = 0; UriPath xi = null; UriPath xs = this.first; if (this.aliased <= n) { while (i < this.aliased) { xi = xs; xs = xs.tail(); i += 1; } while (i <= n) { final UriPath xn = xs.dealias(); if (i == 0) { this.first = xn; } else { xi.setTail(xn); } xi = xn; xs = xs.tail(); i += 1; } if (i == this.size) { this.last = xi; } this.aliased = i; } else if (n == 0) { xi = this.first; } else if (n == this.size - 1) { xi = this.last; } else { while (i <= n) { xi = xs; xs = xs.tail(); i += 1; } } return xi; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathEmpty.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.uri; import java.util.Collection; import java.util.NoSuchElementException; import swim.codec.Output; final class UriPathEmpty extends UriPath { @Override public boolean isDefined() { return false; } @Override public boolean isAbsolute() { return false; } @Override public boolean isRelative() { return true; } @Override public boolean isEmpty() { return true; } @Override public String head() { throw new NoSuchElementException(); } @Override public UriPath tail() { throw new UnsupportedOperationException(); } @Override void setTail(UriPath tail) { throw new UnsupportedOperationException(); } @Override UriPath dealias() { return this; } @Override public UriPath parent() { return this; } @Override public UriPath base() { return this; } @Override public UriPath appended(Collection<? extends String> components) { return UriPath.from(components); } @Override public UriPath appendedSlash() { return UriPath.slash(); } @Override public UriPath appendedSegment(String segment) { return UriPath.segment(segment); } @Override public UriPath prepended(Collection<? extends String> components) { return UriPath.from(components); } @Override public UriPath prependedSlash() { return UriPath.slash(); } @Override public UriPath prependedSegment(String segment) { return UriPath.segment(segment); } @Override public UriPath removeDotSegments() { return this; } @Override public UriPath merge(UriPath that) { if (that == null) { throw new NullPointerException(); } return that; } @Override public void debug(Output<?> output) { output = output.write("UriPath").write('.').write("empty").write('(').write(')'); } @Override public void display(Output<?> output) { // nop } @Override public String toString() { return ""; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathForm.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.uri; import swim.codec.ParserException; import swim.structure.Form; import swim.structure.Item; import swim.structure.Text; import swim.structure.Value; public class UriPathForm extends Form<UriPath> { final UriPath unit; UriPathForm(UriPath unit) { this.unit = unit; } @Override public UriPath unit() { return this.unit; } @Override public Form<UriPath> unit(UriPath unit) { return new UriPathForm(unit); } @Override public Class<UriPath> type() { return UriPath.class; } @Override public Item mold(UriPath value) { if (value != null) { return Text.from(value.toString()); } else { return Item.extant(); } } @Override public UriPath cast(Item item) { final Value value = item.target(); try { final String string = value.stringValue(); if (string != null) { return UriPath.parse(string); } } catch (UnsupportedOperationException | ParserException | UriException e) { // swallow } return null; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathIterator.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.uri; import java.util.Iterator; import java.util.NoSuchElementException; final class UriPathIterator implements Iterator<String> { UriPath path; UriPathIterator(UriPath path) { this.path = path; } @Override public boolean hasNext() { return !this.path.isEmpty(); } @Override public String next() { final UriPath path = this.path; if (path.isEmpty()) { throw new NoSuchElementException(); } final String component = path.head(); this.path = path.tail(); return component; } @Override public void remove() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathLiteral.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.uri; import swim.collections.HashTrieMap; final class UriPathLiteral extends UriPathPattern { final String component; final UriPathPattern rest; UriPathLiteral(String component, UriPathPattern rest) { this.component = component; this.rest = rest; } @Override public boolean isUri() { return this.rest.isUri(); } @Override public Uri toUri() { return this.rest.toUri(); } @Override Uri apply(UriScheme scheme, UriAuthority authority, UriPathBuilder path, String[] args, int index) { path.add(this.component); return this.rest.apply(scheme, authority, path, args, index); } @Override HashTrieMap<String, String> unapply(UriPath path, UriQuery query, UriFragment fragment, HashTrieMap<String, String> args) { if (!path.isEmpty() && this.component.equals(path.head())) { return this.rest.unapply(path.tail(), query, fragment, args); } else { return args; } } @Override boolean matches(UriPath path, UriQuery query, UriFragment fragment) { if (!path.isEmpty() && this.component.equals(path.head())) { return this.rest.matches(path.tail(), query, fragment); } else { return false; } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathMapper.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.uri; import swim.collections.HashTrieMap; abstract class UriPathMapper<T> extends UriAuthorityMapper<T> { abstract T get(UriPath path, UriQuery query, UriFragment fragment); @Override T get(UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment) { return get(path, query, fragment); } abstract UriPathMapper<T> merged(UriPathMapper<T> that); @Override UriAuthorityMapper<T> merged(UriAuthorityMapper<T> that) { if (that instanceof UriPathMapper<?>) { return merged((UriPathMapper<T>) that); } else { return that; } } abstract UriPathMapper<T> removed(UriPath path, UriQuery query, UriFragment fragment); @Override UriAuthorityMapper<T> removed(UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment) { return removed(path, query, fragment); } abstract UriPathMapper<T> unmerged(UriPathMapper<T> that); @Override UriAuthorityMapper<T> unmerged(UriAuthorityMapper<T> that) { if (that instanceof UriPathMapper<?>) { return unmerged((UriPathMapper<T>) that); } else { return this; } } @SuppressWarnings("unchecked") static <T> UriPathMapper<T> compile(Uri pattern, UriPath path, UriQuery query, UriFragment fragment, T value) { if (!path.isEmpty()) { final String segment = path.head(); if (!segment.isEmpty() && segment.charAt(0) == ':') { return new UriPathMapping<T>(HashTrieMap.<String, UriPathMapper<T>>empty(), compile(pattern, path.tail(), query, fragment, value), (UriQueryMapper<T>) empty()); } else { return new UriPathMapping<T>(HashTrieMap.<String, UriPathMapper<T>>empty().updated(segment, compile(pattern, path.tail(), query, fragment, value)), (UriPathMapper<T>) empty(), (UriQueryMapper<T>) empty()); } } else { return new UriPathMapping<T>(HashTrieMap.<String, UriPathMapper<T>>empty(), (UriPathMapper<T>) empty(), UriQueryMapper.compile(pattern, query, fragment, value)); } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathMapping.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.uri; import java.util.Iterator; import java.util.Map; import swim.collections.HashTrieMap; import swim.util.Murmur3; final class UriPathMapping<T> extends UriPathMapper<T> { final HashTrieMap<String, UriPathMapper<T>> table; final UriPathMapper<T> wildcard; final UriQueryMapper<T> terminal; UriPathMapping(HashTrieMap<String, UriPathMapper<T>> table, UriPathMapper<T> wildcard, UriQueryMapper<T> terminal) { this.table = table; this.wildcard = wildcard; this.terminal = terminal; } @Override public boolean isEmpty() { return this.table.isEmpty() && this.wildcard.isEmpty() && this.terminal.isEmpty(); } @Override public int size() { int size = 0; final Iterator<UriPathMapper<T>> routes = this.table.valueIterator(); while (routes.hasNext()) { size += routes.next().size(); } size += this.wildcard.size(); size += this.terminal.size(); return size; } @Override public boolean containsValue(Object value) { final Iterator<UriPathMapper<T>> routes = this.table.valueIterator(); while (routes.hasNext()) { if (routes.next().containsValue(value)) { return true; } } return this.wildcard.containsValue(value) || this.terminal.containsValue(value); } @Override T get(UriPath path, UriQuery query, UriFragment fragment) { if (!path.isEmpty()) { UriPathMapper<T> mapping = this.table.get(path.head()); if (mapping == null) { mapping = this.wildcard; } return mapping.get(path.tail(), query, fragment); } else { return this.terminal.get(query, fragment); } } UriPathMapping<T> merged(UriPathMapping<T> that) { HashTrieMap<String, UriPathMapper<T>> table = this.table; final Iterator<Map.Entry<String, UriPathMapper<T>>> routes = that.table.iterator(); while (routes.hasNext()) { final Map.Entry<String, UriPathMapper<T>> route = routes.next(); final String segment = route.getKey(); UriPathMapper<T> mapping = this.table.get(segment); if (mapping != null) { mapping = mapping.merged(route.getValue()); } else { mapping = route.getValue(); } table = table.updated(segment, mapping); } final UriPathMapper<T> wildcard = this.wildcard.merged(that.wildcard); final UriQueryMapper<T> terminal = this.terminal.merged(that.terminal); return new UriPathMapping<T>(table, wildcard, terminal); } @Override UriPathMapper<T> merged(UriPathMapper<T> that) { if (that instanceof UriPathMapping<?>) { return merged((UriPathMapping<T>) that); } else { return that; } } @SuppressWarnings("unchecked") @Override UriPathMapper<T> removed(UriPath path, UriQuery query, UriFragment fragment) { if (!path.isEmpty()) { final String segment = path.head(); if (!segment.isEmpty() && segment.charAt(0) == ':') { final UriPathMapper<T> oldWildcard = this.wildcard; if (oldWildcard != null) { final UriPathMapper<T> newWildcard = oldWildcard.removed(path.tail(), query, fragment); if (oldWildcard != newWildcard) { if (!this.table.isEmpty() || !newWildcard.isEmpty() || !this.terminal.isEmpty()) { return new UriPathMapping<T>(this.table, newWildcard, this.terminal); } else { return (UriPathMapper<T>) empty(); } } } } else { final HashTrieMap<String, UriPathMapper<T>> oldTable = this.table; final UriPathMapper<T> oldMapping = oldTable.get(segment); if (oldMapping != null) { final UriPathMapper<T> newMapping = oldMapping.removed(path.tail(), query, fragment); if (oldMapping != newMapping) { final HashTrieMap<String, UriPathMapper<T>> newTable; if (!newMapping.isEmpty()) { newTable = oldTable.updated(segment, newMapping); } else { newTable = oldTable.removed(segment); } if (!newTable.isEmpty() || !this.wildcard.isEmpty() || !this.terminal.isEmpty()) { return new UriPathMapping<T>(newTable, this.wildcard, this.terminal); } else { return (UriPathMapper<T>) empty(); } } } } } else { final UriQueryMapper<T> oldTerminal = terminal; if (oldTerminal != null) { final UriQueryMapper<T> newTerminal = oldTerminal.removed(query, fragment); if (oldTerminal != newTerminal) { if (!this.table.isEmpty() || !this.wildcard.isEmpty() || !newTerminal.isEmpty()) { return new UriPathMapping<T>(this.table, this.wildcard, newTerminal); } else { return (UriPathMapper<T>) empty(); } } } } return this; } @SuppressWarnings("unchecked") UriPathMapper<T> unmerged(UriPathMapping<T> that) { HashTrieMap<String, UriPathMapper<T>> table = this.table; final Iterator<Map.Entry<String, UriPathMapper<T>>> routes = that.table.iterator(); while (routes.hasNext()) { final Map.Entry<String, UriPathMapper<T>> route = routes.next(); final String segment = route.getKey(); UriPathMapper<T> mapping = this.table.get(segment); if (mapping != null) { mapping = mapping.unmerged(route.getValue()); if (!mapping.isEmpty()) { table = table.updated(segment, mapping); } else { table = table.removed(segment); } } } final UriPathMapper<T> wildcard = this.wildcard.unmerged(that.wildcard); final UriQueryMapper<T> terminal = this.terminal.unmerged(that.terminal); if (!table.isEmpty() || !wildcard.isEmpty() || !terminal.isEmpty()) { return new UriPathMapping<T>(table, wildcard, terminal); } else { return (UriPathMapper<T>) empty(); } } @Override UriPathMapper<T> unmerged(UriPathMapper<T> that) { if (that instanceof UriPathMapping<?>) { return unmerged((UriPathMapping<T>) that); } else { return this; } } @Override public Iterator<Entry<Uri, T>> iterator() { final Iterator<Entry<Uri, T>> tableIterator = new UriPathMappingEntryIterator<T>(this.table.valueIterator()); return new UriPathMappingIterator<Entry<Uri, T>>(tableIterator, this.wildcard.iterator(), this.terminal.iterator()); } @Override public Iterator<Uri> keyIterator() { final Iterator<Uri> tableIterator = new UriPathMappingKeyIterator<T>(this.table.valueIterator()); return new UriPathMappingIterator<Uri>(tableIterator, this.wildcard.keyIterator(), this.terminal.keyIterator()); } @Override public Iterator<T> valueIterator() { final Iterator<T> tableIterator = new UriPathMappingValueIterator<T>(this.table.valueIterator()); return new UriPathMappingIterator<T>(tableIterator, this.wildcard.valueIterator(), this.terminal.valueIterator()); } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriPathMapping<?>) { final UriPathMapping<?> that = (UriPathMapping<?>) other; return this.table.equals(that.table) && this.wildcard.equals(that.wildcard) && this.terminal.equals(that.terminal); } return false; } @Override public int hashCode() { if (hashSeed == 0) { hashSeed = Murmur3.seed(UriPathMapping.class); } return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, this.table.hashCode()), this.wildcard.hashCode()), terminal.hashCode())); } private static int hashSeed; } final class UriPathMappingIterator<T> implements Iterator<T> { final Iterator<T> tableIterator; final Iterator<T> wildcardIterator; final Iterator<T> terminalIterator; UriPathMappingIterator(Iterator<T> tableIterator, Iterator<T> wildcardIterator, Iterator<T> terminalIterator) { this.tableIterator = tableIterator; this.wildcardIterator = wildcardIterator; this.terminalIterator = terminalIterator; } @Override public boolean hasNext() { return this.tableIterator.hasNext() || this.wildcardIterator.hasNext() || this.terminalIterator.hasNext(); } @Override public T next() { if (this.tableIterator.hasNext()) { return this.tableIterator.next(); } else if (this.wildcardIterator.hasNext()) { return this.wildcardIterator.next(); } else { return this.terminalIterator.next(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } final class UriPathMappingEntryIterator<T> extends FlatteningIterator<UriPathMapper<T>, Map.Entry<Uri, T>> { UriPathMappingEntryIterator(Iterator<UriPathMapper<T>> outer) { super(outer); } @Override protected Iterator<Map.Entry<Uri, T>> childIterator(UriPathMapper<T> parent) { return parent.iterator(); } } final class UriPathMappingKeyIterator<T> extends FlatteningIterator<UriPathMapper<T>, Uri> { UriPathMappingKeyIterator(Iterator<UriPathMapper<T>> outer) { super(outer); } @Override protected Iterator<Uri> childIterator(UriPathMapper<T> parent) { return parent.keyIterator(); } } final class UriPathMappingValueIterator<T> extends FlatteningIterator<UriPathMapper<T>, T> { UriPathMappingValueIterator(Iterator<UriPathMapper<T>> outer) { super(outer); } @Override protected Iterator<T> childIterator(UriPathMapper<T> parent) { return parent.valueIterator(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathParser.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.uri; import swim.codec.Base16; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Output; import swim.codec.Parser; import swim.codec.Utf8; final class UriPathParser extends Parser<UriPath> { final UriParser uri; final UriPathBuilder builder; final Output<String> output; final int c1; final int step; UriPathParser(UriParser uri, UriPathBuilder builder, Output<String> output, int c1, int step) { this.uri = uri; this.builder = builder; this.output = output; this.c1 = c1; this.step = step; } UriPathParser(UriParser uri, UriPathBuilder builder) { this(uri, builder, null, 0, 1); } UriPathParser(UriParser uri) { this(uri, null, null, 0, 1); } @Override public Parser<UriPath> feed(Input input) { return parse(input, this.uri, this.builder, this.output, this.c1, this.step); } static Parser<UriPath> parse(Input input, UriParser uri, UriPathBuilder builder, Output<String> output, int c1, int step) { int c = 0; do { if (step == 1) { while (input.isCont()) { c = input.head(); if (Uri.isPathChar(c)) { if (output == null) { output = Utf8.decodedString(); } input = input.step(); output = output.write(c); } else { break; } } if (input.isCont() && c == '/') { input = input.step(); if (builder == null) { builder = uri.pathBuilder(); } if (output != null) { builder.addSegment(output.bind()); output = null; } builder.addSlash(); continue; } else if (input.isCont() && c == '%') { input = input.step(); step = 2; } else if (!input.isEmpty()) { if (output != null) { if (builder == null) { builder = uri.pathBuilder(); } builder.addSegment(output.bind()); } if (builder != null) { return done(builder.bind()); } else { return done(uri.pathEmpty()); } } } if (step == 2) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); c1 = c; step = 3; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 3) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { if (output == null) { output = Utf8.decodedString(); } input = input.step(); output = output.write((Base16.decodeDigit(c1) << 4) | Base16.decodeDigit(c)); c1 = 0; step = 1; continue; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } break; } while (true); if (input.isError()) { return error(input.trap()); } return new UriPathParser(uri, builder, output, c1, step); } static Parser<UriPath> parse(Input input, UriParser uri, UriPathBuilder builder) { return parse(input, uri, builder, null, 0, 1); } static Parser<UriPath> parse(Input input, UriParser uri) { return parse(input, uri, null, null, 0, 1); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathPattern.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.uri; import swim.collections.HashTrieMap; abstract class UriPathPattern extends UriAuthorityPattern { Uri apply(UriScheme scheme, UriAuthority authority, UriPathBuilder path, String[] args, int index) { return apply(scheme, authority, path.bind(), args, index); } @Override Uri apply(UriScheme scheme, UriAuthority authority, String[] args, int index) { return apply(scheme, authority, new UriPathBuilder(), args, index); } abstract HashTrieMap<String, String> unapply(UriPath path, UriQuery query, UriFragment fragment, HashTrieMap<String, String> args); @Override HashTrieMap<String, String> unapply(UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment, HashTrieMap<String, String> args) { return unapply(path, query, fragment, args); } abstract boolean matches(UriPath path, UriQuery query, UriFragment fragment); @Override boolean matches(UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment) { if (!authority.isDefined()) { return matches(path, query, fragment); } else { return false; } } static UriPathPattern compile(Uri pattern, UriPath path, UriQuery query, UriFragment fragment) { if (!path.isEmpty()) { final String component = path.head(); if (!component.isEmpty() && component.charAt(0) == ':') { return new UriPathVariable(component.substring(1), compile(pattern, path.tail(), query, fragment)); } else { return new UriPathLiteral(component, compile(pattern, path.tail(), query, fragment)); } } else { return UriQueryPattern.compile(pattern, query, fragment); } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathSegment.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.uri; import swim.codec.Format; import swim.codec.Output; final class UriPathSegment extends UriPath { final String head; UriPath tail; String string; UriPathSegment(String head, UriPath tail) { if (head.isEmpty()) { throw new IllegalArgumentException(); } this.head = head; this.tail = tail; } @Override public boolean isDefined() { return true; } @Override public boolean isAbsolute() { return false; } @Override public boolean isRelative() { return true; } @Override public boolean isEmpty() { return false; } @Override public String head() { return this.head; } @Override public UriPath tail() { return this.tail; } @Override void setTail(UriPath tail) { if (tail.isAbsolute()) { this.tail = tail; } else { this.tail = UriPath.slash(tail); } } @Override UriPath dealias() { return new UriPathSegment(this.head, this.tail); } @Override public UriPath parent() { final UriPath tail = this.tail; if (tail.isEmpty()) { return UriPath.empty(); } else { final UriPath next = tail.tail(); if (next.isEmpty()) { return UriPath.empty(); } else { return new UriPathSegment(this.head, tail.parent()); } } } @Override public UriPath base() { final UriPath tail = this.tail; if (tail.isEmpty()) { return UriPath.empty(); } else { return new UriPathSegment(this.head, tail.base()); } } @Override public UriPath prependedSegment(String segment) { return UriPath.segment(segment, UriPath.slash(this)); } public UriPath merge(UriPath that) { if (that == null) { throw new NullPointerException(); } return UriPath.merge(this, that); } @Override public void debug(Output<?> output) { output = output.write("UriPath").write('.').write("parse").write('(').write('"') .display(this).write('"').write(')'); } @Override public void display(Output<?> output) { if (this.string != null) { output = output.write(this.string); } else { UriPath.display(this, output); } } @Override public String toString() { if (this.string == null) { this.string = Format.display(this); } return this.string; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathSlash.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.uri; import swim.codec.Format; import swim.codec.Output; final class UriPathSlash extends UriPath { UriPath tail; String string; UriPathSlash(UriPath tail) { this.tail = tail; } @Override public boolean isDefined() { return true; } @Override public boolean isAbsolute() { return true; } @Override public boolean isRelative() { return false; } @Override public boolean isEmpty() { return false; } @Override public String head() { return "/"; } @Override public UriPath tail() { return this.tail; } @Override void setTail(UriPath tail) { this.tail = tail; } @Override UriPath dealias() { return new UriPathSlash(this.tail); } @Override public UriPath parent() { final UriPath tail = this.tail; if (tail.isEmpty()) { return UriPath.empty(); } else { final UriPath next = tail.tail(); if (next.isEmpty()) { return UriPath.slash(); } else { return new UriPathSlash(tail.parent()); } } } @Override public UriPath base() { final UriPath tail = this.tail; if (tail.isEmpty()) { return this; } else { return new UriPathSlash(tail.base()); } } @Override public UriPath prependedSegment(String segment) { return UriPath.segment(segment, this); } public UriPath merge(UriPath that) { if (that == null) { throw new NullPointerException(); } return UriPath.merge(this, that); } @Override public void debug(Output<?> output) { output = output.write("UriPath").write('.').write("parse").write('(').write('"') .display(this).write('"').write(')'); } @Override public void display(Output<?> output) { if (this.string != null) { output = output.write(this.string); } else { UriPath.display(this, output); } } @Override public String toString() { if (this.string == null) { this.string = Format.display(this); } return this.string; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPathVariable.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.uri; import swim.collections.HashTrieMap; final class UriPathVariable extends UriPathPattern { final String name; final UriPathPattern rest; UriPathVariable(String name, UriPathPattern rest) { this.name = name; this.rest = rest; } @Override public boolean isUri() { return false; } @Override public Uri toUri() { return this.rest.toUri(); } @Override Uri apply(UriScheme scheme, UriAuthority authority, UriPathBuilder path, String[] args, int index) { path.add(args[index]); return this.rest.apply(scheme, authority, path, args, index + 1); } @Override HashTrieMap<String, String> unapply(UriPath path, UriQuery query, UriFragment fragment, HashTrieMap<String, String> args) { if (!path.isEmpty()) { return this.rest.unapply(path.tail(), query, fragment, args.updated(this.name, path.head())); } else { return args; } } @Override boolean matches(UriPath path, UriQuery query, UriFragment fragment) { if (!path.isEmpty()) { return this.rest.matches(path.tail(), query, fragment); } else { return false; } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPattern.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.uri; import swim.codec.Debug; import swim.codec.Display; import swim.codec.Output; import swim.collections.HashTrieMap; import swim.structure.Form; import swim.structure.Kind; import swim.util.Murmur3; public abstract class UriPattern implements Debug, Display { UriPattern() { // stub } public abstract boolean isUri(); public abstract Uri toUri(); public Uri apply(String... args) { return apply(args, 0); } Uri apply(String[] args, int index) { return apply(UriScheme.undefined(), args, index); } Uri apply(UriScheme scheme, String[] args, int index) { return apply(scheme, UriAuthority.undefined(), args, index); } Uri apply(UriScheme scheme, UriAuthority authority, String[] args, int index) { return apply(scheme, authority, UriPath.empty(), args, index); } Uri apply(UriScheme scheme, UriAuthority authority, UriPath path, String[] args, int index) { return apply(scheme, authority, path, UriQuery.undefined(), args, index); } Uri apply(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, String[] args, int index) { return apply(scheme, authority, path, query, UriFragment.undefined(), args, index); } Uri apply(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment, String[] args, int index) { return new Uri(scheme, authority, path, query, fragment); } public abstract HashTrieMap<String, String> unapply(Uri uri, HashTrieMap<String, String> defaults); public HashTrieMap<String, String> unapply(String uri, HashTrieMap<String, String> defaults) { return unapply(Uri.parse(uri), defaults); } public HashTrieMap<String, String> unapply(Uri uri) { return unapply(uri, HashTrieMap.<String, String>empty()); } public HashTrieMap<String, String> unapply(String uri) { return unapply(Uri.parse(uri), HashTrieMap.<String, String>empty()); } public abstract boolean matches(Uri uri); public boolean matches(String uri) { return matches(Uri.parse(uri)); } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriPattern) { final UriPattern that = (UriPattern) other; return toUri().equals(that.toUri()); } return false; } @Override public int hashCode() { if (hashSeed == 0) { hashSeed = Murmur3.seed(UriPattern.class); } return Murmur3.mash(Murmur3.mix(hashSeed, toUri().hashCode())); } @Override public void debug(Output<?> output) { final Uri uri = toUri(); output = output.write("UriPattern").write('.'); if (uri.isDefined()) { output = output.write("parse").write('(').debug(uri.toString()).write(')'); } else { output = output.write("empty").write('(').write(')'); } } @Override public void display(Output<?> output) { toUri().display(output); } @Override public String toString() { return toUri().toString(); } private static int hashSeed; private static UriPattern empty; public static UriPattern empty() { if (empty == null) { empty = new UriConstantPattern(Uri.empty()); } return empty; } public static UriPattern from(Uri pattern) { return UriSchemePattern.compile(pattern, pattern.scheme(), pattern.authority(), pattern.path(), pattern.query(), pattern.fragment()); } public static UriPattern parse(String pattern) { return from(Uri.parse(pattern)); } private static Form<UriPattern> form; @Kind public static Form<UriPattern> form() { if (form == null) { form = new UriPatternForm(UriPattern.empty()); } return form; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPatternForm.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.uri; import swim.structure.Form; import swim.structure.Item; import swim.structure.Record; import swim.structure.Text; import swim.structure.Value; public class UriPatternForm extends Form<UriPattern> { final UriPattern unit; UriPatternForm(UriPattern unit) { this.unit = unit; } @Override public Class<UriPattern> type() { return UriPattern.class; } @Override public UriPattern unit() { return this.unit; } @Override public Item mold(UriPattern value) { return value != null ? Text.from(value.toString()) : Value.extant(); } @Override public UriPattern cast(Item value) { if (value instanceof Record) { value = ((Record) value).target(); } try { final String string = value.stringValue(); if (string != null) { return UriPattern.parse(string); } } catch (UriException e) { } return null; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPort.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.uri; import swim.codec.Debug; import swim.codec.Display; import swim.codec.Format; import swim.codec.Output; import swim.util.HashGenCacheSet; import swim.util.Murmur3; public class UriPort implements Comparable<UriPort>, Debug, Display { protected final int number; protected UriPort(int number) { this.number = number; } public final boolean isDefined() { return this.number != 0; } public final int number() { return this.number; } @Override public int compareTo(UriPort that) { return Integer.compare(this.number, that.number); } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriPort) { return this.number == ((UriPort) other).number; } return false; } @Override public int hashCode() { if (hashSeed == 0) { hashSeed = Murmur3.seed(UriPort.class); } return Murmur3.mash(Murmur3.mix(hashSeed, this.number)); } @Override public void debug(Output<?> output) { output = output.write("UriPort").write('.'); if (isDefined()) { output = output.write("from").write('('); Format.displayInt(this.number, output); output = output.write(')'); } else { output = output.write("undefined").write('(').write(')'); } } @Override public void display(Output<?> output) { Format.displayInt(this.number, output); } @Override public String toString() { return Integer.toString(this.number); } private static int hashSeed; private static UriPort undefined; private static HashGenCacheSet<UriPort> cache; public static UriPort undefined() { if (undefined == null) { undefined = new UriPort(0); } return undefined; } public static UriPort from(int number) { if (number > 0) { return cache().put(new UriPort(number)); } else if (number == 0) { return undefined(); } else { throw new IllegalArgumentException(Integer.toString(number)); } } public static UriPort parse(String string) { return Uri.standardParser().parsePortString(string); } static HashGenCacheSet<UriPort> cache() { if (cache == null) { int cacheSize; try { cacheSize = Integer.parseInt(System.getProperty("swim.uri.port.cache.size")); } catch (NumberFormatException e) { cacheSize = 16; } cache = new HashGenCacheSet<UriPort>(cacheSize); } return cache; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriPortParser.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.uri; import swim.codec.Base10; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Parser; final class UriPortParser extends Parser<UriPort> { final UriParser uri; final int number; UriPortParser(UriParser uri, int number) { this.uri = uri; this.number = number; } UriPortParser(UriParser uri) { this(uri, 0); } @Override public Parser<UriPort> feed(Input input) { return parse(input, this.uri, this.number); } static Parser<UriPort> parse(Input input, UriParser uri, int number) { int c = 0; while (input.isCont()) { c = input.head(); if (Base10.isDigit(c)) { input = input.step(); number = 10 * number + Base10.decodeDigit(c); if (number < 0) { return error(Diagnostic.message("port overflow", input)); } } else { break; } } if (!input.isEmpty()) { return done(uri.port(number)); } return new UriPortParser(uri, number); } static Parser<UriPort> parse(Input input, UriParser uri) { return parse(input, uri, 0); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQuery.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.uri; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import swim.codec.Debug; import swim.codec.Display; import swim.codec.Output; import swim.util.HashGenCacheSet; public abstract class UriQuery implements Iterable<Map.Entry<String, String>>, Map<String, String>, Comparable<UriQuery>, Debug, Display { protected UriQuery() { // stub } public abstract boolean isDefined(); @Override public abstract boolean isEmpty(); @Override public int size() { return UriQuery.size(this); } private static int size(UriQuery query) { int n = 0; while (!query.isEmpty()) { n += 1; query = query.tail(); } return n; } public abstract Entry<String, String> head(); public abstract String key(); public abstract String value(); public abstract UriQuery tail(); protected abstract void setTail(UriQuery tail); protected abstract UriQuery dealias(); @Override public boolean containsKey(Object key) { if (key instanceof String) { return UriQuery.containsKey(this, (String) key); } return false; } private static boolean containsKey(UriQuery query, String key) { while (!query.isEmpty()) { if (key.equals(query.key())) { return true; } query = query.tail(); } return false; } @Override public boolean containsValue(Object value) { if (value instanceof String) { return UriQuery.containsValue(this, (String) value); } return false; } private static boolean containsValue(UriQuery query, String value) { while (!query.isEmpty()) { if (value.equals(query.value())) { return true; } query = query.tail(); } return false; } @Override public String get(Object key) { if (key instanceof String) { return UriQuery.get(this, (String) key); } return null; } private static String get(UriQuery query, String key) { while (!query.isEmpty()) { if (key.equals(query.key())) { return query.value(); } query = query.tail(); } return null; } @Override public String put(String key, String value) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends String, ? extends String> params) { throw new UnsupportedOperationException(); } @Override public String remove(Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } public UriQuery updated(String key, String value) { if (key == null) { throw new NullPointerException("key"); } if (value == null) { throw new NullPointerException("value"); } return UriQuery.updated(this, key, value); } private static UriQuery updated(UriQuery query, String key, String value) { final UriQueryBuilder builder = new UriQueryBuilder(); boolean updated = false; while (!query.isEmpty()) { if (key.equals(query.key())) { builder.addParam(key, value); updated = true; } else { builder.addParam(query.key(), query.value()); } query = query.tail(); } if (!updated) { builder.addParam(key, value); } return builder.bind(); } public UriQuery removed(String key) { if (key == null) { throw new NullPointerException(); } final UriQuery newQuery = UriQuery.removed(this, key); if (this != newQuery) { return newQuery; } else { return this; } } private static UriQuery removed(UriQuery query, String key) { final UriQueryBuilder builder = new UriQueryBuilder(); while (!query.isEmpty()) { if (!key.equals(query.key())) { builder.addParam(query.key(), query.value()); } query = query.tail(); } return builder.bind(); } public UriQuery appended(String value) { return appended(null, value); } public UriQuery appended(String key, String value) { final UriQueryBuilder builder = new UriQueryBuilder(); builder.addQuery(this); builder.addParam(key, value); return builder.bind(); } public UriQuery appended(String... keyValuePairs) { return appended(UriQuery.from(keyValuePairs)); } public UriQuery appended(Map<? extends String, ? extends String> params) { final UriQueryBuilder builder = new UriQueryBuilder(); builder.addQuery(this); builder.addAll(params); return builder.bind(); } public UriQuery prepended(String value) { return prepended(null, value); } public UriQuery prepended(String key, String value) { return UriQuery.param(key, value, this); } public UriQuery prepended(String... keyValuePairs) { return prepended(UriQuery.from(keyValuePairs)); } public UriQuery prepended(Map<? extends String, ? extends String> params) { final UriQueryBuilder builder = new UriQueryBuilder(); builder.addAll(params); builder.addQuery(this); return builder.bind(); } @Override public Iterator<Entry<String, String>> iterator() { return new UriQueryEntryIterator(this); } @Override public Set<Entry<String, String>> entrySet() { return new UriQueryEntrySet(this); } @Override public Set<String> keySet() { return new UriQueryKeySet(this); } @Override public Collection<String> values() { return new UriQueryValues(this); } @Override public final int compareTo(UriQuery that) { return toString().compareTo(that.toString()); } @Override public final boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof Map<?, ?>) { return UriQueryEntrySet.equals(this, ((Map<?, ?>) other).entrySet()); } return false; } @Override public final int hashCode() { return UriQueryEntrySet.hashCode(this); } @Override public abstract void debug(Output<?> output); @Override public abstract void display(Output<?> output); static void display(UriQuery query, Output<?> output) { boolean first = true; while (!query.isEmpty()) { if (!first) { output = output.write('&'); } else { first = false; } final String key = query.key(); if (key != null) { Uri.writeParam(key, output); output = output.write('='); } Uri.writeQuery(query.value(), output); query = query.tail(); } } @Override public abstract String toString(); private static UriQuery undefined; private static HashGenCacheSet<String> keyCache; public static UriQueryBuilder builder() { return new UriQueryBuilder(); } public static UriQuery undefined() { if (undefined == null) { undefined = new UriQueryUndefined(); } return undefined; } public static UriQuery param(String key, String value) { return param(key, value, UriQuery.undefined()); } public static UriQuery param(String value) { return param(value, UriQuery.undefined()); } static UriQuery param(String key, String value, UriQuery tail) { if (value == null) { throw new NullPointerException("value"); } if (key != null) { key = UriQuery.cacheKey(key); } return new UriQueryParam(key, value, tail); } static UriQuery param(String value, UriQuery tail) { if (value == null) { throw new NullPointerException("value"); } return new UriQueryParam(null, value, tail); } public static UriQuery from(String... keyValuePairs) { if (keyValuePairs == null) { throw new NullPointerException(); } final int n = keyValuePairs.length; if (n % 2 != 0) { throw new IllegalArgumentException("Odd number of key-value pairs"); } final UriQueryBuilder builder = new UriQueryBuilder(); for (int i = 0; i < n; i += 2) { builder.addParam(keyValuePairs[i], keyValuePairs[i + 1]); } return builder.bind(); } public static UriQuery from(Map<? extends String, ? extends String> params) { if (params == null) { throw new NullPointerException(); } if (params instanceof UriQuery) { return (UriQuery) params; } else { final UriQueryBuilder builder = new UriQueryBuilder(); builder.addAll(params); return builder.bind(); } } public static UriQuery parse(String string) { return Uri.standardParser().parseQueryString(string); } static HashGenCacheSet<String> keyCache() { if (keyCache == null) { int keyCacheSize; try { keyCacheSize = Integer.parseInt(System.getProperty("swim.uri.key.cache.size")); } catch (NumberFormatException e) { keyCacheSize = 64; } keyCache = new HashGenCacheSet<String>(keyCacheSize); } return keyCache; } static String cacheKey(String key) { if (key.length() <= 32) { return keyCache().put(key); } else { return key; } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryBuilder.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.uri; import java.util.Collection; import java.util.Map; import swim.util.EntryBuilder; public final class UriQueryBuilder implements EntryBuilder<String, String, UriQuery> { UriQuery first; UriQuery last; int size; int aliased; public UriQueryBuilder() { this.first = UriQuery.undefined(); this.last = null; this.size = 0; this.aliased = 0; } boolean isEmpty() { return this.size == 0; } @Override public boolean add(String key, String value) { if (value == null) { throw new NullPointerException(); } return addParam(key, value); } @Override public boolean add(Map.Entry<String, String> param) { if (param == null) { throw new NullPointerException(); } return addParam(param.getKey(), param.getValue()); } @Override public boolean addAll(Collection<? extends Map.Entry<String, String>> params) { if (params == null) { throw new NullPointerException(); } boolean modified = false; for (Map.Entry<String, String> param : params) { modified = add(param) || modified; } return modified; } @Override public boolean addAll(Map<? extends String, ? extends String> params) { if (params == null) { throw new NullPointerException(); } if (params instanceof UriQuery) { return addQuery((UriQuery) params); } else { boolean modified = false; for (Map.Entry<? extends String, ? extends String> param : params.entrySet()) { modified = addParam(param.getKey(), param.getValue()) || modified; } return modified; } } @Override public UriQuery bind() { this.aliased = 0; return this.first; } public boolean addParam(String key, String value) { if (value == null) { throw new NullPointerException("value"); } final UriQuery tail = UriQuery.param(key, value, UriQuery.undefined()); final int size = this.size; if (size == 0) { this.first = tail; } else { dealias(size - 1).setTail(tail); } this.last = tail; this.size = size + 1; this.aliased += 1; return true; } public boolean addParam(String value) { return addParam(null, value); } public boolean addQuery(UriQuery query) { if (!query.isEmpty()) { int size = this.size; if (size == 0) { this.first = query; } else { dealias(size - 1).setTail(query); } size += 1; do { final UriQuery tail = query.tail(); if (!tail.isEmpty()) { query = tail; size += 1; } else { break; } } while (true); this.last = query; this.size = size; return true; } return false; } UriQuery dealias(int n) { int i = 0; UriQuery xi = null; UriQuery xs = this.first; if (this.aliased <= n) { while (i < this.aliased) { xi = xs; xs = xs.tail(); i += 1; } while (i <= n) { final UriQuery xn = xs.dealias(); if (i == 0) { this.first = xn; } else { xi.setTail(xn); } xi = xn; xs = xs.tail(); i += 1; } if (i == this.size) { this.last = xi; } this.aliased = i; } else if (n == 0) { xi = this.first; } else if (n == size - 1) { xi = this.last; } else { while (i <= n) { xi = xs; xs = xs.tail(); i += 1; } } return xi; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryEntry.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.uri; import java.util.Map; final class UriQueryEntry implements Map.Entry<String, String> { final String key; final String value; UriQueryEntry(String key, String value) { this.key = key; this.value = value; } @Override public String getKey() { return this.key; } @Override public String getValue() { return this.value; } @Override public String setValue(String value) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof Map.Entry<?, ?>) { final Map.Entry<?, ?> that = (Map.Entry<?, ?>) other; return (this.key == null ? that.getKey() == null : this.key.equals(that.getKey())) && (this.value == null ? that.getValue() == null : this.value.equals(that.getValue())); } return false; } @Override public int hashCode() { return (this.key == null ? 0 : this.key.hashCode()) ^ (this.value == null ? 0 : this.value.hashCode()); } @Override public String toString() { return this.key.toString() + '=' + this.value.toString(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryEntryIterator.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.uri; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; final class UriQueryEntryIterator implements Iterator<Map.Entry<String, String>> { UriQuery query; UriQueryEntryIterator(UriQuery query) { this.query = query; } @Override public boolean hasNext() { return !this.query.isEmpty(); } @Override public Map.Entry<String, String> next() { final UriQuery query = this.query; if (query.isEmpty()) { throw new NoSuchElementException(); } final Map.Entry<String, String> param = query.head(); this.query = query.tail(); return param; } @Override public void remove() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryEntrySet.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.uri; import java.lang.reflect.Array; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; final class UriQueryEntrySet implements Set<Map.Entry<String, String>> { final UriQuery query; UriQueryEntrySet(UriQuery query) { this.query = query; } @Override public boolean isEmpty() { return this.query.isEmpty(); } @Override public int size() { return this.query.size(); } @Override public boolean contains(Object entry) { if (entry instanceof Map.Entry<?, ?>) { return UriQueryEntrySet.contains(this.query, (Map.Entry<?, ?>) entry); } return false; } private static boolean contains(UriQuery query, Map.Entry<?, ?> entry) { while (!query.isEmpty()) { if ((query.key() == null ? entry.getKey() == null : query.key().equals(entry.getKey())) && (query.value() == null ? entry.getValue() == null : query.value().equals(entry.getValue()))) { return true; } query = query.tail(); } return false; } @Override public boolean containsAll(Collection<?> entries) { for (Object entry : entries) { if (!contains(entry)) { return false; } } return true; } @Override public boolean add(Map.Entry<String, String> entry) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends Map.Entry<String, String>> entries) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object entry) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> entries) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> entries) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Iterator<Map.Entry<String, String>> iterator() { return new UriQueryEntryIterator(this.query); } @Override public Object[] toArray() { final Object[] array = new Object[size()]; UriQueryEntrySet.toArray(this.query, array); return array; } @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] array) { final int n = size(); if (array.length < n) { array = (T[]) Array.newInstance(array.getClass().getComponentType(), n); } UriQueryEntrySet.toArray(this.query, array); if (array.length > n) { array[n] = null; } return array; } private static void toArray(UriQuery query, Object[] array) { int i = 0; while (!query.isEmpty()) { array[i] = query.head(); query = query.tail(); i += 1; } } @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()) { return UriQueryEntrySet.equals(this.query, that); } } return false; } static boolean equals(UriQuery query, Set<?> that) { while (!query.isEmpty()) { if (!that.contains(query.head())) { return false; } query = query.tail(); } return true; } @Override public int hashCode() { return UriQueryEntrySet.hashCode(this.query); } static int hashCode(UriQuery query) { int code = 0; while (!query.isEmpty()) { final String key = query.key(); final String value = query.value(); code += (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); query = query.tail(); } return code; } @Override public String toString() { return UriQueryEntrySet.toString(this.query); } private static String toString(UriQuery query) { final StringBuilder s = new StringBuilder(); s.append('['); if (!query.isEmpty()) { s.append(query.head().toString()); query = query.tail(); while (!query.isEmpty()) { s.append(", ").append(query.head().toString()); query = query.tail(); } } s.append(']'); return s.toString(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryKeyIterator.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.uri; import java.util.Iterator; import java.util.NoSuchElementException; final class UriQueryKeyIterator implements Iterator<String> { UriQuery query; UriQueryKeyIterator(UriQuery query) { this.query = query; } @Override public boolean hasNext() { return !this.query.isEmpty(); } @Override public String next() { final UriQuery query = this.query; if (query.isEmpty()) { throw new NoSuchElementException(); } final String key = query.key(); this.query = query.tail(); return key; } @Override public void remove() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryKeySet.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.uri; import java.lang.reflect.Array; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; final class UriQueryKeySet implements Set<String> { final UriQuery query; UriQueryKeySet(UriQuery query) { this.query = query; } @Override public boolean isEmpty() { return this.query.isEmpty(); } @Override public int size() { return this.query.size(); } @Override public boolean contains(Object key) { return this.query.containsKey(key); } @Override public boolean containsAll(Collection<?> keys) { if (keys == null) { throw new NullPointerException(); } return UriQueryKeySet.containsAll(this.query, new HashSet<Object>(keys)); } private static boolean containsAll(UriQuery query, HashSet<?> missing) { while (!query.isEmpty() && !missing.isEmpty()) { missing.remove(query.key()); query = query.tail(); } return missing.isEmpty(); } @Override public boolean add(String key) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends String> keys) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> keys) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> keys) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Iterator<String> iterator() { return new UriQueryKeyIterator(this.query); } @Override public Object[] toArray() { final Object[] array = new Object[size()]; UriQueryKeySet.toArray(this.query, array); return array; } @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] array) { final int n = size(); if (array.length < n) { array = (T[]) Array.newInstance(array.getClass().getComponentType(), n); } UriQueryKeySet.toArray(this.query, array); if (array.length > n) { array[n] = null; } return array; } private static void toArray(UriQuery query, Object[] array) { int i = 0; while (!query.isEmpty()) { array[i] = query.key(); query = query.tail(); i += 1; } } @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()) { return UriQueryKeySet.equals(this.query, that); } } return false; } private static boolean equals(UriQuery query, Set<?> that) { while (!query.isEmpty()) { if (!that.contains(query.key())) { return false; } query = query.tail(); } return true; } @Override public int hashCode() { return UriQueryKeySet.hashCode(this.query); } private static int hashCode(UriQuery query) { int code = 0; while (!query.isEmpty()) { final String key = query.key(); code += (key == null ? 0 : key.hashCode()); query = query.tail(); } return code; } @Override public String toString() { return UriQueryKeySet.toString(this.query); } private static String toString(UriQuery query) { final StringBuilder s = new StringBuilder(); s.append('['); if (!query.isEmpty()) { s.append(String.valueOf(query.key())); query = query.tail(); while (!query.isEmpty()) { s.append(", ").append(String.valueOf(query.key())); query = query.tail(); } } s.append(']'); return s.toString(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryLiteral.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.uri; import swim.collections.HashTrieMap; final class UriQueryLiteral extends UriQueryPattern { final UriQuery query; final UriFragmentPattern rest; UriQueryLiteral(UriQuery query, UriFragmentPattern rest) { this.query = query; this.rest = rest; } @Override public boolean isUri() { return this.rest.isUri(); } @Override public Uri toUri() { return this.rest.toUri(); } @Override Uri apply(UriScheme scheme, UriAuthority authority, UriPath path, String[] args, int index) { return this.rest.apply(scheme, authority, path, this.query, args, index); } @Override HashTrieMap<String, String> unapply(UriQuery query, UriFragment fragment, HashTrieMap<String, String> args) { return this.rest.unapply(fragment, args); } @Override boolean matches(UriQuery query, UriFragment fragment) { if (this.query.equals(query)) { return this.rest.matches(fragment); } else { return false; } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryMapper.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.uri; abstract class UriQueryMapper<T> extends UriPathMapper<T> { abstract T get(UriQuery query, UriFragment fragment); @Override T get(UriPath path, UriQuery query, UriFragment fragment) { if (path.isEmpty()) { return get(query, fragment); } else { return null; } } abstract UriQueryMapper<T> merged(UriQueryMapper<T> that); @Override UriPathMapper<T> merged(UriPathMapper<T> that) { if (that instanceof UriQueryMapper<?>) { return merged((UriQueryMapper<T>) that); } else { return that; } } abstract UriQueryMapper<T> removed(UriQuery query, UriFragment fragment); @Override UriPathMapper<T> removed(UriPath path, UriQuery query, UriFragment fragment) { if (path.isEmpty()) { return removed(query, fragment); } else { return this; } } abstract UriQueryMapper<T> unmerged(UriQueryMapper<T> that); @Override UriPathMapper<T> unmerged(UriPathMapper<T> that) { if (that instanceof UriQueryMapper<?>) { return unmerged((UriQueryMapper<T>) that); } else { return this; } } static <T> UriQueryMapper<T> compile(Uri pattern, UriQuery query, UriFragment fragment, T value) { return UriFragmentMapper.compile(pattern, fragment, value); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryParam.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.uri; import swim.codec.Format; import swim.codec.Output; final class UriQueryParam extends UriQuery { final String key; final String value; UriQuery tail; String string; UriQueryParam(String key, String value, UriQuery tail) { this.key = key; this.value = value; this.tail = tail; } @Override public boolean isDefined() { return true; } @Override public boolean isEmpty() { return false; } @Override public Entry<String, String> head() { return new UriQueryEntry(this.key, this.value); } @Override public String key() { return this.key; } @Override public String value() { return this.value; } @Override public UriQuery tail() { return this.tail; } @Override protected void setTail(UriQuery tail) { this.tail = tail; } @Override protected UriQuery dealias() { return new UriQueryParam(this.key, this.value, this.tail); } @Override public void debug(Output<?> output) { output = output.write("UriQuery").write('.').write("parse").write('(').write('"') .display(this).write('"').write(')'); } @Override public void display(Output<?> output) { if (this.string != null) { output = output.write(this.string); } else { UriQuery.display(this, output); } } @Override public String toString() { if (this.string == null) { this.string = Format.display(this); } return this.string; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryParser.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.uri; import swim.codec.Base16; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Output; import swim.codec.Parser; import swim.codec.Utf8; final class UriQueryParser extends Parser<UriQuery> { final UriParser uri; final UriQueryBuilder builder; final Output<String> keyOutput; final Output<String> valueOutput; final int c1; final int step; UriQueryParser(UriParser uri, UriQueryBuilder builder, Output<String> keyOutput, Output<String> valueOutput, int c1, int step) { this.uri = uri; this.builder = builder; this.keyOutput = keyOutput; this.valueOutput = valueOutput; this.c1 = c1; this.step = step; } UriQueryParser(UriParser uri, UriQueryBuilder builder) { this(uri, builder, null, null, 0, 1); } UriQueryParser(UriParser uri) { this(uri, null, null, null, 0, 1); } @Override public Parser<UriQuery> feed(Input input) { return parse(input, this.uri, this.builder, this.keyOutput, this.valueOutput, this.c1, this.step); } static Parser<UriQuery> parse(Input input, UriParser uri, UriQueryBuilder builder, Output<String> keyOutput, Output<String> valueOutput, int c1, int step) { int c = 0; do { if (step == 1) { if (keyOutput == null) { keyOutput = Utf8.decodedString(); } while (input.isCont()) { c = input.head(); if (Uri.isParamChar(c)) { input = input.step(); keyOutput.write(c); } else { break; } } if (input.isCont() && c == '=') { input = input.step(); step = 4; } else if (input.isCont() && c == '&') { input = input.step(); if (builder == null) { builder = uri.queryBuilder(); } builder.addParam(keyOutput.bind()); keyOutput = null; continue; } else if (input.isCont() && c == '%') { input = input.step(); step = 2; } else if (!input.isEmpty()) { if (builder == null) { builder = uri.queryBuilder(); } builder.addParam(keyOutput.bind()); return done(builder.bind()); } } if (step == 2) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); c1 = c; step = 3; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 3) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); keyOutput.write((Base16.decodeDigit(c1) << 4) | Base16.decodeDigit(c)); c1 = 0; step = 1; continue; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 4) { if (valueOutput == null) { valueOutput = Utf8.decodedString(); } while (input.isCont()) { c = input.head(); if (Uri.isParamChar(c) || c == '=') { input = input.step(); valueOutput.write(c); } else { break; } } if (input.isCont() && c == '&') { input = input.step(); if (builder == null) { builder = uri.queryBuilder(); } builder.addParam(keyOutput.bind(), valueOutput.bind()); keyOutput = null; valueOutput = null; step = 1; continue; } else if (input.isCont() && c == '%') { input = input.step(); step = 5; } else if (!input.isEmpty()) { if (builder == null) { builder = uri.queryBuilder(); } builder.addParam(keyOutput.bind(), valueOutput.bind()); return done(builder.bind()); } } if (step == 5) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); c1 = c; step = 6; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 6) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); valueOutput.write((Base16.decodeDigit(c1) << 4) | Base16.decodeDigit(c)); c1 = 0; step = 4; continue; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } break; } while (true); if (input.isError()) { return error(input.trap()); } return new UriQueryParser(uri, builder, keyOutput, valueOutput, c1, step); } static Parser<UriQuery> parse(Input input, UriParser uri, UriQueryBuilder builder) { return parse(input, uri, builder, null, null, 0, 1); } static Parser<UriQuery> parse(Input input, UriParser uri) { return parse(input, uri, null, null, null, 0, 1); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryPattern.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.uri; import swim.collections.HashTrieMap; abstract class UriQueryPattern extends UriPathPattern { abstract HashTrieMap<String, String> unapply(UriQuery query, UriFragment fragment, HashTrieMap<String, String> args); @Override HashTrieMap<String, String> unapply(UriPath path, UriQuery query, UriFragment fragment, HashTrieMap<String, String> args) { return unapply(query, fragment, args); } abstract boolean matches(UriQuery query, UriFragment fragment); @Override boolean matches(UriPath path, UriQuery query, UriFragment fragment) { if (path.isEmpty()) { return matches(query, fragment); } else { return false; } } static UriQueryPattern compile(Uri pattern, UriQuery query, UriFragment fragment) { if (query.isDefined()) { return new UriQueryLiteral(query, UriFragmentPattern.compile(pattern, fragment)); } else { return UriFragmentPattern.compile(pattern, fragment); } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryUndefined.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.uri; import java.util.Map; import java.util.NoSuchElementException; import swim.codec.Output; final class UriQueryUndefined extends UriQuery { @Override public boolean isDefined() { return false; } @Override public boolean isEmpty() { return true; } @Override public Entry<String, String> head() { throw new NoSuchElementException(); } @Override public String key() { throw new NoSuchElementException(); } @Override public String value() { throw new NoSuchElementException(); } @Override public UriQuery tail() { throw new UnsupportedOperationException(); } @Override protected void setTail(UriQuery tail) { throw new UnsupportedOperationException(); } @Override protected UriQuery dealias() { return this; } @Override public UriQuery updated(String key, String value) { if (key == null) { throw new NullPointerException("key"); } return UriQuery.param(key, value, this); } @Override public UriQuery removed(String key) { if (key == null) { throw new NullPointerException(); } return this; } @Override public UriQuery appended(String value) { return UriQuery.param(value, this); } @Override public UriQuery appended(String key, String value) { return UriQuery.param(key, value, this); } @Override public UriQuery appended(String... keyValuePairs) { return UriQuery.from(keyValuePairs); } @Override public UriQuery appended(Map<? extends String, ? extends String> params) { return UriQuery.from(params); } @Override public UriQuery prepended(String value) { return UriQuery.param(value, this); } @Override public UriQuery prepended(String key, String value) { return UriQuery.param(key, value, this); } @Override public UriQuery prepended(String... keyValuePairs) { return UriQuery.from(keyValuePairs); } @Override public UriQuery prepended(Map<? extends String, ? extends String> params) { return UriQuery.from(params); } @Override public void debug(Output<?> output) { output = output.write("UriQuery").write('.').write("undefined").write('(').write(')'); } @Override public void display(Output<?> output) { // nop } @Override public String toString() { return ""; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryValueIterator.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.uri; import java.util.Iterator; import java.util.NoSuchElementException; final class UriQueryValueIterator implements Iterator<String> { UriQuery query; UriQueryValueIterator(UriQuery query) { this.query = query; } @Override public boolean hasNext() { return !this.query.isEmpty(); } @Override public String next() { final UriQuery query = this.query; if (query.isEmpty()) { throw new NoSuchElementException(); } final String value = query.value(); this.query = query.tail(); return value; } @Override public void remove() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriQueryValues.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.uri; import java.lang.reflect.Array; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; final class UriQueryValues implements Collection<String> { final UriQuery query; UriQueryValues(UriQuery query) { this.query = query; } @Override public boolean isEmpty() { return this.query.isEmpty(); } @Override public int size() { return this.query.size(); } @Override public boolean contains(Object value) { return this.query.containsValue(value); } @Override public boolean containsAll(Collection<?> values) { if (values == null) { throw new NullPointerException(); } return UriQueryValues.containsAll(this.query, new HashSet<Object>(values)); } private static boolean containsAll(UriQuery query, HashSet<?> missing) { while (!query.isEmpty() && !missing.isEmpty()) { missing.remove(query.value()); query = query.tail(); } return missing.isEmpty(); } @Override public boolean add(String value) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends String> values) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object value) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> values) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> values) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Iterator<String> iterator() { return new UriQueryValueIterator(this.query); } @Override public Object[] toArray() { final Object[] array = new Object[size()]; UriQueryValues.toArray(this.query, array); return array; } @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] array) { final int n = size(); if (array.length < n) { array = (T[]) Array.newInstance(array.getClass().getComponentType(), n); } UriQueryValues.toArray(this.query, array); if (array.length > n) { array[n] = null; } return array; } private static void toArray(UriQuery query, Object[] array) { int i = 0; while (!query.isEmpty()) { array[i] = query.value(); query = query.tail(); i += 1; } } @Override public String toString() { return UriQueryValues.toString(this.query); } private static String toString(UriQuery query) { final StringBuilder s = new StringBuilder(); s.append('['); if (!query.isEmpty()) { s.append(String.valueOf(query.value())); query = query.tail(); while (!query.isEmpty()) { s.append(", ").append(String.valueOf(query.value())); query = query.tail(); } } s.append(']'); return s.toString(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriScheme.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.uri; import swim.codec.Debug; import swim.codec.Display; import swim.codec.Output; import swim.util.HashGenCacheMap; import swim.util.Murmur3; public class UriScheme implements Comparable<UriScheme>, Debug, Display { protected final String name; protected UriScheme(String name) { this.name = name; } public final boolean isDefined() { return this.name.length() > 0; } public final String name() { return this.name; } @Override public final int compareTo(UriScheme that) { return this.name.compareTo(that.name); } @Override public final boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriScheme) { return this.name.equals(((UriScheme) other).name); } return false; } @Override public final int hashCode() { return Murmur3.seed(this.name); } @Override public void debug(Output<?> output) { output = output.write("UriScheme").write('.'); if (isDefined()) { output = output.write("parse").write('(').write('"').display(this).write('"').write(')'); } else { output = output.write("undefined").write('(').write(')'); } } @Override public void display(Output<?> output) { Uri.writeScheme(this.name, output); } @Override public final String toString() { return this.name; } private static UriScheme undefined; private static HashGenCacheMap<String, UriScheme> cache; public static UriScheme undefined() { if (undefined == null) { undefined = new UriScheme(""); } return undefined; } public static UriScheme from(String name) { if (name == null) { throw new NullPointerException(); } final HashGenCacheMap<String, UriScheme> cache = cache(); final UriScheme scheme = cache.get(name); if (scheme != null) { return scheme; } else { return cache.put(name, new UriScheme(name)); } } public static UriScheme parse(String string) { return Uri.standardParser().parseSchemeString(string); } static HashGenCacheMap<String, UriScheme> cache() { if (cache == null) { int cacheSize; try { cacheSize = Integer.parseInt(System.getProperty("swim.uri.scheme.cache.size")); } catch (NumberFormatException e) { cacheSize = 4; } cache = new HashGenCacheMap<String, UriScheme>(cacheSize); } return cache; } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriSchemeLiteral.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.uri; import swim.collections.HashTrieMap; final class UriSchemeLiteral extends UriSchemePattern { final UriScheme scheme; final UriAuthorityPattern rest; UriSchemeLiteral(UriScheme scheme, UriAuthorityPattern rest) { this.scheme = scheme; this.rest = rest; } @Override public boolean isUri() { return this.rest.isUri(); } @Override public Uri toUri() { return this.rest.toUri(); } @Override Uri apply(String[] args, int index) { return this.rest.apply(this.scheme, args, index); } @Override HashTrieMap<String, String> unapply(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment, HashTrieMap<String, String> args) { if (this.scheme.equals(scheme)) { return this.rest.unapply(authority, path, query, fragment, args); } else { return args; } } @Override boolean matches(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment) { if (this.scheme.equals(scheme)) { return this.rest.matches(authority, path, query, fragment); } else { return false; } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriSchemeMapper.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.uri; import swim.collections.HashTrieMap; abstract class UriSchemeMapper<T> extends UriMapper<T> { abstract T get(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment); @Override public T get(Uri uri) { return get(uri.scheme(), uri.authority(), uri.path(), uri.query(), uri.fragment()); } abstract UriSchemeMapper<T> merged(UriSchemeMapper<T> that); @Override public UriMapper<T> merged(UriMapper<T> that) { if (that instanceof UriSchemeMapper<?>) { return merged((UriSchemeMapper<T>) that); } else { return that; } } abstract UriSchemeMapper<T> removed(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment); @Override public UriMapper<T> removed(Uri pattern) { return removed(pattern.scheme(), pattern.authority(), pattern.path(), pattern.query(), pattern.fragment()); } abstract UriSchemeMapper<T> unmerged(UriSchemeMapper<T> that); @Override public UriMapper<T> unmerged(UriMapper<T> that) { if (that instanceof UriSchemeMapper<?>) { return unmerged((UriSchemeMapper<T>) that); } else { return this; } } static <T> UriSchemeMapper<T> compile(Uri pattern, UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment, T value) { if (scheme.isDefined()) { return new UriSchemeMapping<T>(HashTrieMap.<String, UriAuthorityMapper<T>>empty().updated(scheme.name(), UriAuthorityMapper.compile(pattern, authority, path, query, fragment, value))); } else { return UriAuthorityMapper.compile(pattern, authority, path, query, fragment, value); } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriSchemeMapping.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.uri; import java.util.Iterator; import java.util.Map; import swim.collections.HashTrieMap; import swim.util.Murmur3; final class UriSchemeMapping<T> extends UriSchemeMapper<T> { final HashTrieMap<String, UriAuthorityMapper<T>> table; UriSchemeMapping(HashTrieMap<String, UriAuthorityMapper<T>> table) { this.table = table; } @Override public boolean isEmpty() { return this.table.isEmpty(); } @Override public int size() { int size = 0; final Iterator<UriAuthorityMapper<T>> routes = this.table.valueIterator(); while (routes.hasNext()) { size += routes.next().size(); } return size; } @Override public boolean containsValue(Object value) { final Iterator<UriAuthorityMapper<T>> routes = this.table.valueIterator(); while (routes.hasNext()) { if (routes.next().containsValue(value)) { return true; } } return false; } @Override T get(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment) { final UriAuthorityMapper<T> mapping = this.table.get(scheme.name()); if (mapping != null) { return mapping.get(authority, path, query, fragment); } else { return null; } } UriSchemeMapping<T> merged(UriSchemeMapping<T> that) { HashTrieMap<String, UriAuthorityMapper<T>> table = this.table; final Iterator<Map.Entry<String, UriAuthorityMapper<T>>> routes = that.table.iterator(); while (routes.hasNext()) { final Map.Entry<String, UriAuthorityMapper<T>> route = routes.next(); final String schemeName = route.getKey(); UriAuthorityMapper<T> mapping = this.table.get(schemeName); if (mapping != null) { mapping = mapping.merged(route.getValue()); } else { mapping = route.getValue(); } table = table.updated(schemeName, mapping); } return new UriSchemeMapping<T>(table); } @Override UriSchemeMapper<T> merged(UriSchemeMapper<T> that) { if (that instanceof UriSchemeMapping<?>) { return merged((UriSchemeMapping<T>) that); } else { return that; } } @SuppressWarnings("unchecked") @Override UriSchemeMapper<T> removed(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment) { final String schemeName = scheme.name(); final UriAuthorityMapper<T> oldMapping = this.table.get(schemeName); if (oldMapping != null) { final UriAuthorityMapper<T> newMapping = oldMapping.removed(authority, path, query, fragment); if (oldMapping != newMapping) { if (!oldMapping.isEmpty()) { return new UriSchemeMapping<T>(this.table.updated(schemeName, newMapping)); } else { return (UriSchemeMapper<T>) empty(); } } } return this; } @SuppressWarnings("unchecked") UriSchemeMapper<T> unmerged(UriSchemeMapping<T> that) { HashTrieMap<String, UriAuthorityMapper<T>> table = this.table; final Iterator<Map.Entry<String, UriAuthorityMapper<T>>> routes = that.table.iterator(); while (routes.hasNext()) { final Map.Entry<String, UriAuthorityMapper<T>> route = routes.next(); final String schemeName = route.getKey(); UriAuthorityMapper<T> mapping = table.get(schemeName); if (mapping != null) { mapping = mapping.unmerged(route.getValue()); if (!mapping.isEmpty()) { table = table.updated(schemeName, mapping); } else { table = table.removed(schemeName); } } } if (!table.isEmpty()) { return new UriSchemeMapping<T>(table); } else { return (UriSchemeMapper<T>) empty(); } } @Override UriSchemeMapper<T> unmerged(UriSchemeMapper<T> that) { if (that instanceof UriSchemeMapping<?>) { return unmerged((UriSchemeMapping<T>) that); } else { return this; } } @Override public Iterator<Entry<Uri, T>> iterator() { return new UriSchemeMappingIterator<T>(this.table.valueIterator()); } @Override public Iterator<Uri> keyIterator() { return new UriSchemeMappingKeyIterator<T>(this.table.valueIterator()); } @Override public Iterator<T> valueIterator() { return new UriSchemeMappingValueIterator<T>(this.table.valueIterator()); } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriSchemeMapping<?>) { final UriSchemeMapping<?> that = (UriSchemeMapping<?>) other; return this.table.equals(that.table); } return false; } @Override public int hashCode() { if (hashSeed == 0) { hashSeed = Murmur3.seed(UriSchemeMapping.class); } return Murmur3.mash(Murmur3.mix(hashSeed, this.table.hashCode())); } private static int hashSeed; } final class UriSchemeMappingIterator<T> extends FlatteningIterator<UriAuthorityMapper<T>, Map.Entry<Uri, T>> { UriSchemeMappingIterator(Iterator<UriAuthorityMapper<T>> outer) { super(outer); } @Override protected Iterator<Map.Entry<Uri, T>> childIterator(UriAuthorityMapper<T> parent) { return parent.iterator(); } } final class UriSchemeMappingKeyIterator<T> extends FlatteningIterator<UriAuthorityMapper<T>, Uri> { UriSchemeMappingKeyIterator(Iterator<UriAuthorityMapper<T>> outer) { super(outer); } @Override protected Iterator<Uri> childIterator(UriAuthorityMapper<T> parent) { return parent.keyIterator(); } } final class UriSchemeMappingValueIterator<T> extends FlatteningIterator<UriAuthorityMapper<T>, T> { UriSchemeMappingValueIterator(Iterator<UriAuthorityMapper<T>> outer) { super(outer); } @Override protected Iterator<T> childIterator(UriAuthorityMapper<T> parent) { return parent.valueIterator(); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriSchemeParser.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.uri; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Output; import swim.codec.Parser; import swim.codec.Utf8; final class UriSchemeParser extends Parser<UriScheme> { final UriParser uri; final Output<String> output; final int step; UriSchemeParser(UriParser uri, Output<String> output, int step) { this.uri = uri; this.output = output; this.step = step; } UriSchemeParser(UriParser uri) { this(uri, null, 1); } @Override public Parser<UriScheme> feed(Input input) { return parse(input, this.uri, this.output, this.step); } static Parser<UriScheme> parse(Input input, UriParser uri, Output<String> output, int step) { int c = 0; if (step == 1) { if (input.isCont()) { c = input.head(); if (Uri.isAlpha(c)) { input = input.step(); if (output == null) { output = Utf8.decodedString(); } output = output.write(Character.toLowerCase(c)); step = 2; } else { return error(Diagnostic.expected("scheme", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("scheme", input)); } } if (step == 2) { while (input.isCont()) { c = input.head(); if (Uri.isSchemeChar(c)) { input = input.step(); output = output.write(Character.toLowerCase(c)); } else { break; } } if (!input.isEmpty()) { return done(uri.scheme(output.bind())); } } return new UriSchemeParser(uri, output, step); } static Parser<UriScheme> parse(Input input, UriParser uri) { return parse(input, uri, null, 1); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriSchemePattern.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.uri; import swim.collections.HashTrieMap; abstract class UriSchemePattern extends UriPattern { abstract HashTrieMap<String, String> unapply(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment, HashTrieMap<String, String> args); @Override public HashTrieMap<String, String> unapply(Uri uri, HashTrieMap<String, String> args) { return unapply(uri.scheme(), uri.authority(), uri.path(), uri.query(), uri.fragment(), args); } abstract boolean matches(UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment); @Override public boolean matches(Uri uri) { return matches(uri.scheme(), uri.authority(), uri.path(), uri.query(), uri.fragment()); } static UriSchemePattern compile(Uri pattern, UriScheme scheme, UriAuthority authority, UriPath path, UriQuery query, UriFragment fragment) { if (scheme.isDefined()) { return new UriSchemeLiteral(scheme, UriAuthorityPattern.compile(pattern, authority, path, query, fragment)); } else { return UriAuthorityPattern.compile(pattern, authority, path, query, fragment); } } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriTerminalMapper.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.uri; abstract class UriTerminalMapper<T> extends UriFragmentMapper<T> { abstract T get(); @Override T get(UriFragment fragment) { return get(); } UriTerminalMapper<T> merged(UriTerminalMapper<T> that) { if (that.isEmpty()) { return this; } else { return that; } } @Override UriFragmentMapper<T> merged(UriFragmentMapper<T> that) { if (that instanceof UriTerminalMapper<?>) { return merged((UriTerminalMapper<T>) that); } else { return that; } } @SuppressWarnings("unchecked") public UriTerminalMapper<T> removed() { return (UriTerminalMapper<T>) empty(); } @Override UriFragmentMapper<T> removed(UriFragment fragment) { return removed(); } @SuppressWarnings("unchecked") UriTerminalMapper<T> unmerged(UriTerminalMapper<T> that) { return (UriTerminalMapper<T>) empty(); } @Override UriFragmentMapper<T> unmerged(UriFragmentMapper<T> that) { if (that instanceof UriTerminalMapper<?>) { return unmerged((UriTerminalMapper<T>) that); } else { return this; } } static <T> UriTerminalMapper<T> compile(Uri pattern, T value) { return new UriConstantMapping<T>(pattern, value); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriTerminalPattern.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.uri; import swim.collections.HashTrieMap; abstract class UriTerminalPattern extends UriFragmentPattern { abstract HashTrieMap<String, String> unapply(HashTrieMap<String, String> args); @Override HashTrieMap<String, String> unapply(UriFragment fragment, HashTrieMap<String, String> args) { return unapply(args); } abstract boolean matches(); @Override boolean matches(UriFragment fragment) { if (!fragment.isDefined()) { return matches(); } else { return false; } } static UriTerminalPattern compile(Uri pattern) { return new UriConstantPattern(pattern); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriUser.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.uri; import swim.codec.Debug; import swim.codec.Display; import swim.codec.Format; import swim.codec.Output; import swim.util.Murmur3; public class UriUser implements Debug, Display { protected final String username; protected final String password; protected UriUser(String username, String password) { this.username = username; this.password = password; } public boolean isDefined() { return this.username != null; } public String username() { return this.username != null ? this.username : ""; } public UriUser username(String username) { if (username != this.username) { return copy(username, this.password); } else { return this; } } public String password() { return this.password != null ? this.password : ""; } public UriUser password(String password) { if (password != this.password) { return copy(this.username, password); } else { return this; } } protected UriUser copy(String username, String password) { return UriUser.from(username, password); } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof UriUser) { final UriUser that = (UriUser) other; return (this.username == null ? that.username == null : this.username.equals(that.username)) && (this.password == null ? that.password == null : this.password.equals(that.password)); } return false; } @Override public int hashCode() { if (hashSeed == 0) { hashSeed = Murmur3.seed(UriUser.class); } return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed, Murmur3.hash(this.username)), Murmur3.hash(this.password))); } @Override public void debug(Output<?> output) { output = output.write("UriUser").write('.'); if (isDefined()) { output = output.write("parse").write('(').write('"').display(this).write('"').write(')'); } else { output = output.write("undefined").write('(').write(')'); } } @Override public void display(Output<?> output) { if (this.username != null) { Uri.writeUser(this.username, output); if (this.password != null) { output = output.write(':'); Uri.writeUser(this.password, output); } } } @Override public String toString() { return Format.display(this); } private static int hashSeed; private static UriUser undefined; public static UriUser undefined() { if (undefined == null) { undefined = new UriUser(null, null); } return undefined; } public static UriUser from(String username) { if (username != null) { return new UriUser(username, null); } else { return undefined(); } } public static UriUser from(String username, String password) { if (username != null || password != null) { if (username == null) { username = ""; } return new UriUser(username, password); } else { return undefined(); } } public static UriUser parse(String string) { return Uri.standardParser().parseUserString(string); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/UriUserParser.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.uri; import swim.codec.Base16; import swim.codec.Diagnostic; import swim.codec.Input; import swim.codec.Output; import swim.codec.Parser; import swim.codec.Utf8; final class UriUserParser extends Parser<UriUser> { final UriParser uri; final Output<String> usernameOutput; final Output<String> passwordOutput; final int c1; final int step; UriUserParser(UriParser uri, Output<String> usernameOutput, Output<String> passwordOutput, int c1, int step) { this.uri = uri; this.usernameOutput = usernameOutput; this.passwordOutput = passwordOutput; this.c1 = c1; this.step = step; } UriUserParser(UriParser uri) { this(uri, null, null, 0, 1); } @Override public Parser<UriUser> feed(Input input) { return parse(input, this.uri, this.usernameOutput, this.passwordOutput, this.c1, this.step); } static Parser<UriUser> parse(Input input, UriParser uri, Output<String> usernameOutput, Output<String> passwordOutput, int c1, int step) { int c = 0; do { if (step == 1) { if (usernameOutput == null) { usernameOutput = Utf8.decodedString(); } while (input.isCont()) { c = input.head(); if (Uri.isUserChar(c)) { input = input.step(); usernameOutput.write(c); } else { break; } } if (input.isCont() && c == ':') { input = input.step(); step = 4; } else if (input.isCont() && c == '%') { input = input.step(); step = 2; } else if (!input.isEmpty()) { return done(uri.user(usernameOutput.bind(), null)); } } if (step == 2) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); c1 = c; step = 3; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 3) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); usernameOutput.write((Base16.decodeDigit(c1) << 4) | Base16.decodeDigit(c)); c1 = 0; step = 1; continue; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 4) { if (passwordOutput == null) { passwordOutput = Utf8.decodedString(); } while (input.isCont()) { c = input.head(); if (Uri.isUserInfoChar(c)) { input = input.step(); passwordOutput.write(c); } else { break; } } if (input.isCont() && c == '%') { input = input.step(); step = 5; } else if (!input.isEmpty()) { return done(uri.user(usernameOutput.bind(), passwordOutput.bind())); } } if (step == 5) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); c1 = c; step = 6; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } if (step == 6) { if (input.isCont()) { c = input.head(); if (Base16.isDigit(c)) { input = input.step(); passwordOutput.write((Base16.decodeDigit(c1) << 4) | Base16.decodeDigit(c)); c1 = 0; step = 4; continue; } else { return error(Diagnostic.expected("hex digit", input)); } } else if (input.isDone()) { return error(Diagnostic.expected("hex digit", input)); } } break; } while (true); if (input.isError()) { return error(input.trap()); } return new UriUserParser(uri, usernameOutput, passwordOutput, c1, step); } static Parser<UriUser> parse(Input input, UriParser uri) { return parse(input, uri, null, null, 0, 1); } }
0
java-sources/ai/swim/swim-uri/3.10.0/swim
java-sources/ai/swim/swim-uri/3.10.0/swim/uri/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. /** * Uniform resource identifiers. */ package swim.uri;
0
java-sources/ai/swim/swim-util
java-sources/ai/swim/swim-util/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. /** * Utility library. */ module swim.util { exports swim.util; }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/Builder.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.util; import java.util.Collection; /** * Type that accumulates input values of type {@code I}, and binds an output * result of type {@code O}. */ public interface Builder<I, O> { /** * Adds a single input value to this builder, returning {@code true} if the * state of the builder changed. */ boolean add(I input); /** * Adds multiple input values to this builder, returning {@code true} if the * state of the builder changed. */ boolean addAll(Collection<? extends I> inputs); /** * Returns the output result of this builder. */ O bind(); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/CombinerFunction.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.util; @FunctionalInterface public interface CombinerFunction<V, U> { U combine(U result, V element); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/Cursor.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.util; import java.util.ListIterator; import java.util.Map; public interface Cursor<T> extends ListIterator<T> { boolean isEmpty(); T head(); void step(); void skip(long count); @Override boolean hasNext(); long nextIndexLong(); @Override default int nextIndex() { final long k = nextIndexLong(); final int i = (int) k; if (i != k) { throw new IndexOutOfBoundsException("index overflow"); } return i; } @Override T next(); boolean hasPrevious(); long previousIndexLong(); @Override default int previousIndex() { final long k = previousIndexLong(); final int i = (int) k; if (i != k) { throw new IndexOutOfBoundsException("index overflow"); } return i; } T previous(); @Override default void set(T object) { throw new UnsupportedOperationException(); } @Override default void add(T object) { throw new UnsupportedOperationException(); } @Override default void remove() { throw new UnsupportedOperationException(); } default void load() throws InterruptedException { // stub } static <T> Cursor<T> empty() { return new CursorEmpty<T>(); } static <T> Cursor<T> unary(T value) { return new CursorUnary<T>(value); } static <T> Cursor<T> array(Object[] array, int index, int limit) { return new CursorArray<T>(array, index, limit); } static <T> Cursor<T> array(Object[] array, int index) { return new CursorArray<T>(array, index, array.length); } static <T> Cursor<T> array(Object[] array) { return new CursorArray<T>(array, 0, array.length); } static <K> Cursor<K> keys(Cursor<? extends Map.Entry<? extends K, ?>> entries) { return new CursorKeys<K>(entries); } static <V> Cursor<V> values(Cursor<? extends Map.Entry<?, ? extends V>> entries) { return new CursorValues<V>(entries); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/CursorArray.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.util; import java.util.NoSuchElementException; final class CursorArray<T> implements Cursor<T> { final Object[] array; int index; int limit; CursorArray(Object[] array, int index, int limit) { this.array = array; this.index = index; this.limit = limit; } @Override public boolean isEmpty() { return this.index >= this.limit; } @SuppressWarnings("unchecked") @Override public T head() { if (this.index < this.limit) { return (T) 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; } @SuppressWarnings("unchecked") @Override public T next() { final int index = this.index; if (index < this.limit) { this.index = index + 1; return (T) 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; } @SuppressWarnings("unchecked") @Override public T previous() { final int index = this.index - 1; if (index >= 0) { this.index = index; return (T) this.array[index]; } else { this.index = 0; throw new NoSuchElementException(); } } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/CursorEmpty.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.util; import java.util.NoSuchElementException; final class CursorEmpty<T> implements Cursor<T> { @Override public boolean isEmpty() { return true; } @Override public T head() { throw new NoSuchElementException(); } @Override public void step() { throw new UnsupportedOperationException(); } @Override public void skip(long count) { // nop } @Override public boolean hasNext() { return false; } @Override public long nextIndexLong() { return 0L; } @Override public T next() { throw new NoSuchElementException(); } @Override public boolean hasPrevious() { return false; } @Override public long previousIndexLong() { return -1L; } @Override public T previous() { throw new NoSuchElementException(); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/CursorKeys.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.util; import java.util.Map; final class CursorKeys<K> implements Cursor<K> { final Cursor<? extends Map.Entry<? extends K, ?>> inner; CursorKeys(Cursor<? extends Map.Entry<? extends K, ?>> inner) { this.inner = inner; } @Override public boolean isEmpty() { return this.inner.isEmpty(); } @Override public K head() { return this.inner.head().getKey(); } @Override public void step() { this.inner.step(); } @Override public void skip(long count) { this.inner.skip(count); } @Override public boolean hasNext() { return this.inner.hasNext(); } @Override public long nextIndexLong() { return this.inner.nextIndexLong(); } @Override public int nextIndex() { return this.inner.nextIndex(); } @Override public K next() { return this.inner.next().getKey(); } @Override public boolean hasPrevious() { return this.inner.hasPrevious(); } @Override public long previousIndexLong() { return this.inner.previousIndexLong(); } @Override public int previousIndex() { return this.inner.previousIndex(); } @Override public K previous() { return this.inner.previous().getKey(); } @Override public void load() throws InterruptedException { this.inner.load(); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/CursorUnary.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.util; import java.util.NoSuchElementException; final class CursorUnary<T> implements Cursor<T> { final T value; int index; CursorUnary(T value) { this.value = value; this.index = 0; } @Override public boolean isEmpty() { return this.index != 0; } @Override public T head() { if (this.index == 0) { return this.value; } else { throw new NoSuchElementException(); } } @Override public void step() { if (this.index == 0) { this.index = 1; } else { throw new UnsupportedOperationException(); } } @Override public void skip(long count) { this.index = (int) Math.min(Math.max(0L, (long) this.index + count), 1L); } @Override public boolean hasNext() { return this.index == 0; } @Override public long nextIndexLong() { return (long) this.index; } @Override public int nextIndex() { return this.index; } @Override public T next() { if (this.index == 0) { this.index = 1; return this.value; } else { throw new NoSuchElementException(); } } @Override public boolean hasPrevious() { return this.index == 1; } @Override public long previousIndexLong() { return (long) (this.index - 1); } @Override public int previousIndex() { return this.index - 1; } @Override public T previous() { if (this.index == 1) { this.index = 0; return this.value; } else { throw new NoSuchElementException(); } } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/CursorValues.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.util; import java.util.Map; final class CursorValues<V> implements Cursor<V> { final Cursor<? extends Map.Entry<?, ? extends V>> inner; CursorValues(Cursor<? extends Map.Entry<?, ? extends V>> inner) { this.inner = inner; } @Override public boolean isEmpty() { return this.inner.isEmpty(); } @Override public V head() { return this.inner.head().getValue(); } @Override public void step() { this.inner.step(); } @Override public void skip(long count) { this.inner.skip(count); } @Override public boolean hasNext() { return this.inner.hasNext(); } @Override public long nextIndexLong() { return this.inner.nextIndexLong(); } @Override public int nextIndex() { return this.inner.nextIndex(); } @Override public V next() { return this.inner.next().getValue(); } @Override public boolean hasPrevious() { return this.inner.hasPrevious(); } @Override public long previousIndexLong() { return this.inner.previousIndexLong(); } @Override public int previousIndex() { return this.inner.previousIndex(); } @Override public V previous() { return this.inner.previous().getValue(); } @Override public void load() throws InterruptedException { this.inner.load(); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/EntryBuilder.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.util; import java.util.Collection; import java.util.Map; /** * Type that accumulates map entries, and binds an output result of type * {@code O}. */ public interface EntryBuilder<K, V, O> extends PairBuilder<K, V, O>, Builder<Map.Entry<K, V>, O> { /** * Adds an input pair to this builder, returning {@code true} if the state * of the builder changed. */ @Override boolean add(K key, V value); /** * Adds a single entry to this builder, returning {@code true} if the state * of the builder changed. */ @Override boolean add(Map.Entry<K, V> input); /** * Adds multiple entries to this builder, returning {@code true} if the state * of the builder changed. */ @Override boolean addAll(Collection<? extends Map.Entry<K, V>> inputs); /** * Adds multiple entries to this builder, returning {@code true} if the state * of the builder changed. */ boolean addAll(Map<? extends K, ? extends V> inputs); /** * Returns the output result of this builder. */ @Override O bind(); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/HashGenCacheMap.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.util; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceArray; /** * A hashed generational cache map discards the least recently used value * with the worst hit rate per hash bucket. HashGenCacheMap is a concurrent * and lock-free LRFU cache, with O(1) access time. * * <p>Maintaining four "generations" of cached values per hash bucket, the cache * discards from the younger generations based on least recent usage, and * promotes younger generations to older generations based on most frequent * usage. Cache misses count as negative usage of the older generations, * biasing the cache against least recently used values with poor hit rates.</p> * * <p>The cache soft references the older generations, and weak references the * younger generations; the garbage collector can reclaim the entire cache, * but will preferentially wipe the younger cache generations before the older * cache generations.</p> */ public class HashGenCacheMap<K, V> { final AtomicReferenceArray<HashGenCacheMapBucket<K, V>> buckets; volatile int gen4Hits; volatile int gen3Hits; volatile int gen2Hits; volatile int gen1Hits; volatile int misses; public HashGenCacheMap(int size) { this.buckets = new AtomicReferenceArray<HashGenCacheMapBucket<K, V>>(size); } public V get(K key) { if (this.buckets.length() == 0) { return null; } final int index = Math.abs(key.hashCode()) % this.buckets.length(); final HashGenCacheMapBucket<K, V> bucket = this.buckets.get(index); if (bucket == null) { return null; } final K gen4Key = bucket.gen4KeyRef.get(); if (gen4Key != null && key.equals(gen4Key)) { final V gen4Val = bucket.gen4ValRef.get(); if (gen4Val != null) { GEN4_HITS.incrementAndGet(this); BUCKET_GEN4_WEIGHT.incrementAndGet(bucket); return gen4Val; } else { bucket.gen4KeyRef.clear(); } } final K gen3Key = bucket.gen3KeyRef.get(); if (gen3Key != null && key.equals(gen3Key)) { final V gen3Val = bucket.gen3ValRef.get(); if (gen3Val != null) { GEN3_HITS.incrementAndGet(this); if (BUCKET_GEN3_WEIGHT.incrementAndGet(bucket) > bucket.gen4Weight) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight)); } return gen3Val; } else { bucket.gen3KeyRef.clear(); } } final K gen2Key = bucket.gen2KeyRef.get(); if (gen2Key != null && key.equals(gen2Key)) { final V gen2Val = bucket.gen2ValRef.get(); if (gen2Val != null) { GEN2_HITS.incrementAndGet(this); if (BUCKET_GEN2_WEIGHT.incrementAndGet(bucket) > bucket.gen3Weight) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight)); } return gen2Val; } else { bucket.gen2KeyRef.clear(); } } final K gen1Key = bucket.gen1KeyRef.get(); if (gen1Key != null && key.equals(gen1Key)) { final V gen1Val = bucket.gen1ValRef.get(); if (gen1Val != null) { GEN1_HITS.incrementAndGet(this); if (BUCKET_GEN1_WEIGHT.incrementAndGet(bucket) > bucket.gen2Weight) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight)); } return gen1Val; } else { bucket.gen1KeyRef.clear(); } } MISSES.incrementAndGet(this); return null; } public V put(K key, V value) { if (this.buckets.length() == 0) { return value; } final int index = Math.abs(key.hashCode()) % this.buckets.length(); HashGenCacheMapBucket<K, V> bucket = this.buckets.get(index); if (bucket == null) { bucket = new HashGenCacheMapBucket<K, V>(); } K gen4Key = bucket.gen4KeyRef.get(); if (gen4Key != null && key.equals(gen4Key)) { final V gen4Val = bucket.gen4ValRef.get(); if (gen4Val != null) { GEN4_HITS.incrementAndGet(this); BUCKET_GEN4_WEIGHT.incrementAndGet(bucket); return gen4Val; } else { bucket.gen4KeyRef.clear(); gen4Key = null; } } K gen3Key = bucket.gen3KeyRef.get(); if (gen3Key != null && key.equals(gen3Key)) { final V gen3Val = bucket.gen3ValRef.get(); if (gen3Val != null) { GEN3_HITS.incrementAndGet(this); if (BUCKET_GEN3_WEIGHT.incrementAndGet(bucket) > bucket.gen4Weight) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight)); } return gen3Val; } else { bucket.gen3KeyRef.clear(); gen3Key = null; } } K gen2Key = bucket.gen2KeyRef.get(); if (gen2Key != null && key.equals(gen2Key)) { final V gen2Val = bucket.gen2ValRef.get(); if (gen2Val != null) { GEN2_HITS.incrementAndGet(this); if (BUCKET_GEN2_WEIGHT.incrementAndGet(bucket) > bucket.gen3Weight) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight)); } return gen2Val; } else { bucket.gen2KeyRef.clear(); gen2Key = null; } } K gen1Key = bucket.gen1KeyRef.get(); if (gen1Key != null && key.equals(gen1Key)) { final V gen1Val = bucket.gen1ValRef.get(); if (gen1Val != null) { GEN1_HITS.incrementAndGet(this); if (BUCKET_GEN1_WEIGHT.incrementAndGet(bucket) > bucket.gen2Weight) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight)); } return gen1Val; } else { bucket.gen1KeyRef.clear(); gen1Key = null; } } MISSES.incrementAndGet(this); if (gen4Key == null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, new SoftReference<K>(key), new SoftReference<V>(value), 1)); } else if (gen3Key == null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, new SoftReference<K>(key), new SoftReference<V>(value), 1)); } else if (gen2Key == null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, new SoftReference<K>(key), new SoftReference<V>(value), 1)); } else if (gen1Key == null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, new SoftReference<K>(key), new SoftReference<V>(value), 1)); } else { // Penalize older gens for thrash. Promote gen1 to prevent nacent gens // from flip-flopping. If sacrificed gen2 was worth keeping, it likely // would have already been promoted. this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight - 1, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight - 1, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, new SoftReference<K>(key), new SoftReference<V>(value), 1)); } return value; } public boolean weaken(K key) { if (this.buckets.length() == 0) { return false; } final int index = Math.abs(key.hashCode()) % this.buckets.length(); final HashGenCacheMapBucket<K, V> bucket = this.buckets.get(index); if (bucket == null) { return false; } K gen4Key = bucket.gen4KeyRef.get(); if (gen4Key != null && key.equals(gen4Key)) { final V gen4Val = bucket.gen4ValRef.get(); if (gen4Val != null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( weakRef(bucket.gen4KeyRef), weakRef(bucket.gen4ValRef), bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight)); return true; } else { bucket.gen4KeyRef.clear(); gen4Key = null; } } K gen3Key = bucket.gen3KeyRef.get(); if (gen3Key != null && key.equals(gen3Key)) { final V gen3Val = bucket.gen3ValRef.get(); if (gen3Val != null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, weakRef(bucket.gen3KeyRef), weakRef(bucket.gen3ValRef), bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight)); return true; } else { bucket.gen3KeyRef.clear(); gen3Key = null; } } K gen2Key = bucket.gen2KeyRef.get(); if (gen2Key != null && key.equals(gen2Key)) { final V gen2Val = bucket.gen2ValRef.get(); if (gen2Val != null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, weakRef(bucket.gen2KeyRef), weakRef(bucket.gen2ValRef), bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight)); return true; } else { bucket.gen2KeyRef.clear(); gen2Key = null; } } K gen1Key = bucket.gen1KeyRef.get(); if (gen1Key != null && key.equals(gen1Key)) { final V gen1Val = bucket.gen1ValRef.get(); if (gen1Val != null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, weakRef(bucket.gen1KeyRef), weakRef(bucket.gen1ValRef), bucket.gen1Weight)); return true; } else { bucket.gen1KeyRef.clear(); gen1Key = null; } } if (gen4Key == null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 1)); } else if (gen3Key == null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 1)); } else if (gen2Key == null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 1)); } else if (gen1Key == null) { this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 1)); } return false; } public V remove(K key) { if (this.buckets.length() == 0) { return null; } final int index = Math.abs(key.hashCode()) % this.buckets.length(); final HashGenCacheMapBucket<K, V> bucket = this.buckets.get(index); if (bucket == null) { return null; } final K gen4Key = bucket.gen4KeyRef.get(); if (gen4Key != null && key.equals(gen4Key)) { final V gen4Val = bucket.gen4ValRef.get(); this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 0)); return gen4Val; } final K gen3Key = bucket.gen3KeyRef.get(); if (gen3Key != null && key.equals(gen3Key)) { final V gen3Val = bucket.gen3ValRef.get(); this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 0)); return gen3Val; } final K gen2Key = bucket.gen2KeyRef.get(); if (gen2Key != null && key.equals(gen2Key)) { final V gen2Val = bucket.gen2ValRef.get(); this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1KeyRef, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 0)); return gen2Val; } final K gen1Key = bucket.gen1KeyRef.get(); if (gen1Key != null && key.equals(gen1Key)) { final V gen1Val = bucket.gen1ValRef.get(); this.buckets.set(index, new HashGenCacheMapBucket<K, V>( bucket.gen4KeyRef, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3KeyRef, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2KeyRef, bucket.gen2ValRef, bucket.gen2Weight, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 0)); return gen1Val; } return null; } public void clear() { for (int i = 0; i < this.buckets.length(); i += 1) { this.buckets.set(i, null); } } long hits() { return (long) this.gen4Hits + (long) this.gen3Hits + (long) this.gen2Hits + (long) this.gen1Hits; } public double hitRatio() { final double hits = (double) hits(); return hits / (hits + (double) this.misses); } static final <T> WeakReference<T> weakRef(Reference<T> ref) { if (ref instanceof WeakReference<?>) { return (WeakReference<T>) ref; } else { return new WeakReference<T>(ref.get()); } } @SuppressWarnings("unchecked") static final <T> SoftReference<T> nullRef() { return (SoftReference<T>) NULL_REF; } static final SoftReference<Object> NULL_REF = new SoftReference<Object>(null); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMapBucket<?, ?>> BUCKET_GEN4_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMapBucket<?, ?>>) (Class<?>) HashGenCacheMapBucket.class, "gen4Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMapBucket<?, ?>> BUCKET_GEN3_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMapBucket<?, ?>>) (Class<?>) HashGenCacheMapBucket.class, "gen3Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMapBucket<?, ?>> BUCKET_GEN2_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMapBucket<?, ?>>) (Class<?>) HashGenCacheMapBucket.class, "gen2Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMapBucket<?, ?>> BUCKET_GEN1_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMapBucket<?, ?>>) (Class<?>) HashGenCacheMapBucket.class, "gen1Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMap<?, ?>> GEN4_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMap<?, ?>>) (Class<?>) HashGenCacheMap.class, "gen4Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMap<?, ?>> GEN3_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMap<?, ?>>) (Class<?>) HashGenCacheMap.class, "gen3Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMap<?, ?>> GEN2_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMap<?, ?>>) (Class<?>) HashGenCacheMap.class, "gen2Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMap<?, ?>> GEN1_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMap<?, ?>>) (Class<?>) HashGenCacheMap.class, "gen1Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheMap<?, ?>> MISSES = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheMap<?, ?>>) (Class<?>) HashGenCacheMap.class, "misses"); } final class HashGenCacheMapBucket<K, V> { final Reference<K> gen4KeyRef; final Reference<V> gen4ValRef; final Reference<K> gen3KeyRef; final Reference<V> gen3ValRef; final Reference<K> gen2KeyRef; final Reference<V> gen2ValRef; final Reference<K> gen1KeyRef; final Reference<V> gen1ValRef; volatile int gen4Weight; volatile int gen3Weight; volatile int gen2Weight; volatile int gen1Weight; HashGenCacheMapBucket(Reference<K> gen4KeyRef, Reference<V> gen4ValRef, int gen4Weight, Reference<K> gen3KeyRef, Reference<V> gen3ValRef, int gen3Weight, Reference<K> gen2KeyRef, Reference<V> gen2ValRef, int gen2Weight, Reference<K> gen1KeyRef, Reference<V> gen1ValRef, int gen1Weight) { this.gen4KeyRef = gen4KeyRef; this.gen4ValRef = gen4ValRef; this.gen4Weight = gen4Weight; this.gen3KeyRef = gen3KeyRef; this.gen3ValRef = gen3ValRef; this.gen3Weight = gen3Weight; this.gen2KeyRef = gen2KeyRef; this.gen2ValRef = gen2ValRef; this.gen2Weight = gen2Weight; this.gen1KeyRef = gen1KeyRef; this.gen1ValRef = gen1ValRef; this.gen1Weight = gen1Weight; } HashGenCacheMapBucket() { this(HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 0, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 0, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 0, HashGenCacheMap.<K>nullRef(), HashGenCacheMap.<V>nullRef(), 0); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/HashGenCacheSet.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.util; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceArray; /** * A hashed generational cache set discards the least recently used value * with the worst hit rate per hash bucket. HashGenCacheSet is a concurrent * and lock-free LRFU cache, with O(1) access time. * * <p>Maintaining four "generations" of cached values per hash bucket, the cache * discards from the younger generations based on least recent usage, and * promotes younger generations to older generations based on most frequent * usage. Cache misses count as negative usage of the older generations, * biasing the cache against least recently used values with poor hit rates.</p> * * <p>The cache soft references the older generations, and weak references the * younger generations; the garbage collector can reclaim the entire cache, * but will preferentially wipe the younger cache generations before the older * cache generations.</p> */ public class HashGenCacheSet<T> { final AtomicReferenceArray<HashGenCacheSetBucket<T>> buckets; volatile int gen4Hits; volatile int gen3Hits; volatile int gen2Hits; volatile int gen1Hits; volatile int misses; public HashGenCacheSet(int size) { this.buckets = new AtomicReferenceArray<HashGenCacheSetBucket<T>>(size); } public T put(T value) { if (this.buckets.length() == 0) { return value; } final int index = Math.abs(value.hashCode()) % this.buckets.length(); HashGenCacheSetBucket<T> bucket = this.buckets.get(index); if (bucket == null) { bucket = new HashGenCacheSetBucket<T>(); } final T gen4Val = bucket.gen4ValRef.get(); if (gen4Val != null && value.equals(gen4Val)) { GEN4_HITS.incrementAndGet(this); BUCKET_GEN4_WEIGHT.incrementAndGet(bucket); return gen4Val; } final T gen3Val = bucket.gen3ValRef.get(); if (gen3Val != null && value.equals(gen3Val)) { GEN3_HITS.incrementAndGet(this); if (BUCKET_GEN3_WEIGHT.incrementAndGet(bucket) > bucket.gen4Weight) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen3ValRef, bucket.gen3Weight, bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight)); } return gen3Val; } final T gen2Val = bucket.gen2ValRef.get(); if (gen2Val != null && value.equals(gen2Val)) { GEN2_HITS.incrementAndGet(this); if (BUCKET_GEN2_WEIGHT.incrementAndGet(bucket) > bucket.gen3Weight) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1ValRef, bucket.gen1Weight)); } return gen2Val; } final T gen1Val = bucket.gen1ValRef.get(); if (gen1Val != null && value.equals(gen1Val)) { GEN1_HITS.incrementAndGet(this); if (BUCKET_GEN1_WEIGHT.incrementAndGet(bucket) > bucket.gen2Weight) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1ValRef, bucket.gen1Weight, bucket.gen2ValRef, bucket.gen2Weight)); } return gen1Val; } MISSES.incrementAndGet(this); if (gen4Val == null) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight, new SoftReference<T>(value), 1)); } else if (gen3Val == null) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight, new SoftReference<T>(value), 1)); } else if (gen2Val == null) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1ValRef, bucket.gen1Weight, new SoftReference<T>(value), 1)); } else if (gen1Val == null) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, new SoftReference<T>(value), 1)); } else { // Penalize older gens for thrash. Promote gen1 to prevent nacent gens // from flip-flopping. If sacrificed gen2 was worth keeping, it likely // would have already been promoted. this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight - 1, bucket.gen3ValRef, bucket.gen3Weight - 1, bucket.gen1ValRef, bucket.gen1Weight, new SoftReference<T>(value), 1)); } return value; } public boolean weaken(T value) { if (this.buckets.length() == 0) { return false; } final int index = Math.abs(value.hashCode()) % this.buckets.length(); final HashGenCacheSetBucket<T> bucket = this.buckets.get(index); if (bucket == null) { return false; } final T gen4Val = bucket.gen4ValRef.get(); if (gen4Val != null && value.equals(gen4Val)) { this.buckets.set(index, new HashGenCacheSetBucket<T>( weakRef(bucket.gen4ValRef), bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight)); return true; } final T gen3Val = bucket.gen3ValRef.get(); if (gen3Val != null && value.equals(gen3Val)) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, weakRef(bucket.gen3ValRef), bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight)); return true; } final T gen2Val = bucket.gen2ValRef.get(); if (gen2Val != null && value.equals(gen2Val)) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, weakRef(bucket.gen2ValRef), bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight)); return true; } final T gen1Val = bucket.gen1ValRef.get(); if (gen1Val != null && value.equals(gen1Val)) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, weakRef(bucket.gen1ValRef), bucket.gen1Weight)); return true; } if (gen4Val == null) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheSet.<T>nullRef(), 1)); } else if (gen3Val == null) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheSet.<T>nullRef(), 1)); } else if (gen2Val == null) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheSet.<T>nullRef(), 1)); } else if (gen1Val == null) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, HashGenCacheSet.<T>nullRef(), 1)); } return false; } public boolean remove(T value) { if (this.buckets.length() == 0) { return false; } final int index = Math.abs(value.hashCode()) % this.buckets.length(); final HashGenCacheSetBucket<T> bucket = this.buckets.get(index); if (bucket == null) { return false; } final T gen4Val = bucket.gen4ValRef.get(); if (gen4Val != null && value.equals(gen4Val)) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheSet.<T>nullRef(), 0)); return true; } final T gen3Val = bucket.gen3ValRef.get(); if (gen3Val != null && value.equals(gen3Val)) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen2ValRef, bucket.gen2Weight, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheSet.<T>nullRef(), 0)); return true; } final T gen2Val = bucket.gen2ValRef.get(); if (gen2Val != null && value.equals(gen2Val)) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen1ValRef, bucket.gen1Weight, HashGenCacheSet.<T>nullRef(), 0)); return true; } final T gen1Val = bucket.gen1ValRef.get(); if (gen1Val != null && value.equals(gen1Val)) { this.buckets.set(index, new HashGenCacheSetBucket<T>( bucket.gen4ValRef, bucket.gen4Weight, bucket.gen3ValRef, bucket.gen3Weight, bucket.gen2ValRef, bucket.gen2Weight, HashGenCacheSet.<T>nullRef(), 0)); return true; } return false; } public void clear() { for (int i = 0; i < this.buckets.length(); i += 1) { this.buckets.set(i, null); } } long hits() { return (long) this.gen4Hits + (long) this.gen3Hits + (long) this.gen2Hits + (long) this.gen1Hits; } public double hitRatio() { final double hits = (double) hits(); return hits / (hits + (double) this.misses); } static final <T> WeakReference<T> weakRef(Reference<T> ref) { if (ref instanceof WeakReference<?>) { return (WeakReference<T>) ref; } else { return new WeakReference<T>(ref.get()); } } @SuppressWarnings("unchecked") static final <T> SoftReference<T> nullRef() { return (SoftReference<T>) NULL_REF; } static final SoftReference<Object> NULL_REF = new SoftReference<Object>(null); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSetBucket<?>> BUCKET_GEN4_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSetBucket<?>>) (Class<?>) HashGenCacheSetBucket.class, "gen4Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSetBucket<?>> BUCKET_GEN3_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSetBucket<?>>) (Class<?>) HashGenCacheSetBucket.class, "gen3Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSetBucket<?>> BUCKET_GEN2_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSetBucket<?>>) (Class<?>) HashGenCacheSetBucket.class, "gen2Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSetBucket<?>> BUCKET_GEN1_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSetBucket<?>>) (Class<?>) HashGenCacheSetBucket.class, "gen1Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSet<?>> GEN4_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSet<?>>) (Class<?>) HashGenCacheSet.class, "gen4Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSet<?>> GEN3_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSet<?>>) (Class<?>) HashGenCacheSet.class, "gen3Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSet<?>> GEN2_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSet<?>>) (Class<?>) HashGenCacheSet.class, "gen2Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSet<?>> GEN1_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSet<?>>) (Class<?>) HashGenCacheSet.class, "gen1Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenCacheSet<?>> MISSES = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenCacheSet<?>>) (Class<?>) HashGenCacheSet.class, "misses"); } final class HashGenCacheSetBucket<T> { final Reference<T> gen4ValRef; final Reference<T> gen3ValRef; final Reference<T> gen2ValRef; final Reference<T> gen1ValRef; volatile int gen4Weight; volatile int gen3Weight; volatile int gen2Weight; volatile int gen1Weight; HashGenCacheSetBucket(Reference<T> gen4ValRef, int gen4Weight, Reference<T> gen3ValRef, int gen3Weight, Reference<T> gen2ValRef, int gen2Weight, Reference<T> gen1ValRef, int gen1Weight) { this.gen4ValRef = gen4ValRef; this.gen4Weight = gen4Weight; this.gen3ValRef = gen3ValRef; this.gen3Weight = gen3Weight; this.gen2ValRef = gen2ValRef; this.gen2Weight = gen2Weight; this.gen1ValRef = gen1ValRef; this.gen1Weight = gen1Weight; } HashGenCacheSetBucket() { this(HashGenCacheSet.<T>nullRef(), 0, HashGenCacheSet.<T>nullRef(), 0, HashGenCacheSet.<T>nullRef(), 0, HashGenCacheSet.<T>nullRef(), 0); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/HashGenMap.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.util; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceArray; /** * A hashed generational map evicts the least recently used value with the * worst hit rate per hash bucket. HashGenMap is a concurrent and lock-free * LRFU cache, with O(1) access time, that strongly references its values. * * Maintaining four "generations" of cached values per hash bucket, the cache * discards from the younger generations based on least recent usage, and * promotes younger generations to older generations based on most frequent * usage. Cache misses count as negative usage of the older generations, * biasing the cache against least recently used values with poor hit rates. * * The evict(K, V) method is guaranteed to be called when a value is displaced * from the cache. */ public class HashGenMap<K, V> { final AtomicReferenceArray<HashGenMapBucket<K, V>> buckets; volatile int gen4Hits; volatile int gen3Hits; volatile int gen2Hits; volatile int gen1Hits; volatile int misses; volatile int evicts; public HashGenMap(int size) { this.buckets = new AtomicReferenceArray<HashGenMapBucket<K, V>>(size); } protected void evict(K key, V value) { // stub } public V get(K key) { if (this.buckets.length() == 0) { return null; } HashGenMapBucket<K, V> bucket; HashGenMapBucket<K, V> newBucket; V cacheVal; final int index = Math.abs(key.hashCode()) % this.buckets.length(); do { bucket = this.buckets.get(index); if (bucket == null) { newBucket = null; cacheVal = null; } else { if (bucket.gen4Key != null && key.equals(bucket.gen4Key)) { GEN4_HITS.incrementAndGet(this); BUCKET_GEN4_WEIGHT.incrementAndGet(bucket); newBucket = bucket; cacheVal = bucket.gen4Val; } else if (bucket.gen3Key != null && key.equals(bucket.gen3Key)) { GEN3_HITS.incrementAndGet(this); if (BUCKET_GEN3_WEIGHT.incrementAndGet(bucket) > bucket.gen4Weight) { newBucket = new HashGenMapBucket<K, V>( bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight); } else { newBucket = bucket; } cacheVal = bucket.gen3Val; } else if (bucket.gen2Key != null && key.equals(bucket.gen2Key)) { GEN2_HITS.incrementAndGet(this); if (BUCKET_GEN2_WEIGHT.incrementAndGet(bucket) > bucket.gen3Weight) { newBucket = new HashGenMapBucket<K, V>( bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight, bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight); } else { newBucket = bucket; } cacheVal = bucket.gen2Val; } else if (bucket.gen1Key != null && key.equals(bucket.gen1Key)) { GEN1_HITS.incrementAndGet(this); if (BUCKET_GEN1_WEIGHT.incrementAndGet(bucket) > bucket.gen2Weight) { newBucket = new HashGenMapBucket<K, V>( bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight); } else { newBucket = bucket; } cacheVal = bucket.gen1Val; } else { MISSES.incrementAndGet(this); newBucket = bucket; cacheVal = null; } } } while (bucket != newBucket && !this.buckets.compareAndSet(index, bucket, newBucket)); return cacheVal; } public V put(K key, V value) { if (this.buckets.length() == 0) { return value; } HashGenMapBucket<K, V> bucket; HashGenMapBucket<K, V> newBucket; K evictKey = null; V evictVal = null; V cacheVal; final int index = Math.abs(key.hashCode()) % this.buckets.length(); do { bucket = this.buckets.get(index); if (bucket == null) { newBucket = new HashGenMapBucket<K, V>(key, value); cacheVal = value; } else { if (bucket.gen4Key != null && key.equals(bucket.gen4Key)) { GEN4_HITS.incrementAndGet(this); BUCKET_GEN4_WEIGHT.incrementAndGet(bucket); newBucket = bucket; cacheVal = bucket.gen4Val; } else if (bucket.gen3Key != null && key.equals(bucket.gen3Key)) { GEN3_HITS.incrementAndGet(this); if (BUCKET_GEN3_WEIGHT.incrementAndGet(bucket) > bucket.gen4Weight) { newBucket = new HashGenMapBucket<K, V>( bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight); } else { newBucket = bucket; } cacheVal = bucket.gen3Val; } else if (bucket.gen2Key != null && key.equals(bucket.gen2Key)) { GEN2_HITS.incrementAndGet(this); if (BUCKET_GEN2_WEIGHT.incrementAndGet(bucket) > bucket.gen3Weight) { newBucket = new HashGenMapBucket<K, V>( bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight, bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight); } else { newBucket = bucket; } cacheVal = bucket.gen2Val; } else if (bucket.gen1Key != null && key.equals(bucket.gen1Key)) { GEN1_HITS.incrementAndGet(this); if (BUCKET_GEN1_WEIGHT.incrementAndGet(bucket) > bucket.gen2Weight) { newBucket = new HashGenMapBucket<K, V>( bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight); } else { newBucket = bucket; } cacheVal = bucket.gen1Val; } else { MISSES.incrementAndGet(this); evictKey = bucket.gen2Key; evictVal = bucket.gen2Val; // Penalize older gens for thrash. Promote gen1 to prevent nacent gens // from flip-flopping. If sacrificed gen2 was worth keeping, it likely // would have already been promoted. newBucket = new HashGenMapBucket<K, V>( bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight - 1, bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight - 1, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight, key, value, 1); cacheVal = value; } } } while (bucket != newBucket && !this.buckets.compareAndSet(index, bucket, newBucket)); if (evictKey != null) { EVICTS.incrementAndGet(this); evict(evictKey, evictVal); } return cacheVal; } public V remove(K key) { if (this.buckets.length() == 0) { return null; } HashGenMapBucket<K, V> bucket; HashGenMapBucket<K, V> newBucket; V cacheVal; final int index = Math.abs(key.hashCode()) % this.buckets.length(); do { bucket = this.buckets.get(index); if (bucket == null) { cacheVal = null; newBucket = null; } else { if (bucket.gen4Key != null && key.equals(bucket.gen4Key)) { cacheVal = bucket.gen4Val; newBucket = new HashGenMapBucket<K, V>( bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight, null, null, 0); } else if (bucket.gen3Key != null && key.equals(bucket.gen3Key)) { cacheVal = bucket.gen3Val; newBucket = new HashGenMapBucket<K, V>( bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight, null, null, 0); } else if (bucket.gen2Key != null && key.equals(bucket.gen2Key)) { cacheVal = bucket.gen2Val; newBucket = new HashGenMapBucket<K, V>( bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen1Key, bucket.gen1Val, bucket.gen1Weight, null, null, 0); } else if (bucket.gen1Key != null && key.equals(bucket.gen1Key)) { cacheVal = bucket.gen1Val; newBucket = new HashGenMapBucket<K, V>( bucket.gen4Key, bucket.gen4Val, bucket.gen4Weight, bucket.gen3Key, bucket.gen3Val, bucket.gen3Weight, bucket.gen2Key, bucket.gen2Val, bucket.gen2Weight, null, null, 0); } else { cacheVal = null; newBucket = bucket; } } } while (bucket != newBucket && !this.buckets.compareAndSet(index, bucket, newBucket)); return cacheVal; } public void clear() { for (int i = 0; i < this.buckets.length(); i += 1) { this.buckets.set(i, null); } } public long hits() { return (long) this.gen4Hits + (long) this.gen3Hits + (long) this.gen2Hits + (long) this.gen1Hits; } public double hitRatio() { final double hits = (double) hits(); return hits / (hits + (double) this.misses); } @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMapBucket<?, ?>> BUCKET_GEN4_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMapBucket<?, ?>>) (Class<?>) HashGenMapBucket.class, "gen4Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMapBucket<?, ?>> BUCKET_GEN3_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMapBucket<?, ?>>) (Class<?>) HashGenMapBucket.class, "gen3Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMapBucket<?, ?>> BUCKET_GEN2_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMapBucket<?, ?>>) (Class<?>) HashGenMapBucket.class, "gen2Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMapBucket<?, ?>> BUCKET_GEN1_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMapBucket<?, ?>>) (Class<?>) HashGenMapBucket.class, "gen1Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMap<?, ?>> GEN4_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMap<?, ?>>) (Class<?>) HashGenMap.class, "gen4Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMap<?, ?>> GEN3_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMap<?, ?>>) (Class<?>) HashGenMap.class, "gen3Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMap<?, ?>> GEN2_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMap<?, ?>>) (Class<?>) HashGenMap.class, "gen2Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMap<?, ?>> GEN1_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMap<?, ?>>) (Class<?>) HashGenMap.class, "gen1Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMap<?, ?>> MISSES = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMap<?, ?>>) (Class<?>) HashGenMap.class, "misses"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenMap<?, ?>> EVICTS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenMap<?, ?>>) (Class<?>) HashGenMap.class, "evicts"); } final class HashGenMapBucket<K, V> { final K gen4Key; final V gen4Val; final K gen3Key; final V gen3Val; final K gen2Key; final V gen2Val; final K gen1Key; final V gen1Val; volatile int gen4Weight; volatile int gen3Weight; volatile int gen2Weight; volatile int gen1Weight; HashGenMapBucket(K gen4Key, V gen4Val, int gen4Weight, K gen3Key, V gen3Val, int gen3Weight, K gen2Key, V gen2Val, int gen2Weight, K gen1Key, V gen1Val, int gen1Weight) { this.gen4Key = gen4Key; this.gen4Val = gen4Val; this.gen4Weight = gen4Weight; this.gen3Key = gen3Key; this.gen3Val = gen3Val; this.gen3Weight = gen3Weight; this.gen2Key = gen2Key; this.gen2Val = gen2Val; this.gen2Weight = gen2Weight; this.gen1Key = gen1Key; this.gen1Val = gen1Val; this.gen1Weight = gen1Weight; } HashGenMapBucket(K key, V value) { this(null, null, 0, null, null, 0, null, null, 0, key, value, 1); } HashGenMapBucket() { this(null, null, 0, null, null, 0, null, null, 0, null, null, 0); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/HashGenSet.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.util; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceArray; /** * A hashed generational set evicts the least recently used value with the * worst hit rate per hash bucket. HashGenSet is a concurrent and lock-free * LRFU cache, with O(1) access time, that strongly references its values. * * Maintaining four "generations" of cached values per hash bucket, the cache * discards from the younger generations based on least recent usage, and * promotes younger generations to older generations based on most frequent * usage. Cache misses count as negative usage of the older generations, * biasing the cache against least recently used values with poor hit rates. * * The evict(V) method is guaranteed to be called when a value is displaced * from the cache. */ public class HashGenSet<V> { final AtomicReferenceArray<HashGenSetBucket<V>> buckets; volatile int gen4Hits; volatile int gen3Hits; volatile int gen2Hits; volatile int gen1Hits; volatile int misses; volatile int evicts; public HashGenSet(int size) { buckets = new AtomicReferenceArray<HashGenSetBucket<V>>(size); } protected void evict(V value) { } public V put(V value) { if (buckets.length() == 0) { return value; } HashGenSetBucket<V> bucket; HashGenSetBucket<V> newBucket; V evictVal = null; V cacheVal; final int index = Math.abs(value.hashCode()) % buckets.length(); do { bucket = buckets.get(index); if (bucket == null) { newBucket = new HashGenSetBucket<V>(value); cacheVal = value; } else { if (bucket.gen4Val != null && value.equals(bucket.gen4Val)) { GEN4_HITS.incrementAndGet(this); BUCKET_GEN4_WEIGHT.incrementAndGet(bucket); newBucket = bucket; cacheVal = bucket.gen4Val; } else if (bucket.gen3Val != null && value.equals(bucket.gen3Val)) { GEN3_HITS.incrementAndGet(this); if (BUCKET_GEN3_WEIGHT.incrementAndGet(bucket) > bucket.gen4Weight) { newBucket = new HashGenSetBucket<V>( bucket.gen3Val, bucket.gen3Weight, bucket.gen4Val, bucket.gen4Weight, bucket.gen2Val, bucket.gen2Weight, bucket.gen1Val, bucket.gen1Weight); } else { newBucket = bucket; } cacheVal = bucket.gen3Val; } else if (bucket.gen2Val != null && value.equals(bucket.gen2Val)) { GEN2_HITS.incrementAndGet(this); if (BUCKET_GEN2_WEIGHT.incrementAndGet(bucket) > bucket.gen3Weight) { newBucket = new HashGenSetBucket<V>( bucket.gen4Val, bucket.gen4Weight, bucket.gen2Val, bucket.gen2Weight, bucket.gen3Val, bucket.gen3Weight, bucket.gen1Val, bucket.gen1Weight); } else { newBucket = bucket; } cacheVal = bucket.gen2Val; } else if (bucket.gen1Val != null && value.equals(bucket.gen1Val)) { GEN1_HITS.incrementAndGet(this); if (BUCKET_GEN1_WEIGHT.incrementAndGet(bucket) > bucket.gen2Weight) { newBucket = new HashGenSetBucket<V>( bucket.gen4Val, bucket.gen4Weight, bucket.gen3Val, bucket.gen3Weight, bucket.gen1Val, bucket.gen1Weight, bucket.gen2Val, bucket.gen2Weight); } else { newBucket = bucket; } cacheVal = bucket.gen1Val; } else { MISSES.incrementAndGet(this); evictVal = bucket.gen2Val; // Penalize older gens for thrash. Promote gen1 to prevent nacent gens // from flip-flopping. If sacrificed gen2 was worth keeping, it likely // would have already been promoted. newBucket = new HashGenSetBucket<V>( bucket.gen4Val, bucket.gen4Weight - 1, bucket.gen3Val, bucket.gen3Weight - 1, bucket.gen1Val, bucket.gen1Weight, value, 1); cacheVal = value; } } } while (bucket != newBucket && !buckets.compareAndSet(index, bucket, newBucket)); if (evictVal != null) { EVICTS.incrementAndGet(this); evict(evictVal); } return cacheVal; } public boolean remove(V value) { if (buckets.length() == 0) { return false; } HashGenSetBucket<V> bucket; HashGenSetBucket<V> newBucket; boolean removed; final int index = Math.abs(value.hashCode()) % buckets.length(); do { bucket = buckets.get(index); if (bucket == null) { newBucket = null; removed = false; } else { if (bucket.gen4Val != null && value.equals(bucket.gen4Val)) { newBucket = new HashGenSetBucket<V>( bucket.gen3Val, bucket.gen3Weight, bucket.gen2Val, bucket.gen2Weight, bucket.gen1Val, bucket.gen1Weight, null, 0); removed = true; } else if (bucket.gen3Val != null && value.equals(bucket.gen3Val)) { newBucket = new HashGenSetBucket<V>( bucket.gen4Val, bucket.gen4Weight, bucket.gen2Val, bucket.gen2Weight, bucket.gen1Val, bucket.gen1Weight, null, 0); removed = true; } else if (bucket.gen2Val != null && value.equals(bucket.gen2Val)) { newBucket = new HashGenSetBucket<V>( bucket.gen4Val, bucket.gen4Weight, bucket.gen3Val, bucket.gen3Weight, bucket.gen1Val, bucket.gen1Weight, null, 0); removed = true; } else if (bucket.gen1Val != null && value.equals(bucket.gen1Val)) { newBucket = new HashGenSetBucket<V>( bucket.gen4Val, bucket.gen4Weight, bucket.gen3Val, bucket.gen3Weight, bucket.gen2Val, bucket.gen2Weight, null, 0); removed = true; } else { newBucket = bucket; removed = false; } } } while (bucket != newBucket && !buckets.compareAndSet(index, bucket, newBucket)); return removed; } public void clear() { for (int i = 0; i < buckets.length(); i += 1) { buckets.set(i, null); } } public double hitRatio() { final double hits = (double) gen4Hits + (double) gen3Hits + (double) gen2Hits + (double) gen1Hits; return hits / (hits + (double) misses); } @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSetBucket<?>> BUCKET_GEN4_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSetBucket<?>>) (Class<?>) HashGenSetBucket.class, "gen4Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSetBucket<?>> BUCKET_GEN3_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSetBucket<?>>) (Class<?>) HashGenSetBucket.class, "gen3Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSetBucket<?>> BUCKET_GEN2_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSetBucket<?>>) (Class<?>) HashGenSetBucket.class, "gen2Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSetBucket<?>> BUCKET_GEN1_WEIGHT = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSetBucket<?>>) (Class<?>) HashGenSetBucket.class, "gen1Weight"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSet<?>> GEN4_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSet<?>>) (Class<?>) HashGenSet.class, "gen4Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSet<?>> GEN3_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSet<?>>) (Class<?>) HashGenSet.class, "gen3Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSet<?>> GEN2_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSet<?>>) (Class<?>) HashGenSet.class, "gen2Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSet<?>> GEN1_HITS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSet<?>>) (Class<?>) HashGenSet.class, "gen1Hits"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSet<?>> MISSES = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSet<?>>) (Class<?>) HashGenSet.class, "misses"); @SuppressWarnings("unchecked") static final AtomicIntegerFieldUpdater<HashGenSet<?>> EVICTS = AtomicIntegerFieldUpdater.newUpdater((Class<HashGenSet<?>>) (Class<?>) HashGenSet.class, "evicts"); } final class HashGenSetBucket<V> { final V gen4Val; final V gen3Val; final V gen2Val; final V gen1Val; volatile int gen4Weight; volatile int gen3Weight; volatile int gen2Weight; volatile int gen1Weight; HashGenSetBucket(V gen4Val, int gen4Weight, V gen3Val, int gen3Weight, V gen2Val, int gen2Weight, V gen1Val, int gen1Weight) { this.gen4Val = gen4Val; this.gen4Weight = gen4Weight; this.gen3Val = gen3Val; this.gen3Weight = gen3Weight; this.gen2Val = gen2Val; this.gen2Weight = gen2Weight; this.gen1Val = gen1Val; this.gen1Weight = gen1Weight; } HashGenSetBucket(V value) { this(null, 0, null, 0, null, 0, value, 1); } HashGenSetBucket() { this(null, 0, null, 0, null, 0, null, 0); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/IterableMap.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.util; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Map; import java.util.Set; public interface IterableMap<K, V> extends Iterable<Map.Entry<K, V>>, Map<K, V> { @Override boolean isEmpty(); @Override int size(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override V get(Object key); @Override V put(K key, V newValue); @Override void putAll(Map<? extends K, ? extends V> map); @Override V remove(Object key); @Override void clear(); @Override default Set<Entry<K, V>> entrySet() { return new IterableMapEntrySet<K, V>(this); } @Override default Set<K> keySet() { return new IterableMapKeySet<K, V>(this); } @Override default Collection<V> values() { return new IterableMapValues<K, V>(this); } @Override Cursor<Entry<K, V>> iterator(); default Cursor<K> keyIterator() { return new CursorKeys<K>(iterator()); } default Cursor<V> valueIterator() { return new CursorValues<V>(iterator()); } } final class IterableMapEntrySet<K, V> extends AbstractSet<Map.Entry<K, V>> { private final IterableMap<K, V> map; IterableMapEntrySet(IterableMap<K, V> map) { this.map = map; } @Override public int size() { return this.map.size(); } @Override public Cursor<Map.Entry<K, V>> iterator() { return this.map.iterator(); } } final class IterableMapKeySet<K, V> extends AbstractSet<K> { private final IterableMap<K, V> map; IterableMapKeySet(IterableMap<K, V> map) { this.map = map; } @Override public int size() { return this.map.size(); } @Override public Cursor<K> iterator() { return this.map.keyIterator(); } } final class IterableMapValues<K, V> extends AbstractCollection<V> { private final IterableMap<K, V> map; IterableMapValues(IterableMap<K, V> map) { this.map = map; } @Override public int size() { return this.map.size(); } @Override public Cursor<V> iterator() { return this.map.valueIterator(); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/KeyedList.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.util; import java.util.List; import java.util.ListIterator; import java.util.Map; public interface KeyedList<E> extends List<E> { E get(int index, Object key); Map.Entry<Object, E> getEntry(int index); Map.Entry<Object, E> getEntry(int index, Object key); E set(int index, E element, Object key); boolean add(E element, Object key); void add(int index, E element, Object key); E remove(int index, Object key); void move(int fromIndex, int toIndex); void move(int fromIndex, int toIndex, Object key); ListIterator<Object> keyIterator(); ListIterator<Map.Entry<Object, E>> entryIterator(); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/Log.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.util; /** * Takes actions when presented messages of various severities. */ public interface Log { /** * Logs a trace-level message. */ void trace(Object message); /** * Logs a debug-level message. */ void debug(Object message); /** * Logs an info-level message. */ void info(Object message); /** * Logs a warn-level message. */ void warn(Object message); /** * Logs an error-level message. */ void error(Object message); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/Murmur3.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.util; import java.nio.ByteOrder; /** * 32-bit <a href="https://en.wikipedia.org/wiki/MurmurHash">MurmurHash</a> * algorithm, version 3. */ public final class Murmur3 { private Murmur3() { } /** * Returns the hash code of the name of the class. */ public static int seed(Class<?> clazz) { return seed(clazz.getName()); } /** * Returns the hash code of the {@code string}. */ public static int seed(String string) { return mash(mix(0, string)); } /** * Returns the hash code of the primitive `byte` `value`. */ public static int hash(byte value) { return value; } /** * Returns the hash code of the primitive `short` `value`. */ public static int hash(short value) { return value; } /** * Returns the hash code of the primitive `int` `value`. */ public static int hash(int value) { return value; } /** * Returns the hash code of the primitive `long` `value`. */ public static int hash(long value) { return (int) value ^ ((int) (value >>> 32) + (int) (value >>> 63)); } /** * Returns the hash code of the primitive `float` `value`. */ public static int hash(float value) { if (value == (float) (int) value) { return (int) value; } else if (value == (float) (long) value) { return hash((long) value); } else { return Float.floatToIntBits(value); } } /** * Returns the hash code of the primitive `double` `value`. */ public static int hash(double value) { if (value == (double) (int) value) { return (int) value; } else if (value == (double) (long) value) { return hash((long) value); } else if (value == (double) (float) value) { return Float.floatToIntBits((float) value); } else { final long y = Double.doubleToLongBits(value); return (int) y ^ (int) (y >>> 32); } } /** * Returns the hash code of the primitive `char` `value`. */ public static int hash(char value) { return value; } /** * Returns the hash code of the primitive `boolean` `value`. */ public static int hash(boolean value) { if (value) { return Boolean.TRUE.hashCode(); } else { return Boolean.FALSE.hashCode(); } } /** * Returns the hash code of the {@code number}. */ public static int hash(Number number) { if (number instanceof Double) { return hash(number.doubleValue()); } else if (number instanceof Float) { return hash(number.floatValue()); } else if (number instanceof Long) { return hash(number.longValue()); } else { return number.intValue(); } } /** * Returns the hash code of the–possibly {@code null}–{@code object}. */ public static int hash(Object object) { if (object == null) { return 0; } else if (object instanceof Number) { return hash((Number) object); } else { return object.hashCode(); } } /** * Mixes each consecutive 4-byte word in the {@code array}, starting at * index {@code offset}, and continuing for {@code size} bytes, into the * accumulated hash {@code code}. */ public static int mix(int code, byte[] array, int offset, int size) { if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) { return mixByteArrayBE(code, array, offset, size); } else if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) { return mixByteArrayLE(code, array, offset, size); } else { throw new AssertionError(); } } static int mixByteArrayBE(int code, byte[] array, int offset, int size) { final int limit = offset + size; while (offset + 3 < limit) { final int word = (array[offset ] & 0xff) << 24 | (array[offset + 1] & 0xff) << 16 | (array[offset + 2] & 0xff) << 8 | array[offset + 3] & 0xff; code = mix(code, word); offset += 4; } if (offset < limit) { int word = (array[offset] & 0xff) << 24; if (offset + 1 < limit) { word |= (array[offset + 1] & 0xff) << 16; if (offset + 2 < limit) { word |= (array[offset + 2] & 0xff) << 8; //assert offset + 3 === limit; } } word *= 0xcc9e2d51; word = Integer.rotateLeft(word, 15); word *= 0x1b873593; code ^= word; } return code ^ size; } static int mixByteArrayLE(int code, byte[] array, int offset, int size) { final int limit = offset + size; while (offset + 3 < limit) { final int word = array[offset ] & 0xff | (array[offset + 1] & 0xff) << 8 | (array[offset + 2] & 0xff) << 16 | (array[offset + 3] & 0xff) << 24; code = mix(code, word); offset += 4; } if (offset < limit) { int word = array[offset] & 0xff; if (offset + 1 < limit) { word |= (array[offset + 1] & 0xff) << 8; if (offset + 2 < limit) { word |= (array[offset + 2] & 0xff) << 16; //assert offset + 3 == limit; } } word *= 0xcc9e2d51; word = Integer.rotateLeft(word, 15); word *= 0x1b873593; code ^= word; } return code ^ size; } /** * Mixes each consecutive 4-byte word in the {@code array} into the * accumulated hash {@code code}. */ public static int mix(int code, byte[] array) { return mix(code, array, 0, array != null ? array.length : 0); } /** * Mixes each consecutive 4-byte word in the UTF-8 encoding of the {@code * string} into the accumulated hash {@code code}. */ public static int mix(int code, String string) { if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) { return mixStringBE(code, string); } else if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) { return mixStringLE(code, string); } else { throw new AssertionError(); } } @SuppressWarnings("checkstyle:LeftCurly") static int mixStringBE(int code, String string) { int word = 0; int k = 32; int i = 0; final int n = string != null ? string.length() : 0; int utf8Length = 0; while (i < n) { final int c = string.codePointAt(i); if (c >= 0 && c <= 0x7f) { // U+0000..U+007F k -= 8; word |= c << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } utf8Length += 1; } else if (c >= 0x80 && c <= 0x7ff) { // U+0080..U+07FF k -= 8; word |= (0xc0 | (c >>> 6)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | (c & 0x3f)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } utf8Length += 2; } else if (c >= 0x0800 && c <= 0xffff) { // (U+0800..U+D7FF, U+E000..U+FFFF, and surrogates k -= 8; word |= (0xe0 | (c >>> 12)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | ((c >>> 6) & 0x3f)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | (c & 0x3f)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } utf8Length += 3; } else if (c >= 0x10000 && c <= 0x10ffff) { // U+10000..U+10FFFF k -= 8; word |= (0xf0 | (c >>> 18)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | ((c >>> 12) & 0x3f)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | ((c >>> 6) & 0x3f)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } k -= 8; word |= (0x80 | (c & 0x3f)) << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } utf8Length += 4; } else { // surrogate or invalid code point k -= 8; word |= 0xef << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } k -= 8; word |= 0xbf << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } k -= 8; word |= 0xbd << k; if (k == 0) { code = mix(code, word); word = 0; k = 32; } utf8Length += 3; } i = string.offsetByCodePoints(i, 1); } if (k != 32) { word *= 0xcc9e2d51; word = Integer.rotateLeft(word, 15); word *= 0x1b873593; code ^= word; } return code ^ utf8Length; } @SuppressWarnings("checkstyle:LeftCurly") static int mixStringLE(int code, String string) { int word = 0; int k = 0; int i = 0; final int n = string.length(); int utf8Length = 0; while (i < n) { final int c = string.codePointAt(i); if (c >= 0 && c <= 0x7f) { // U+0000..U+007F word |= c << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } utf8Length += 1; } else if (c >= 0x80 && c <= 0x7ff) { // U+0080..U+07FF word |= (0xc0 | (c >>> 6)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } word |= (0x80 | (c & 0x3f)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } utf8Length += 2; } else if (c >= 0x0800 && c <= 0xffff) { // (U+0800..U+D7FF, U+E000..U+FFFF, and surrogates word |= (0xe0 | (c >>> 12)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } word |= (0x80 | ((c >>> 6) & 0x3f)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } word |= (0x80 | (c & 0x3f)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } utf8Length += 3; } else if (c >= 0x10000 && c <= 0x10ffff) { // U+10000..U+10FFFF word |= (0xf0 | (c >>> 18)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } word |= (0x80 | ((c >>> 12) & 0x3f)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } word |= (0x80 | ((c >>> 6) & 0x3f)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } word |= (0x80 | (c & 0x3f)) << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } utf8Length += 4; } else { // surrogate or invalid code point word |= 0xef << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } word |= 0xbf << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } word |= 0xbd << k; k += 8; if (k == 32) { code = mix(code, word); word = 0; k = 0; } utf8Length += 3; } i = string.offsetByCodePoints(i, 1); } if (k != 32) { word *= 0xcc9e2d51; word = Integer.rotateLeft(word, 15); word *= 0x1b873593; code ^= word; } return code ^ utf8Length; } /** * Mixes a new hash {@code value} into the accumulated cumulative hash * {@code code}. */ public static int mix(int code, int value) { value *= 0xcc9e2d51; value = Integer.rotateLeft(value, 15); value *= 0x1b873593; code ^= value; code = Integer.rotateLeft(code, 13); code = code * 5 + 0xe6546b64; return code; } /** * Finalizes a hash {@code code}. */ public static int mash(int code) { code ^= code >>> 16; code *= 0x85ebca6b; code ^= code >>> 13; code *= 0xc2b2ae35; code ^= code >>> 16; return code; } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/OrderedMap.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.util; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedMap; public interface OrderedMap<K, V> extends IterableMap<K, V>, SortedMap<K, V> { @Override boolean isEmpty(); @Override int size(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); int indexOf(Object key); @Override V get(Object key); Entry<K, V> getEntry(Object key); Entry<K, V> getIndex(int index); Entry<K, V> firstEntry(); @Override K firstKey(); V firstValue(); Entry<K, V> lastEntry(); @Override K lastKey(); V lastValue(); Entry<K, V> nextEntry(K key); K nextKey(K key); V nextValue(K key); Entry<K, V> previousEntry(K key); K previousKey(K key); V previousValue(K key); @Override V put(K key, V newValue); @Override default void putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override V remove(Object key); @Override void clear(); @Override default OrderedMap<K, V> headMap(K toKey) { return new OrderedMapView<K, V>(this, null, toKey); } @Override default OrderedMap<K, V> tailMap(K fromKey) { return new OrderedMapView<K, V>(this, fromKey, null); } @Override default OrderedMap<K, V> subMap(K fromKey, K toKey) { return new OrderedMapView<K, V>(this, fromKey, toKey); } @Override default Set<Entry<K, V>> entrySet() { return IterableMap.super.entrySet(); } @Override default Set<K> keySet() { return IterableMap.super.keySet(); } @Override default Collection<V> values() { return IterableMap.super.values(); } @Override OrderedMapCursor<K, V> iterator(); @Override default Cursor<K> keyIterator() { return IterableMap.super.keyIterator(); } @Override default Cursor<V> valueIterator() { return IterableMap.super.valueIterator(); } @Override Comparator<? super K> comparator(); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/OrderedMapCursor.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.util; import java.util.Map; public interface OrderedMapCursor<K, V> extends Cursor<Map.Entry<K, V>> { K nextKey(); K previousKey(); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/OrderedMapView.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.util; import java.util.Comparator; import java.util.Iterator; import java.util.Map; final class OrderedMapView<K, V> implements OrderedMap<K, V> { final OrderedMap<K, V> map; final K fromKey; final K toKey; OrderedMapView(OrderedMap<K, V> map, K fromKey, K toKey) { this.map = map; this.fromKey = fromKey; this.toKey = toKey; } @Override public boolean isEmpty() { return size() == 0; } @Override public int size() { int fromIndex; if (this.fromKey != null) { fromIndex = this.map.indexOf(this.fromKey); if (fromIndex < 0) { fromIndex = -(fromIndex + 1); } } else { fromIndex = 0; } int toIndex; if (this.toKey != null) { toIndex = this.map.indexOf(this.toKey); if (toIndex < 0) { toIndex = -(toIndex + 1); } else { toIndex += 1; } } else { toIndex = this.map.size(); } return toIndex - fromIndex; } @Override public boolean containsKey(Object key) { return (this.fromKey == null || compareKey(this.fromKey, key) >= 0) && (this.toKey == null || compareKey(key, this.toKey) < 0) && this.map.containsKey(key); } @Override public boolean containsValue(Object value) { final Cursor<V> cursor = valueIterator(); while (cursor.hasNext()) { if (value == null ? cursor.next() == null : value.equals(cursor.next())) { return true; } } return false; } @Override public int indexOf(Object key) { if ((this.fromKey == null || compareKey(this.fromKey, key) >= 0) && (this.toKey == null || compareKey(key, this.toKey) < 0)) { int fromIndex; if (this.fromKey != null) { fromIndex = this.map.indexOf(this.fromKey); if (fromIndex < 0) { fromIndex = -(fromIndex + 1); } } else { fromIndex = 0; } final int keyIndex = this.map.indexOf(key); if (keyIndex >= 0) { return keyIndex - fromIndex; } else { return keyIndex + fromIndex; } } else { throw new IllegalArgumentException(key.toString()); } } @Override public V get(Object key) { if ((this.fromKey == null || compareKey(this.fromKey, key) >= 0) && (this.toKey == null || compareKey(key, this.toKey) < 0)) { return this.map.get(key); } else { return null; } } @Override public Entry<K, V> getEntry(Object key) { if ((this.fromKey == null || compareKey(this.fromKey, key) >= 0) && (this.toKey == null || compareKey(key, this.toKey) < 0)) { return this.map.getEntry(key); } else { return null; } } @Override public Entry<K, V> getIndex(int index) { final Cursor<Entry<K, V>> cursor = iterator(); int i = 0; while (i < index && cursor.hasNext()) { cursor.step(); i += 1; } if (i == index && cursor.hasNext()) { return cursor.next(); } else { throw new IndexOutOfBoundsException(Integer.toString(index)); } } @Override public Entry<K, V> firstEntry() { Entry<K, V> nextEntry; if (this.fromKey != null) { nextEntry = this.map.getEntry(this.fromKey); if (nextEntry != null) { return nextEntry; } else { nextEntry = this.map.nextEntry(this.fromKey); } } else { nextEntry = this.map.firstEntry(); } if (this.toKey == null || nextEntry != null && compareKey(nextEntry.getKey(), this.toKey) < 0) { return nextEntry; } else { return null; } } @Override public K firstKey() { final K nextKey; if (this.fromKey != null) { if (this.map.containsKey(this.fromKey)) { return this.fromKey; } else { nextKey = this.map.nextKey(this.fromKey); } } else { nextKey = this.map.firstKey(); } if (this.toKey == null || nextKey != null && compareKey(nextKey, this.toKey) < 0) { return nextKey; } else { return null; } } @Override public V firstValue() { final K firstKey = firstKey(); if (firstKey != null) { return this.map.get(firstKey); } else { return null; } } @Override public Entry<K, V> lastEntry() { final Entry<K, V> previousEntry; if (this.toKey != null) { previousEntry = this.map.previousEntry(this.toKey); } else { previousEntry = this.map.lastEntry(); } if (this.fromKey == null || previousEntry != null && compareKey(this.fromKey, previousEntry.getKey()) <= 0) { return previousEntry; } else { return null; } } @Override public K lastKey() { final K previousKey; if (this.toKey != null) { previousKey = this.map.previousKey(this.toKey); } else { previousKey = this.map.lastKey(); } if (this.fromKey == null || previousKey != null && compareKey(this.fromKey, previousKey) <= 0) { return previousKey; } else { return null; } } @Override public V lastValue() { final K lastKey = lastKey(); if (lastKey != null) { return this.map.get(lastKey); } else { return null; } } @Override public Entry<K, V> nextEntry(K key) { final Entry<K, V> nextEntry = this.map.nextEntry(key); if (nextEntry != null && (this.toKey == null || compareKey(nextEntry.getKey(), this.toKey) < 0)) { return nextEntry; } else { return null; } } @Override public K nextKey(K key) { final K nextKey = this.map.nextKey(key); if (nextKey != null && (this.toKey == null || compareKey(nextKey, this.toKey) < 0)) { return nextKey; } else { return null; } } @Override public V nextValue(K key) { final K nextKey = nextKey(key); if (nextKey != null) { return this.map.get(nextKey); } else { return null; } } @Override public Entry<K, V> previousEntry(K key) { final Entry<K, V> previousEntry = this.map.previousEntry(key); if (previousEntry != null && (this.fromKey == null || compareKey(this.fromKey, previousEntry.getKey()) <= 0)) { return previousEntry; } else { return null; } } @Override public K previousKey(K key) { final K previousKey = this.map.previousKey(key); if (previousKey != null && (this.fromKey == null || compareKey(this.fromKey, previousKey) <= 0)) { return previousKey; } else { return null; } } @Override public V previousValue(K key) { final K previousKey = previousKey(key); if (previousKey != null) { return this.map.get(previousKey); } else { return null; } } @Override public V put(K key, V newValue) { if ((this.fromKey == null || compareKey(this.fromKey, key) <= 0) && (this.toKey == null || compareKey(key, this.toKey) < 0)) { return this.map.put(key, newValue); } else { throw new IllegalArgumentException(key.toString()); } } @Override public V remove(Object key) { if ((this.fromKey == null || compareKey(this.fromKey, key) <= 0) && (this.toKey == null || compareKey(key, this.toKey) < 0)) { return this.map.remove(key); } else { return null; } } @Override public void clear() { final Cursor<K> cursor = keyIterator(); while (cursor.hasNext()) { cursor.step(); cursor.remove(); } } @Override public OrderedMap<K, V> headMap(K toKey) { if (compareKey(toKey, this.toKey) > 0) { toKey = this.toKey; } return new OrderedMapView<K, V>(this.map, this.fromKey, toKey); } @Override public OrderedMap<K, V> tailMap(K fromKey) { if (compareKey(fromKey, this.fromKey) < 0) { fromKey = this.fromKey; } return new OrderedMapView<K, V>(this.map, fromKey, this.toKey); } @Override public OrderedMap<K, V> subMap(K fromKey, K toKey) { if (compareKey(fromKey, this.fromKey) < 0) { fromKey = this.fromKey; } if (compareKey(toKey, this.toKey) > 0) { toKey = this.toKey; } return new OrderedMapView<K, V>(this.map, fromKey, toKey); } @Override public OrderedMapCursor<K, V> iterator() { int index = this.map.indexOf(this.fromKey); if (index < 0) { index = -(index + 1); } final OrderedMapCursor<K, V> cursor = this.map.iterator(); cursor.skip(index - 1); return new OrderedMapViewCursor<K, V>(this.map, cursor, this.fromKey, this.toKey); } @Override public Comparator<? super K> comparator() { return this.map.comparator(); } @SuppressWarnings("unchecked") private int compareKey(Object x, Object y) { final Comparator<Object> comparator = (Comparator<Object>) (Comparator<?>) this.map.comparator(); if (comparator != null) { return comparator.compare(x, y); } else { return ((Comparable<Object>) x).compareTo(y); } } @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 Iterator<Entry<K, V>> these = iterator(); while (these.hasNext()) { code += these.next().hashCode(); } return code; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append('{'); final Iterator<Entry<K, V>> these = iterator(); if (these.hasNext()) { sb.append(these.next()); while (these.hasNext()) { sb.append(", ").append(these.next()); } } sb.append('}'); return sb.toString(); } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/OrderedMapViewCursor.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.util; import java.util.Comparator; import java.util.Map; import java.util.NoSuchElementException; final class OrderedMapViewCursor<K, V> implements OrderedMapCursor<K, V> { final OrderedMap<K, V> map; final OrderedMapCursor<K, V> cursor; final K fromKey; final K toKey; OrderedMapViewCursor(OrderedMap<K, V> map, OrderedMapCursor<K, V> cursor, K fromKey, K toKey) { this.map = map; this.cursor = cursor; this.fromKey = fromKey; this.toKey = toKey; } @Override public boolean isEmpty() { return this.cursor.isEmpty() || this.toKey != null && compareKey(this.cursor.nextKey(), this.toKey) >= 0; } @Override public Map.Entry<K, V> head() { if (!isEmpty()) { return this.cursor.head(); } else { throw new NoSuchElementException(); } } @Override public void step() { if (!isEmpty()) { this.cursor.step(); } else { throw new UnsupportedOperationException(); } } @Override public void skip(long count) { this.cursor.skip(count); } @Override public boolean hasNext() { return this.cursor.hasNext() && (this.toKey == null || compareKey(this.cursor.nextKey(), this.toKey) < 0); } @Override public long nextIndexLong() { return this.cursor.nextIndexLong(); } @Override public K nextKey() { if (this.cursor.hasNext()) { final K nextKey = this.cursor.nextKey(); if (this.toKey == null || compareKey(nextKey, this.toKey) < 0) { return nextKey; } } return null; } @Override public Map.Entry<K, V> next() { if (hasNext()) { return this.cursor.next(); } else { throw new NoSuchElementException(); } } @Override public boolean hasPrevious() { return this.cursor.hasPrevious() && (this.fromKey == null || compareKey(this.fromKey, this.cursor.previousKey()) <= 0); } @Override public long previousIndexLong() { return this.cursor.previousIndexLong(); } @Override public K previousKey() { if (this.cursor.hasPrevious()) { final K previousKey = this.cursor.previousKey(); if (this.fromKey == null || compareKey(this.fromKey, previousKey) <= 0) { return previousKey; } } return null; } @Override public Map.Entry<K, V> previous() { if (hasPrevious()) { return this.cursor.previous(); } else { throw new NoSuchElementException(); } } @Override public void set(Map.Entry<K, V> newValue) { this.cursor.set(newValue); } @Override public void remove() { this.cursor.remove(); } @SuppressWarnings("unchecked") private int compareKey(Object x, Object y) { final Comparator<Object> comparator = (Comparator<Object>) (Comparator<?>) this.map.comparator(); if (comparator != null) { return comparator.compare(x, y); } else { return ((Comparable<Object>) x).compareTo(y); } } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/PairBuilder.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.util; /** * Type that accumulates pairs of input values, and binds an output result of * type {@code O}. */ public interface PairBuilder<K, V, O> { /** * Adds an input pair to this builder, returning {@code true} if the state * of the builder changed. */ boolean add(K key, V value); /** * Returns the output result of this builder. */ O bind(); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/ReducedMap.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.util; /** * An {@link OrderedMap} that memoizes partial combinations of sub-elements to * support efficient, incremental reduction of continuously mutating datasets. */ public interface ReducedMap<K, V, U> extends OrderedMap<K, V> { /** * Returns the reduction of this {@code ReducedMap}, combining all contained * elements with the given {@code accumulator} and {@code combiner} functions, * recomputing only what has changed since the last invocation of {@code * reduced}. Stores partial computations to accelerate repeated reduction * of continuously mutating datasets. */ U reduced(U identity, CombinerFunction<? super V, U> accumulator, CombinerFunction<U, U> combiner); }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/Severity.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.util; /** * Level of importance. Used for log levels and diagnostic classifications. */ public final class Severity implements Comparable<Severity> { final int level; final String label; private Severity(int level, String label) { this.level = level; this.label = label; } /** * Returns the integer level of importance of this {@code Severity}, with * higher levels signifying greater importance. * * @return an integer between {@code 0} and {@code 7}, inclusive. One of * {@code TRACE_LEVEL}, {@code DEBUG_LEVEL}, {@code INFO_LEVEL}, * {@code NOTE_LEVEL}, {@code WARNING_LEVEL}, {@code ERROR_LEVEL}, * {@code ALERT_LEVEL}, or {@code FATAL_LEVEL}. */ public int level() { return this.level; } /** * Returns a descriptive label for this {@code Severity}. */ public String label() { return this.label; } /** * Returns a new {@code Severity} with the same level as this {@code * Severity}, but with a new descriptive {@code label}. */ public Severity label(String label) { if (this.label.equals(label)) { return this; } else { return create(this.level, label); } } /** * Returns {@code true} if this {@code Severity} has {@code TRACE_LEVEL} * of importance. */ public boolean isTrace() { return this.level == TRACE_LEVEL; } /** * Returns {@code true} if this {@code Severity} has {@code DEBUG_LEVEL} * of importance. */ public boolean isDebug() { return this.level == DEBUG_LEVEL; } /** * Returns {@code true} if this {@code Severity} has {@code INFO_LEVEL} * of importance. */ public boolean isInfo() { return this.level == INFO_LEVEL; } /** * Returns {@code true} if this {@code Severity} has {@code NOTE_LEVEL} * of importance. */ public boolean isNote() { return this.level == NOTE_LEVEL; } /** * Returns {@code true} if this {@code Severity} has {@code WARNING_LEVEL} * of importance. */ public boolean isWarning() { return this.level == WARNING_LEVEL; } /** * Returns {@code true} if this {@code Severity} has {@code ERROR_LEVEL} * of importance. */ public boolean isError() { return this.level == ERROR_LEVEL; } /** * Returns {@code true} if this {@code Severity} has {@code ALERT_LEVEL} * of importance. */ public boolean isAlert() { return this.level == ALERT_LEVEL; } /** * Returns {@code true} if this {@code Severity} has {@code FATAL_LEVEL} * of importance. */ public boolean isFatal() { return this.level == FATAL_LEVEL; } @Override public int compareTo(Severity that) { if (this == that) { return 0; } else if (this.level < that.level) { return -1; } else if (this.level > that.level) { return 1; } else { return this.label.compareTo(that.label); } } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof Severity) { final Severity that = (Severity) other; return this.level == that.level && this.label.equals(that.label); } return false; } @Override public int hashCode() { if (hashSeed == 0) { hashSeed = Murmur3.seed(Severity.class); } return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed, this.level), this.label.hashCode())); } @Override public String toString() { return this.label; } public static final int TRACE_LEVEL = 0; public static final int DEBUG_LEVEL = 1; public static final int INFO_LEVEL = 2; public static final int NOTE_LEVEL = 3; public static final int WARNING_LEVEL = 4; public static final int ERROR_LEVEL = 5; public static final int ALERT_LEVEL = 6; public static final int FATAL_LEVEL = 7; private static int hashSeed; private static Severity trace; private static Severity debug; private static Severity info; private static Severity note; private static Severity warning; private static Severity error; private static Severity alert; private static Severity fatal; /** * Returns a {@code Severity} with the given importance {@code level}, * and descriptive {@code label}. * * @throws IllegalArgumentException if {@code level} is not a valid * level of importance. */ public static Severity create(int level, String label) { switch (level) { case TRACE_LEVEL: return trace(label); case DEBUG_LEVEL: return debug(label); case INFO_LEVEL: return info(label); case NOTE_LEVEL: return note(label); case WARNING_LEVEL: return warning(label); case ERROR_LEVEL: return error(label); case ALERT_LEVEL: return alert(label); case FATAL_LEVEL: return fatal(label); default: throw new IllegalArgumentException(Integer.toString(level)); } } /** * Returns the {@code Severity} with the given importance {@code level}. * * @throws IllegalArgumentException if {@code level} is not a valid * level of importance. */ public static Severity create(int level) { return create(level, null); } /** * Returns the {@code Severity} with {@code TRACE_LEVEL} of importance. */ public static Severity trace() { if (trace == null) { trace = new Severity(TRACE_LEVEL, "trace"); } return trace; } /** * Returns a {@code Severity} with {@code TRACE_LEVEL} of importance, * and the given descriptive {@code label}. */ public static Severity trace(String label) { if (label == null || "trace".equals(label)) { return trace(); } else { return new Severity(TRACE_LEVEL, label); } } /** * Returns the {@code Severity} with {@code DEBUG_LEVEL} of importance. */ public static Severity debug() { if (debug == null) { debug = new Severity(DEBUG_LEVEL, "debug"); } return debug; } /** * Returns a {@code Severity} with {@code DEBUG_LEVEL} of importance, * and the given descriptive {@code label}. */ public static Severity debug(String label) { if (label == null || "debug".equals(label)) { return debug(); } else { return new Severity(DEBUG_LEVEL, label); } } /** * Returns the {@code Severity} with {@code INFO_LEVEL} of importance. */ public static Severity info() { if (info == null) { info = new Severity(INFO_LEVEL, "info"); } return info; } /** * Returns a {@code Severity} with {@code INFO_LEVEL} of importance, * and the given descriptive {@code label}. */ public static Severity info(String label) { if (label == null || "info".equals(label)) { return info(); } else { return new Severity(INFO_LEVEL, label); } } /** * Returns the {@code Severity} with {@code NOTE_LEVEL} of importance. */ public static Severity note() { if (note == null) { note = new Severity(NOTE_LEVEL, "note"); } return note; } /** * Returns a {@code Severity} with {@code NOTE_LEVEL} of importance, * and the given descriptive {@code label}. */ public static Severity note(String label) { if (label == null || "note".equals(label)) { return note(); } else { return new Severity(NOTE_LEVEL, label); } } /** * Returns the {@code Severity} with {@code WARNING_LEVEL} of importance. */ public static Severity warning() { if (warning == null) { warning = new Severity(WARNING_LEVEL, "warning"); } return warning; } /** * Returns a {@code Severity} with {@code WARNING_LEVEL} of importance, * and the given descriptive {@code label}. */ public static Severity warning(String label) { if (label == null || "warning".equals(label)) { return warning(); } else { return new Severity(WARNING_LEVEL, label); } } /** * Returns the {@code Severity} with {@code ERROR_LEVEL} of importance. */ public static Severity error() { if (error == null) { error = new Severity(ERROR_LEVEL, "error"); } return error; } /** * Returns a {@code Severity} with {@code ERROR_LEVEL} of importance, * and the given descriptive {@code label}. */ public static Severity error(String label) { if (label == null || "error".equals(label)) { return error(); } else { return new Severity(ERROR_LEVEL, label); } } /** * Returns the {@code Severity} with {@code ALERT_LEVEL} of importance. */ public static Severity alert() { if (alert == null) { alert = new Severity(ALERT_LEVEL, "alert"); } return alert; } /** * Returns a {@code Severity} with {@code ALERT_LEVEL} of importance, * and the given descriptive {@code label}. */ public static Severity alert(String label) { if (label == null || "alert".equals(label)) { return alert(); } else { return new Severity(ALERT_LEVEL, label); } } /** * Returns the {@code Severity} with {@code FATAL_LEVEL} of importance. */ public static Severity fatal() { if (fatal == null) { fatal = new Severity(FATAL_LEVEL, "fatal"); } return fatal; } /** * Returns a {@code Severity} with {@code FATAL_LEVEL} of importance, * and the given descriptive {@code label}. */ public static Severity fatal(String label) { if (label == null || "fatal".equals(label)) { return fatal(); } else { return new Severity(FATAL_LEVEL, label); } } }
0
java-sources/ai/swim/swim-util/3.10.0/swim
java-sources/ai/swim/swim-util/3.10.0/swim/util/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. /** * Utility library. */ package swim.util;
0
java-sources/ai/swim/swim-vm
java-sources/ai/swim/swim-vm/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 polyglot virtual machine integration. */ module swim.vm { requires swim.collections; requires transitive swim.dynamic; requires transitive org.graalvm.sdk; exports swim.vm; }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/VmBridge.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.vm; import java.util.Collection; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.Proxy; import swim.dynamic.Bridge; import swim.dynamic.GuestWrapper; import swim.dynamic.HostArrayType; import swim.dynamic.HostLibrary; import swim.dynamic.HostMethod; import swim.dynamic.HostObjectType; import swim.dynamic.HostPackage; import swim.dynamic.HostRuntime; import swim.dynamic.HostStaticMethod; import swim.dynamic.HostType; import swim.dynamic.HostValue; public class VmBridge extends Bridge { final HostRuntime hostRuntime; String guestLanguage; public VmBridge(HostRuntime hostRuntime, String guestLanguage) { this.hostRuntime = hostRuntime; this.guestLanguage = guestLanguage; } @Override public final HostRuntime hostRuntime() { return this.hostRuntime; } @Override public final String guestLanguage() { return this.guestLanguage; } protected void setGuestLanguage(String guestLanguage) { this.guestLanguage = guestLanguage; } @Override public HostLibrary getHostLibrary(String libraryName) { return this.hostRuntime.getHostLibrary(libraryName); } @Override public Collection<HostLibrary> hostLibraries() { return this.hostRuntime.hostLibraries(); } @Override public HostPackage getHostPackage(String packageName) { return this.hostRuntime.getHostPackage(packageName); } @Override public Collection<HostPackage> hostPackages() { return this.hostRuntime.hostPackages(); } @Override public HostType<?> getHostType(Class<?> typeClass) { return this.hostRuntime.getHostType(typeClass); } @Override public Collection<HostType<?>> hostTypes() { return this.hostRuntime.hostTypes(); } public boolean isNativeHostClass(Class<?> hostClass) { return hostClass.isPrimitive() || hostClass == Object.class || hostClass == String.class || hostClass == Boolean.class || hostClass == Byte.class || hostClass == Character.class || hostClass == Short.class || hostClass == Integer.class || hostClass == Long.class || hostClass == Float.class || hostClass == Double.class; } @SuppressWarnings("unchecked") @Override public final <T> HostType<? super T> hostType(T hostValue) { if (hostValue instanceof HostValue) { return (HostType<? super T>) ((HostValue) hostValue).dynamicType(); } else if (hostValue != null) { Class<?> hostClass = hostValue.getClass(); if (hostClass.isArray()) { // TODO: bridge array types } else if (!isNativeHostClass(hostClass)) { do { final HostType<?> hostType = getHostType(hostClass); if (hostType != null && !hostType.isBuiltin()) { return (HostType<? super T>) hostType; } hostClass = hostClass.getSuperclass(); } while (hostClass != null); // TODO: dynamically merge implemented interfaces final Class<?>[] interfaces = hostValue.getClass().getInterfaces(); for (int i = 0, n = interfaces.length; i < n; i += 1) { final HostType<?> hostType = getHostType(interfaces[i]); if (hostType != null && !hostType.isBuiltin()) { return (HostType<? super T>) hostType; } } } } return null; } public <T> Object hostTypedValueToGuestProxy(HostType<? super T> hostType, T hostValue) { if (hostType instanceof HostObjectType<?>) { return new VmHostObject<T>(this, (HostObjectType<? super T>) hostType, hostValue); } else if (hostType instanceof HostArrayType<?>) { return new VmHostArray<T>(this, (HostArrayType<? super T>) hostType, hostValue); } else { throw new UnsupportedOperationException(); } } @Override public Object hostToGuest(Object hostValue) { final Object guestValue; if (hostValue instanceof Value || hostValue instanceof Proxy) { guestValue = hostValue; } else if (hostValue instanceof GuestWrapper) { guestValue = ((GuestWrapper) hostValue).unwrap(); } else { final HostType<? super Object> hostType = hostType(hostValue); if (hostType != null) { guestValue = hostTypedValueToGuestProxy(hostType, hostValue); } else if (hostValue instanceof Object[]) { guestValue = new VmBridgeArray(this, (Object[]) hostValue); } else { guestValue = hostValue; } } return guestValue; } @Override public Object guestToHost(Object guestValue) { Object hostValue; if (guestValue instanceof Value) { final Value value = (Value) guestValue; if (value.isProxyObject()) { hostValue = value.asProxyObject(); } else if (value.isHostObject()) { hostValue = value.asHostObject(); } else if (value.isString()) { hostValue = value.asString(); } else if (value.isNumber()) { hostValue = value.as(Number.class); } else if (value.isBoolean()) { hostValue = value.asBoolean(); } else if (value.isNull()) { hostValue = null; } else { hostValue = guestValue; } } else { hostValue = guestValue; } if (hostValue instanceof VmHostProxy<?>) { hostValue = ((VmHostProxy<?>) hostValue).unwrap(); } return hostValue; } public <T> Object hostMethodToGuestMethod(HostMethod<? super T> method, T self) { return new VmHostMethod<T>(this, method, self); } public Object hostStaticMethodToGuestStaticMethod(HostStaticMethod staticMethod) { return new VmHostStaticMethod(this, staticMethod); } @Override public boolean guestCanExecute(Object guestFunction) { return guestFunction instanceof Value && ((Value) guestFunction).canExecute(); } @Override public Object guestExecute(Object guestFunction, Object... hostArguments) { if (guestFunction instanceof Value) { final int arity = hostArguments.length; final Object[] guestArguments = new Object[arity]; for (int i = 0; i < arity; i += 1) { guestArguments[i] = hostToGuest(hostArguments[i]); } final Object guestResult = ((Value) guestFunction).execute(guestArguments); final Object hostResult = guestToHost(guestResult); return hostResult; } else { throw new UnsupportedOperationException(); } } @Override public void guestExecuteVoid(Object guestFunction, Object... hostArguments) { if (guestFunction instanceof Value) { final int arity = hostArguments.length; final Object[] guestArguments = new Object[arity]; for (int i = 0; i < arity; i += 1) { guestArguments[i] = hostToGuest(hostArguments[i]); } ((Value) guestFunction).executeVoid(guestArguments); } else { throw new UnsupportedOperationException(); } } @Override public boolean guestCanInvokeMember(Object guestObject, String member) { return guestObject instanceof Value && ((Value) guestObject).canInvokeMember(member); } @Override public Object guestInvokeMember(Object guestObject, String member, Object... hostArguments) { if (guestObject instanceof Value) { final int arity = hostArguments.length; final Object[] guestArguments = new Object[arity]; for (int i = 0; i < arity; i += 1) { guestArguments[i] = hostToGuest(hostArguments[i]); } final Object guestResult = ((Value) guestObject).invokeMember(member, guestArguments); final Object hostResult = guestToHost(guestResult); return hostResult; } else { throw new UnsupportedOperationException(); } } }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/VmBridgeArray.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.vm; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyArray; public class VmBridgeArray extends VmHostProxy<Object[]> implements ProxyArray { final VmBridge bridge; final Object[] array; public VmBridgeArray(VmBridge bridge, Object[] array) { this.bridge = bridge; this.array = array; } @Override public final Object[] unwrap() { return this.array; } @Override public long getSize() { return (long) this.array.length; } @Override public Object get(long index) { return this.bridge.hostToGuest(this.array[(int) index]); } @Override public void set(long index, Value value) { this.array[(int) index] = this.bridge.guestToHost(value); } @Override public boolean remove(long index) { throw new UnsupportedOperationException(); } }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/VmHostArray.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.vm; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyArray; import swim.dynamic.HostArrayType; public class VmHostArray<T> extends VmHostProxy<T> implements ProxyArray { final VmBridge bridge; final HostArrayType<? super T> type; final T self; public VmHostArray(VmBridge bridge, HostArrayType<? super T> type, T self) { this.bridge = bridge; this.type = type; this.self = self; } @Override public final T unwrap() { return this.self; } @Override public long getSize() { return this.type.elementCount(this.bridge, this.self); } @Override public Object get(long index) { return this.type.getElement(this.bridge, this.self, index); } @Override public void set(long index, Value value) { this.type.setElement(this.bridge, this.self, index, value); } @Override public boolean remove(long index) { return this.type.removeElement(this.bridge, this.self, index); } }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/VmHostMethod.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.vm; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyExecutable; import swim.dynamic.HostMethod; public class VmHostMethod<T> implements ProxyExecutable { final VmBridge bridge; final HostMethod<? super T> method; final T self; public VmHostMethod(VmBridge bridge, HostMethod<? super T> method, T self) { this.bridge = bridge; this.method = method; this.self = self; } @Override public Object execute(Value... guestArguments) { final int arity = guestArguments.length; final Object[] hostArguments = new Object[arity]; for (int i = 0; i < arity; i += 1) { hostArguments[i] = this.bridge.guestToHost(guestArguments[i]); } final Object hostResult = this.method.invoke(this.bridge, this.self, hostArguments); final Object guestResult = this.bridge.hostToGuest(hostResult); return guestResult; } }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/VmHostObject.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.vm; import java.util.Collection; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyObject; import swim.dynamic.HostField; import swim.dynamic.HostMember; import swim.dynamic.HostMethod; import swim.dynamic.HostObjectType; public class VmHostObject<T> extends VmHostProxy<T> implements ProxyObject { final VmBridge bridge; final HostObjectType<? super T> type; final T self; public VmHostObject(VmBridge bridge, HostObjectType<? super T> type, T self) { this.bridge = bridge; this.type = type; this.self = self; } @Override public final T unwrap() { return this.self; } @Override public boolean hasMember(String key) { final HostMember<? super T> member = this.type.getMember(this.bridge, this.self, key); return member != null; } @Override public Object getMember(String key) { final HostMember<? super T> member = this.type.getMember(this.bridge, this.self, key); if (member instanceof HostField<?>) { final Object hostValue = ((HostField<? super T>) member).get(this.bridge, this.self); return this.bridge.hostToGuest(hostValue); } else if (member instanceof HostMethod<?>) { return this.bridge.hostMethodToGuestMethod((HostMethod<? super T>) member, this.self); } else { return null; } } @Override public void putMember(String key, Value guestValue) { final HostMember<? super T> member = this.type.getMember(this.bridge, this.self, key); if (member instanceof HostField<?>) { final Object hostValue = this.bridge.guestToHost(guestValue); ((HostField<? super T>) member).set(this.bridge, this.self, hostValue); } else { throw new UnsupportedOperationException(); } } @Override public boolean removeMember(String key) { final HostMember<? super T> member = this.type.getMember(this.bridge, this.self, key); if (member instanceof HostField<?>) { return ((HostField<? super T>) member).remove(this.bridge, this.self); } else { throw new UnsupportedOperationException(); } } @Override public Object getMemberKeys() { final Collection<? extends HostMember<? super T>> members = this.type.members(this.bridge, this.self); final String[] memberKeys = new String[members.size()]; int i = 0; for (HostMember<? super T> member : members) { memberKeys[i] = member.key(); i += 1; } return new VmProxyArray(memberKeys); } }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/VmHostProxy.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.vm; import org.graalvm.polyglot.proxy.Proxy; public abstract class VmHostProxy<T> implements Proxy { public abstract T unwrap(); }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/VmHostStaticMethod.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.vm; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyExecutable; import swim.dynamic.HostStaticMethod; public class VmHostStaticMethod implements ProxyExecutable { final VmBridge bridge; final HostStaticMethod staticMethod; public VmHostStaticMethod(VmBridge bridge, HostStaticMethod staticMethod) { this.bridge = bridge; this.staticMethod = staticMethod; } @Override public Object execute(Value... guestArguments) { final int arity = guestArguments.length; final Object[] hostArguments = new Object[arity]; for (int i = 0; i < arity; i += 1) { hostArguments[i] = this.bridge.guestToHost(guestArguments[i]); } final Object hostResult = this.staticMethod.invoke(this.bridge, hostArguments); final Object guestResult = this.bridge.hostToGuest(hostResult); return guestResult; } }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/VmProxyArray.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.vm; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyArray; public class VmProxyArray extends VmHostProxy<Object[]> implements ProxyArray { final Object[] array; public VmProxyArray(Object[] array) { this.array = array; } @Override public final Object[] unwrap() { return this.array; } @Override public long getSize() { return (long) this.array.length; } @Override public Object get(long index) { return this.array[(int) index]; } @Override public void set(long index, Value value) { this.array[(int) index] = value; } @Override public boolean remove(long index) { throw new UnsupportedOperationException(); } }
0
java-sources/ai/swim/swim-vm/3.10.0/swim
java-sources/ai/swim/swim-vm/3.10.0/swim/vm/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 polyglot virtual machine integration. */ package swim.vm;
0
java-sources/ai/swim/swim-vm-js
java-sources/ai/swim/swim-vm-js/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 JavaScript language integration. */ module swim.vm.js { requires swim.json; requires transitive swim.uri; requires transitive swim.vm; exports swim.vm.js; }
0
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm/js/JsBridge.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.vm.js; import java.util.Map; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Source; import swim.collections.HashTrieMap; import swim.dynamic.HostArrayType; import swim.dynamic.HostClassType; import swim.dynamic.HostLibrary; import swim.dynamic.HostMethod; import swim.dynamic.HostObjectType; import swim.dynamic.HostStaticMethod; import swim.dynamic.HostType; import swim.uri.UriPath; import swim.vm.VmBridge; import swim.vm.VmHostArray; public class JsBridge extends VmBridge implements JsModuleResolver, JsModuleLoader { final Context jsContext; HashTrieMap<HostType<?>, Object> guestTypes; HashTrieMap<HostType<?>, Object> guestPrototypes; Object guestObjectPrototype; Object guestFunctionPrototype; public JsBridge(JsRuntime jsRuntime, Context jsContext) { super(jsRuntime, "js"); this.jsContext = jsContext; this.guestTypes = HashTrieMap.empty(); this.guestPrototypes = HashTrieMap.empty(); this.guestObjectPrototype = null; this.guestFunctionPrototype = null; } public final JsRuntime jsRuntime() { return (JsRuntime) hostRuntime(); } public final Context jsContext() { return this.jsContext; } public JsModuleResolver moduleResolver() { return jsRuntime().moduleResolver(); } public HostLibrary getHostModule(UriPath moduleId) { return jsRuntime().getHostModule(moduleId); } public Map<UriPath, HostLibrary> hostModules() { return jsRuntime().hostModules(); } @Override public <T> Object hostTypedValueToGuestProxy(HostType<? super T> hostType, T hostValue) { if (hostType instanceof HostObjectType<?>) { return new JsHostObject<T>(this, (HostObjectType<? super T>) hostType, hostValue); } else if (hostType instanceof HostArrayType<?>) { return new VmHostArray<T>(this, (HostArrayType<? super T>) hostType, hostValue); } else { throw new UnsupportedOperationException(); } } @Override public <T> Object hostMethodToGuestMethod(HostMethod<? super T> method, T self) { return new JsHostMethod<T>(this, method, self); } @Override public Object hostStaticMethodToGuestStaticMethod(HostStaticMethod staticMethod) { return new JsHostStaticMethod(this, staticMethod); } protected Object createGuestType(HostType<?> hostType) { if (hostType instanceof HostClassType<?>) { return new JsHostClass(this, (HostClassType<?>) hostType); } else if (hostType != null) { return new JsHostType(this, hostType); } else { throw new NullPointerException(); } } public Object hostTypeToGuestType(HostType<?> hostType) { HashTrieMap<HostType<?>, Object> guestTypes = this.guestTypes; Object guestType = guestTypes.get(hostType); if (guestType == null) { guestType = createGuestType(hostType); guestTypes = guestTypes.updated(hostType, guestType); this.guestTypes = guestTypes; } return guestType; } protected Object createGuestPrototype(HostType<?> hostType) { if (hostType instanceof HostClassType<?>) { return new JsHostPrototype(this, (HostClassType<?>) hostType); } return null; } public Object hostTypeToGuestPrototype(HostType<?> hostType) { HashTrieMap<HostType<?>, Object> guestPrototypes = this.guestPrototypes; Object guestPrototype = guestPrototypes.get(hostType); if (guestPrototype == null) { guestPrototype = createGuestPrototype(hostType); if (guestPrototype == null) { guestPrototype = guestObjectPrototype(); } else { guestPrototypes = guestPrototypes.updated(hostType, guestPrototype); this.guestPrototypes = guestPrototypes; } } return guestPrototype; } public Object guestObjectPrototype() { Object prototype = this.guestObjectPrototype; if (prototype == null) { prototype = this.jsContext.getBindings("js").getMember("Object").getMember("prototype"); this.guestObjectPrototype = prototype; } return prototype; } public Object guestFunctionPrototype() { Object prototype = this.guestFunctionPrototype; if (prototype == null) { prototype = this.jsContext.getBindings("js").getMember("Function").getMember("prototype"); this.guestFunctionPrototype = prototype; } return prototype; } @Override public UriPath resolveModulePath(UriPath basePath, UriPath modulePath) { if (getHostModule(modulePath) != null) { return modulePath; } else { return moduleResolver().resolveModulePath(basePath, modulePath); } } @Override public Source loadModuleSource(UriPath moduleId) { return moduleResolver().loadModuleSource(moduleId); } @Override public JsModule loadModule(JsModuleSystem moduleSystem, UriPath moduleId) { JsModule module = loadHostModule(moduleSystem, moduleId); if (module == null) { module = loadGuestModule(moduleSystem, moduleId); } return module; } protected JsModule loadHostModule(JsModuleSystem moduleSystem, UriPath moduleId) { final HostLibrary hostLibrary = getHostModule(moduleId); if (hostLibrary != null) { return createHostModule(moduleSystem, moduleId, hostLibrary); } return null; } protected JsModule createHostModule(JsModuleSystem moduleSystem, UriPath moduleId, HostLibrary hostLibrary) { return new JsHostLibraryModule(this, moduleSystem, moduleId, hostLibrary); } protected JsModule loadGuestModule(JsModuleSystem moduleSystem, UriPath moduleId) { final Source moduleSource = loadModuleSource(moduleId); if (moduleSource != null) { return createGuestModule(moduleSystem, moduleId, moduleSource); } return null; } protected JsModule createGuestModule(JsModuleSystem moduleSystem, UriPath moduleId, Source moduleSource) { return new JsGuestModule(moduleSystem, moduleId, moduleSource); } @Override public void evalModule(JsModule module) { module.evalModule(); } public JsModule eval(UriPath moduleId, Source moduleSource) { final JsModuleSystem moduleSystem = new JsModuleSystem(this.jsContext, this); final JsModule module = createGuestModule(moduleSystem, moduleId, moduleSource); evalModule(module); return module; } public JsModule eval(UriPath moduleId, CharSequence source) { final Source moduleSource = Source.newBuilder("js", source, moduleId.toString()).buildLiteral(); return eval(moduleId, moduleSource); } public JsModule eval(String moduleId, CharSequence source) { final Source moduleSource = Source.newBuilder("js", source, moduleId).buildLiteral(); return eval(UriPath.parse(moduleId), moduleSource); } }
0
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm/js/JsCachedModuleResolver.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.vm.js; import org.graalvm.polyglot.Source; import swim.uri.UriPath; import swim.util.HashGenCacheMap; public class JsCachedModuleResolver implements JsModuleResolver { final JsModuleResolver moduleResolver; final HashGenCacheMap<UriPath, Source> sourceCache; public JsCachedModuleResolver(JsModuleResolver moduleResolver) { this.moduleResolver = moduleResolver; this.sourceCache = createSourceCache(); } public final JsModuleResolver moduleResolver() { return this.moduleResolver; } @Override public UriPath resolveModulePath(UriPath basePath, UriPath modulePath) { return this.moduleResolver.resolveModulePath(basePath, modulePath); } @Override public Source loadModuleSource(UriPath moduleId) { Source moduleSource = this.sourceCache.get(moduleId); if (moduleSource == null) { moduleSource = this.moduleResolver.loadModuleSource(moduleId); this.sourceCache.put(moduleId, moduleSource); } return moduleSource; } static HashGenCacheMap<UriPath, Source> createSourceCache() { int sourceCacheSize; try { sourceCacheSize = Integer.parseInt(System.getProperty("swim.vm.js.source.cache.size")); } catch (NumberFormatException e) { sourceCacheSize = 128; } return new HashGenCacheMap<UriPath, Source>(sourceCacheSize); } }
0
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm/js/JsGuestModule.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.vm.js; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Source; import org.graalvm.polyglot.Value; import swim.uri.UriPath; public class JsGuestModule implements JsModule { final JsModuleSystem moduleSystem; final UriPath moduleId; final Source moduleSource; Value moduleExports; final JsGuestModuleObject moduleObject; final JsRequireFunction requireFunction; public JsGuestModule(JsModuleSystem moduleSystem, UriPath moduleId, Source moduleSource) { this.moduleSystem = moduleSystem; this.moduleId = moduleId; this.moduleSource = moduleSource; this.moduleExports = createModuleExports(); this.moduleObject = createModuleObject(); this.requireFunction = createRequireFunction(); } @Override public final JsModuleSystem moduleSystem() { return this.moduleSystem; } @Override public final UriPath moduleId() { return this.moduleId; } public final Source moduleSource() { return this.moduleSource; } @Override public final Value moduleExports() { return this.moduleExports; } void setModuleExports(Value moduleExports) { this.moduleExports = moduleExports; } protected Value createModuleExports() { return this.moduleSystem.jsContext.asValue(new JsGuestModuleExports(this)); } protected JsGuestModuleObject createModuleObject() { return new JsGuestModuleObject(this); } protected final JsGuestModuleObject moduleObject() { return this.moduleObject; } protected JsRequireFunction createRequireFunction() { return new JsRequireFunction(this); } public final JsRequireFunction requireFunction() { return this.requireFunction; } @Override public void evalModule() { final Context jsContext = this.moduleSystem.jsContext; final Value bindings = jsContext.getBindings("js"); bindings.putMember("require", this.requireFunction); bindings.putMember("module", this.moduleObject); bindings.putMember("exports", this.moduleExports); this.moduleSystem.jsContext.eval(this.moduleSource); bindings.removeMember("exports"); bindings.removeMember("module"); bindings.removeMember("require"); } public JsModule requireModule(UriPath modulePath) { return this.moduleSystem.requireModule(this.moduleId, modulePath); } }
0
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm/js/JsGuestModuleExports.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.vm.js; import java.util.Iterator; import org.graalvm.polyglot.Value; import org.graalvm.polyglot.proxy.ProxyObject; import swim.collections.HashTrieMap; import swim.vm.VmProxyArray; public class JsGuestModuleExports implements ProxyObject { final JsGuestModule module; HashTrieMap<String, Value> members; public JsGuestModuleExports(JsGuestModule module) { this.module = module; this.members = HashTrieMap.empty(); } public final JsGuestModule module() { return this.module; } @Override public boolean hasMember(String key) { return this.members.containsKey(key); } @Override public Object getMember(String key) { return this.members.get(key); } @Override public void putMember(String key, Value value) { this.members = this.members.updated(key, value); } @Override public boolean removeMember(String key) { final HashTrieMap<String, Value> oldMembers = this.members; final HashTrieMap<String, Value> newMembers = oldMembers.removed(key); if (oldMembers != newMembers) { this.members = newMembers; return true; } else { return false; } } @Override public Object getMemberKeys() { final HashTrieMap<String, Value> members = this.members; final String[] memberKeys = new String[members.size()]; final Iterator<String> memberKeyIterator = members.keyIterator(); int i = 0; while (memberKeyIterator.hasNext()) { memberKeys[i] = memberKeyIterator.next(); i += 1; } return new VmProxyArray(memberKeys); } }
0
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm
java-sources/ai/swim/swim-vm-js/3.10.0/swim/vm/js/JsGuestModuleLoader.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.vm.js; import org.graalvm.polyglot.Source; import swim.uri.UriPath; public class JsGuestModuleLoader implements JsModuleResolver, JsModuleLoader { final JsModuleResolver moduleResolver; public JsGuestModuleLoader(JsModuleResolver moduleResolver) { this.moduleResolver = moduleResolver; } public JsGuestModuleLoader() { this(new JsNodeModuleResolver()); } public final JsModuleResolver moduleResolver() { return this.moduleResolver; } @Override public UriPath resolveModulePath(UriPath basePath, UriPath modulePath) { return this.moduleResolver.resolveModulePath(basePath, modulePath); } @Override public Source loadModuleSource(UriPath moduleId) { return this.moduleResolver.loadModuleSource(moduleId); } @Override public JsModule loadModule(JsModuleSystem moduleSystem, UriPath moduleId) { final Source moduleSource = loadModuleSource(moduleId); if (moduleSource != null) { return createModule(moduleSystem, moduleId, moduleSource); } return null; } protected JsModule createModule(JsModuleSystem moduleSystem, UriPath moduleId, Source moduleSource) { return new JsGuestModule(moduleSystem, moduleId, moduleSource); } @Override public void evalModule(JsModule module) { module.evalModule(); } }