code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.thimbleware.jmemcached.protocol.exceptions;
/**
*/
public class ClientException extends Exception {
public ClientException() {
}
public ClientException(String s) {
super(s);
}
public ClientException(String s, Throwable throwable) {
super(s, throwable);
}
public ClientException(Throwable throwable) {
super(throwable);
}
}
| Java |
/**
* Copyright 2008 ThimbleWare Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
*/
public enum Op {
GET, GETS, APPEND, PREPEND, DELETE, DECR,
INCR, REPLACE, ADD, SET, CAS, STATS, VERSION,
QUIT, FLUSH_ALL, VERBOSITY;
private static Map<ChannelBuffer, Op> opsbf = new HashMap<ChannelBuffer, Op>();
static {
for (int x = 0 ; x < Op.values().length; x++) {
byte[] bytes = Op.values()[x].toString().toLowerCase().getBytes();
opsbf.put(ChannelBuffers.wrappedBuffer(bytes), Op.values()[x]);
}
}
public static Op FindOp(ChannelBuffer cmd) {
cmd.readerIndex(0);
return opsbf.get(cmd);
}
}
| Java |
package com.thimbleware.jmemcached.protocol;
import java.io.Serializable;
/**
* Class for holding the current session status.
*/
public final class SessionStatus implements Serializable {
/**
* Possible states that the current session is in.
*/
public static enum State {
WAITING_FOR_DATA,
READY,
PROCESSING_MULTILINE,
}
// the state the session is in
public State state;
// if we are waiting for more data, how much?
public int bytesNeeded;
// the current working command
public CommandMessage cmd;
public SessionStatus() {
ready();
}
public SessionStatus ready() {
this.cmd = null;
this.bytesNeeded = -1;
this.state = State.READY;
return this;
}
public SessionStatus processingMultiline() {
this.state = State.PROCESSING_MULTILINE;
return this;
}
public SessionStatus needMore(int size, CommandMessage cmd) {
this.cmd = cmd;
this.bytesNeeded = size;
this.state = State.WAITING_FOR_DATA;
return this;
}
}
| Java |
package com.thimbleware.jmemcached.protocol.text;
import com.thimbleware.jmemcached.CacheElement;
import com.thimbleware.jmemcached.Key;
import com.thimbleware.jmemcached.LocalCacheElement;
import com.thimbleware.jmemcached.protocol.CommandMessage;
import com.thimbleware.jmemcached.protocol.Op;
import com.thimbleware.jmemcached.protocol.SessionStatus;
import com.thimbleware.jmemcached.protocol.exceptions.IncorrectlyTerminatedPayloadException;
import com.thimbleware.jmemcached.protocol.exceptions.InvalidProtocolStateException;
import com.thimbleware.jmemcached.protocol.exceptions.MalformedCommandException;
import com.thimbleware.jmemcached.protocol.exceptions.UnknownCommandException;
import com.thimbleware.jmemcached.util.BufferUtils;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferIndexFinder;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import java.util.ArrayList;
import java.util.List;
/**
* The MemcachedCommandDecoder is responsible for taking lines from the MemcachedFrameDecoder and parsing them
* into CommandMessage instances for handling by the MemcachedCommandHandler
* <p/>
* Protocol status is held in the SessionStatus instance which is shared between each of the decoders in the pipeline.
*/
public final class MemcachedCommandDecoder extends FrameDecoder {
private static final int MIN_BYTES_LINE = 2;
private SessionStatus status;
private static final ChannelBuffer NOREPLY = ChannelBuffers.wrappedBuffer("noreply".getBytes());
public MemcachedCommandDecoder(SessionStatus status) {
this.status = status;
}
/**
* Index finder which locates a byte which is neither a {@code CR ('\r')}
* nor a {@code LF ('\n')}.
*/
static ChannelBufferIndexFinder CRLF_OR_WS = new ChannelBufferIndexFinder() {
public final boolean find(ChannelBuffer buffer, int guessedIndex) {
byte b = buffer.getByte(guessedIndex);
return b == ' ' || b == '\r' || b == '\n';
}
};
static boolean eol(int pos, ChannelBuffer buffer) {
return buffer.readableBytes() >= MIN_BYTES_LINE && buffer.getByte(buffer.readerIndex() + pos) == '\r' && buffer.getByte(buffer.readerIndex() + pos+1) == '\n';
}
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
if (status.state == SessionStatus.State.READY) {
ChannelBuffer in = buffer.slice();
// split into pieces
List<ChannelBuffer> pieces = new ArrayList<ChannelBuffer>(6);
if (in.readableBytes() < MIN_BYTES_LINE) return null;
int pos = in.bytesBefore(CRLF_OR_WS);
boolean eol = false;
do {
if (pos != -1) {
eol = eol(pos, in);
int skip = eol ? MIN_BYTES_LINE : 1;
ChannelBuffer slice = in.readSlice(pos);
slice.readerIndex(0);
pieces.add(slice);
in.skipBytes(skip);
if (eol) break;
}
} while ((pos = in.bytesBefore(CRLF_OR_WS)) != -1);
if (eol) {
buffer.skipBytes(in.readerIndex());
return processLine(pieces, channel, ctx);
}
if (status.state != SessionStatus.State.WAITING_FOR_DATA) status.ready();
} else if (status.state == SessionStatus.State.WAITING_FOR_DATA) {
if (buffer.readableBytes() >= status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity()) {
// verify delimiter matches at the right location
ChannelBuffer dest = buffer.slice(buffer.readerIndex() + status.bytesNeeded, MIN_BYTES_LINE);
if (!dest.equals(MemcachedResponseEncoder.CRLF)) {
// before we throw error... we're ready for the next command
status.ready();
// error, no delimiter at end of payload
throw new IncorrectlyTerminatedPayloadException("payload not terminated correctly");
} else {
status.processingMultiline();
// There's enough bytes in the buffer and the delimiter is at the end. Read it.
ChannelBuffer result = buffer.slice(buffer.readerIndex(), status.bytesNeeded);
buffer.skipBytes(status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity());
CommandMessage commandMessage = continueSet(channel, status, result, ctx);
if (status.state != SessionStatus.State.WAITING_FOR_DATA) status.ready();
return commandMessage;
}
}
} else {
throw new InvalidProtocolStateException("invalid protocol state");
}
return null;
}
/**
* Process an individual complete protocol line and either passes the command for processing by the
* session handler, or (in the case of SET-type commands) partially parses the command and sets the session into
* a state to wait for additional data.
*
* @param parts the (originally space separated) parts of the command
* @param channel the netty channel to operate on
* @param channelHandlerContext the netty channel handler context
* @throws com.thimbleware.jmemcached.protocol.exceptions.MalformedCommandException
* @throws com.thimbleware.jmemcached.protocol.exceptions.UnknownCommandException
*/
private Object processLine(List<ChannelBuffer> parts, Channel channel, ChannelHandlerContext channelHandlerContext) throws UnknownCommandException, MalformedCommandException {
final int numParts = parts.size();
// Turn the command into an enum for matching on
Op op;
try {
op = Op.FindOp(parts.get(0));
if (op == null)
throw new IllegalArgumentException("unknown operation: " + parts.get(0).toString());
} catch (IllegalArgumentException e) {
throw new UnknownCommandException("unknown operation: " + parts.get(0).toString());
}
// Produce the initial command message, for filling in later
CommandMessage cmd = CommandMessage.command(op);
switch (op) {
case DELETE:
cmd.setKey(parts.get(1));
if (numParts >= MIN_BYTES_LINE) {
if (parts.get(numParts - 1).equals(NOREPLY)) {
cmd.noreply = true;
if (numParts == 4)
cmd.time = BufferUtils.atoi(parts.get(MIN_BYTES_LINE));
} else if (numParts == 3)
cmd.time = BufferUtils.atoi(parts.get(MIN_BYTES_LINE));
}
return cmd;
case DECR:
case INCR:
// Malformed
if (numParts < MIN_BYTES_LINE || numParts > 3)
throw new MalformedCommandException("invalid increment command");
cmd.setKey(parts.get(1));
cmd.incrAmount = BufferUtils.atoi(parts.get(MIN_BYTES_LINE));
if (numParts == 3 && parts.get(MIN_BYTES_LINE).equals(NOREPLY)) {
cmd.noreply = true;
}
return cmd;
case FLUSH_ALL:
if (numParts >= 1) {
if (parts.get(numParts - 1).equals(NOREPLY)) {
cmd.noreply = true;
if (numParts == 3)
cmd.time = BufferUtils.atoi((parts.get(1)));
} else if (numParts == MIN_BYTES_LINE)
cmd.time = BufferUtils.atoi((parts.get(1)));
}
return cmd;
case VERBOSITY: // verbosity <time> [noreply]\r\n
// Malformed
if (numParts < MIN_BYTES_LINE || numParts > 3)
throw new MalformedCommandException("invalid verbosity command");
cmd.time = BufferUtils.atoi((parts.get(1))); // verbose level
if (numParts > 1 && parts.get(MIN_BYTES_LINE).equals(NOREPLY))
cmd.noreply = true;
return cmd;
case APPEND:
case PREPEND:
case REPLACE:
case ADD:
case SET:
case CAS:
// if we don't have all the parts, it's malformed
if (numParts < 5) {
throw new MalformedCommandException("invalid command length");
}
// Fill in all the elements of the command
int size = BufferUtils.atoi(parts.get(4));
long expire = BufferUtils.atoi(parts.get(3)) * 1000;
int flags = BufferUtils.atoi(parts.get(MIN_BYTES_LINE));
cmd.element = new LocalCacheElement(new Key(parts.get(1).slice()), flags, expire != 0 && expire < CacheElement.THIRTY_DAYS ? LocalCacheElement.Now() + expire : expire, 0L);
// look for cas and "noreply" elements
if (numParts > 5) {
int noreply = op == Op.CAS ? 6 : 5;
if (op == Op.CAS) {
cmd.cas_key = BufferUtils.atol(parts.get(5));
}
if (numParts == noreply + 1 && parts.get(noreply).equals(NOREPLY))
cmd.noreply = true;
}
// Now indicate that we need more for this command by changing the session status's state.
// This instructs the frame decoder to start collecting data for us.
status.needMore(size, cmd);
break;
//
case GET:
case GETS:
case STATS:
case VERSION:
case QUIT:
// Get all the keys
cmd.setKeys(parts.subList(1, numParts));
// Pass it on.
return cmd;
default:
throw new UnknownCommandException("unknown command: " + op);
}
return null;
}
/**
* Handles the continuation of a SET/ADD/REPLACE command with the data it was waiting for.
*
* @param channel netty channel
* @param state the current session status (unused)
* @param remainder the bytes picked up
* @param channelHandlerContext netty channel handler context
*/
private CommandMessage continueSet(Channel channel, SessionStatus state, ChannelBuffer remainder, ChannelHandlerContext channelHandlerContext) {
state.cmd.element.setData(remainder);
return state.cmd;
}
}
| Java |
package com.thimbleware.jmemcached.protocol.text;
import com.thimbleware.jmemcached.Cache;
import com.thimbleware.jmemcached.CacheElement;
import com.thimbleware.jmemcached.protocol.Op;
import com.thimbleware.jmemcached.protocol.ResponseMessage;
import com.thimbleware.jmemcached.protocol.exceptions.ClientException;
import com.thimbleware.jmemcached.util.BufferUtils;
import org.jboss.netty.channel.*;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.buffer.ChannelBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.thimbleware.jmemcached.protocol.text.MemcachedPipelineFactory.*;
import static java.lang.String.valueOf;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
/**
* Response encoder for the memcached text protocol. Produces strings destined for the StringEncoder
*/
public final class MemcachedResponseEncoder<CACHE_ELEMENT extends CacheElement> extends SimpleChannelUpstreamHandler {
final Logger logger = LoggerFactory.getLogger(MemcachedResponseEncoder.class);
public static final ChannelBuffer CRLF = ChannelBuffers.copiedBuffer("\r\n", USASCII);
private static final ChannelBuffer SPACE = ChannelBuffers.copiedBuffer(" ", USASCII);
private static final ChannelBuffer VALUE = ChannelBuffers.copiedBuffer("VALUE ", USASCII);
private static final ChannelBuffer EXISTS = ChannelBuffers.copiedBuffer("EXISTS\r\n", USASCII);
private static final ChannelBuffer NOT_FOUND = ChannelBuffers.copiedBuffer("NOT_FOUND\r\n", USASCII);
private static final ChannelBuffer NOT_STORED = ChannelBuffers.copiedBuffer("NOT_STORED\r\n", USASCII);
private static final ChannelBuffer STORED = ChannelBuffers.copiedBuffer("STORED\r\n", USASCII);
private static final ChannelBuffer DELETED = ChannelBuffers.copiedBuffer("DELETED\r\n", USASCII);
private static final ChannelBuffer END = ChannelBuffers.copiedBuffer("END\r\n", USASCII);
private static final ChannelBuffer OK = ChannelBuffers.copiedBuffer("OK\r\n", USASCII);
private static final ChannelBuffer ERROR = ChannelBuffers.copiedBuffer("ERROR\r\n", USASCII);
private static final ChannelBuffer CLIENT_ERROR = ChannelBuffers.copiedBuffer("CLIENT_ERROR\r\n", USASCII);
/**
* Handle exceptions in protocol processing. Exceptions are either client or internal errors. Report accordingly.
*
* @param ctx
* @param e
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
try {
throw e.getCause();
} catch (ClientException ce) {
if (ctx.getChannel().isOpen())
ctx.getChannel().write(CLIENT_ERROR);
} catch (Throwable tr) {
logger.error("error", tr);
if (ctx.getChannel().isOpen())
ctx.getChannel().write(ERROR);
}
}
@Override
public void messageReceived(ChannelHandlerContext channelHandlerContext, MessageEvent messageEvent) throws Exception {
ResponseMessage<CACHE_ELEMENT> command = (ResponseMessage<CACHE_ELEMENT>) messageEvent.getMessage();
Op cmd = command.cmd.op;
Channel channel = messageEvent.getChannel();
switch (cmd) {
case GET:
case GETS:
CacheElement[] results = command.elements;
ChannelBuffer[] buffers = new ChannelBuffer[results.length * (9 + (cmd == Op.GETS ? 2 : 0)) + 1];
int i = 0;
for (CacheElement result : results) {
if (result != null) {
buffers[i++] = VALUE;
buffers[i++] = result.getKey().bytes;
buffers[i++] = SPACE;
buffers[i++] = BufferUtils.itoa(result.getFlags());
buffers[i++] = SPACE;
buffers[i++] = BufferUtils.itoa(result.size());
if (cmd == Op.GETS) {
buffers[i++] = SPACE;
buffers[i++] = BufferUtils.ltoa(result.getCasUnique());
}
buffers[i++] = CRLF;
buffers[i++] = result.getData();
buffers[i++] = CRLF;
}
}
buffers[i] = END;
Channels.write(channel, ChannelBuffers.wrappedBuffer(buffers));
break;
case APPEND:
case PREPEND:
case ADD:
case SET:
case REPLACE:
case CAS:
if (!command.cmd.noreply)
Channels.write(channel, storeResponse(command.response));
break;
case DELETE:
if (!command.cmd.noreply)
Channels.write(channel, deleteResponseString(command.deleteResponse));
break;
case DECR:
case INCR:
if (!command.cmd.noreply)
Channels.write(channel, incrDecrResponseString(command.incrDecrResponse));
break;
case STATS:
for (Map.Entry<String, Set<String>> stat : command.stats.entrySet()) {
for (String statVal : stat.getValue()) {
StringBuilder builder = new StringBuilder();
builder.append("STAT ");
builder.append(stat.getKey());
builder.append(" ");
builder.append(String.valueOf(statVal));
builder.append("\r\n");
Channels.write(channel, ChannelBuffers.copiedBuffer(builder.toString(), USASCII));
}
}
Channels.write(channel, END.duplicate());
break;
case VERSION:
Channels.write(channel, ChannelBuffers.copiedBuffer("VERSION " + command.version + "\r\n", USASCII));
break;
case QUIT:
Channels.disconnect(channel);
break;
case FLUSH_ALL:
if (!command.cmd.noreply) {
ChannelBuffer ret = command.flushSuccess ? OK.duplicate() : ERROR.duplicate();
Channels.write(channel, ret);
}
break;
case VERBOSITY:
break;
default:
Channels.write(channel, ERROR.duplicate());
logger.error("error; unrecognized command: " + cmd);
}
}
private ChannelBuffer deleteResponseString(Cache.DeleteResponse deleteResponse) {
if (deleteResponse == Cache.DeleteResponse.DELETED) return DELETED.duplicate();
else return NOT_FOUND.duplicate();
}
private ChannelBuffer incrDecrResponseString(Integer ret) {
if (ret == null)
return NOT_FOUND.duplicate();
else
return ChannelBuffers.copiedBuffer(valueOf(ret) + "\r\n", USASCII);
}
/**
* Find the string response message which is equivalent to a response to a set/add/replace message
* in the cache
*
* @param storeResponse the response code
* @return the string to output on the network
*/
private ChannelBuffer storeResponse(Cache.StoreResponse storeResponse) {
switch (storeResponse) {
case EXISTS:
return EXISTS.duplicate();
case NOT_FOUND:
return NOT_FOUND.duplicate();
case NOT_STORED:
return NOT_STORED.duplicate();
case STORED:
return STORED.duplicate();
}
throw new RuntimeException("unknown store response from cache: " + storeResponse);
}
}
| Java |
package com.thimbleware.jmemcached.protocol.text;
import com.thimbleware.jmemcached.Cache;
import com.thimbleware.jmemcached.protocol.MemcachedCommandHandler;
import com.thimbleware.jmemcached.protocol.SessionStatus;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import java.nio.charset.Charset;
/**
*/
public final class MemcachedPipelineFactory implements ChannelPipelineFactory {
public static final Charset USASCII = Charset.forName("US-ASCII");
private Cache cache;
private String version;
private boolean verbose;
private int idleTime;
private int frameSize;
private DefaultChannelGroup channelGroup;
private final MemcachedResponseEncoder memcachedResponseEncoder = new MemcachedResponseEncoder();
private final MemcachedCommandHandler memcachedCommandHandler;
public MemcachedPipelineFactory(Cache cache, String version, boolean verbose, int idleTime, int frameSize, DefaultChannelGroup channelGroup) {
this.cache = cache;
this.version = version;
this.verbose = verbose;
this.idleTime = idleTime;
this.frameSize = frameSize;
this.channelGroup = channelGroup;
memcachedCommandHandler = new MemcachedCommandHandler(this.cache, this.version, this.verbose, this.idleTime, this.channelGroup);
}
public final ChannelPipeline getPipeline() throws Exception {
SessionStatus status = new SessionStatus().ready();
return Channels.pipeline(
new MemcachedCommandDecoder(status),
memcachedCommandHandler,
memcachedResponseEncoder);
}
}
| Java |
/**
* Copyright 2008 ThimbleWare Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached.protocol;
import com.thimbleware.jmemcached.Cache;
import com.thimbleware.jmemcached.CacheElement;
import com.thimbleware.jmemcached.Key;
import com.thimbleware.jmemcached.protocol.exceptions.UnknownCommandException;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicInteger;
// TODO implement flush_all delay
/**
* The actual command handler, which is responsible for processing the CommandMessage instances
* that are inbound from the protocol decoders.
* <p/>
* One instance is shared among the entire pipeline, since this handler is stateless, apart from some globals
* for the entire daemon.
* <p/>
* The command handler produces ResponseMessages which are destined for the response encoder.
*/
@ChannelHandler.Sharable
public final class MemcachedCommandHandler<CACHE_ELEMENT extends CacheElement> extends SimpleChannelUpstreamHandler {
final Logger logger = LoggerFactory.getLogger(MemcachedCommandHandler.class);
public final AtomicInteger curr_conns = new AtomicInteger();
public final AtomicInteger total_conns = new AtomicInteger();
/**
* The following state variables are universal for the entire daemon. These are used for statistics gathering.
* In order for these values to work properly, the handler _must_ be declared with a ChannelPipelineCoverage
* of "all".
*/
public final String version;
public final int idle_limit;
public final boolean verbose;
/**
* The actual physical data storage.
*/
private final Cache<CACHE_ELEMENT> cache;
/**
* The channel group for the entire daemon, used for handling global cleanup on shutdown.
*/
private final DefaultChannelGroup channelGroup;
/**
* Construct the server session handler
*
* @param cache the cache to use
* @param memcachedVersion the version string to return to clients
* @param verbosity verbosity level for debugging
* @param idle how long sessions can be idle for
* @param channelGroup
*/
public MemcachedCommandHandler(Cache cache, String memcachedVersion, boolean verbosity, int idle, DefaultChannelGroup channelGroup) {
this.cache = cache;
version = memcachedVersion;
verbose = verbosity;
idle_limit = idle;
this.channelGroup = channelGroup;
}
/**
* On open we manage some statistics, and add this connection to the channel group.
*
* @param channelHandlerContext
* @param channelStateEvent
* @throws Exception
*/
@Override
public void channelOpen(ChannelHandlerContext channelHandlerContext, ChannelStateEvent channelStateEvent) throws Exception {
total_conns.incrementAndGet();
curr_conns.incrementAndGet();
channelGroup.add(channelHandlerContext.getChannel());
}
/**
* On close we manage some statistics, and remove this connection from the channel group.
*
* @param channelHandlerContext
* @param channelStateEvent
* @throws Exception
*/
@Override
public void channelClosed(ChannelHandlerContext channelHandlerContext, ChannelStateEvent channelStateEvent) throws Exception {
curr_conns.decrementAndGet();
channelGroup.remove(channelHandlerContext.getChannel());
}
/**
* The actual meat of the matter. Turn CommandMessages into executions against the physical cache, and then
* pass on the downstream messages.
*
* @param channelHandlerContext
* @param messageEvent
* @throws Exception
*/
@Override
@SuppressWarnings("unchecked")
public void messageReceived(ChannelHandlerContext channelHandlerContext, MessageEvent messageEvent) throws Exception {
if (!(messageEvent.getMessage() instanceof CommandMessage)) {
// Ignore what this encoder can't encode.
channelHandlerContext.sendUpstream(messageEvent);
return;
}
CommandMessage<CACHE_ELEMENT> command = (CommandMessage<CACHE_ELEMENT>) messageEvent.getMessage();
Op cmd = command.op;
int cmdKeysSize = command.keys == null ? 0 : command.keys.size();
// first process any messages in the delete queue
cache.asyncEventPing();
// now do the real work
if (this.verbose) {
StringBuilder log = new StringBuilder();
log.append(cmd);
if (command.element != null) {
log.append(" ").append(command.element.getKey());
}
for (int i = 0; i < cmdKeysSize; i++) {
log.append(" ").append(command.keys.get(i));
}
logger.info(log.toString());
}
Channel channel = messageEvent.getChannel();
if (cmd == null) handleNoOp(channelHandlerContext, command);
else
switch (cmd) {
case GET:
case GETS:
handleGets(channelHandlerContext, command, channel);
break;
case APPEND:
handleAppend(channelHandlerContext, command, channel);
break;
case PREPEND:
handlePrepend(channelHandlerContext, command, channel);
break;
case DELETE:
handleDelete(channelHandlerContext, command, channel);
break;
case DECR:
handleDecr(channelHandlerContext, command, channel);
break;
case INCR:
handleIncr(channelHandlerContext, command, channel);
break;
case REPLACE:
handleReplace(channelHandlerContext, command, channel);
break;
case ADD:
handleAdd(channelHandlerContext, command, channel);
break;
case SET:
handleSet(channelHandlerContext, command, channel);
break;
case CAS:
handleCas(channelHandlerContext, command, channel);
break;
case STATS:
handleStats(channelHandlerContext, command, cmdKeysSize, channel);
break;
case VERSION:
handleVersion(channelHandlerContext, command, channel);
break;
case QUIT:
handleQuit(channel);
break;
case FLUSH_ALL:
handleFlush(channelHandlerContext, command, channel);
break;
case VERBOSITY:
handleVerbosity(channelHandlerContext, command, channel);
break;
default:
throw new UnknownCommandException("unknown command");
}
}
protected void handleNoOp(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command) {
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command));
}
protected void handleFlush(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withFlushResponse(cache.flush_all(command.time)), channel.getRemoteAddress());
}
protected void handleVerbosity(ChannelHandlerContext channelHandlerContext, CommandMessage command, Channel channel) {
//TODO set verbosity mode
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command), channel.getRemoteAddress());
}
protected void handleQuit(Channel channel) {
channel.disconnect();
}
protected void handleVersion(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
ResponseMessage responseMessage = new ResponseMessage(command);
responseMessage.version = version;
Channels.fireMessageReceived(channelHandlerContext, responseMessage, channel.getRemoteAddress());
}
protected void handleStats(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, int cmdKeysSize, Channel channel) {
String option = "";
if (cmdKeysSize > 0) {
option = command.keys.get(0).bytes.toString();
}
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withStatResponse(cache.stat(option)), channel.getRemoteAddress());
}
protected void handleDelete(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Cache.DeleteResponse dr = cache.delete(command.keys.get(0), command.time);
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withDeleteResponse(dr), channel.getRemoteAddress());
}
protected void handleDecr(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Integer incrDecrResp = cache.get_add(command.keys.get(0), -1 * command.incrAmount);
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withIncrDecrResponse(incrDecrResp), channel.getRemoteAddress());
}
protected void handleIncr(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Integer incrDecrResp = cache.get_add(command.keys.get(0), command.incrAmount); // TODO support default value and expiry!!
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withIncrDecrResponse(incrDecrResp), channel.getRemoteAddress());
}
protected void handlePrepend(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Cache.StoreResponse ret;
ret = cache.prepend(command.element);
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress());
}
protected void handleAppend(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Cache.StoreResponse ret;
ret = cache.append(command.element);
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress());
}
protected void handleReplace(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Cache.StoreResponse ret;
ret = cache.replace(command.element);
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress());
}
protected void handleAdd(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Cache.StoreResponse ret;
ret = cache.add(command.element);
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress());
}
protected void handleCas(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Cache.StoreResponse ret;
ret = cache.cas(command.cas_key, command.element);
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress());
}
protected void handleSet(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Cache.StoreResponse ret;
ret = cache.set(command.element);
Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel.getRemoteAddress());
}
protected void handleGets(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) {
Key[] keys = new Key[command.keys.size()];
keys = command.keys.toArray(keys);
CACHE_ELEMENT[] results = get(keys);
ResponseMessage<CACHE_ELEMENT> resp = new ResponseMessage<CACHE_ELEMENT>(command).withElements(results);
Channels.fireMessageReceived(channelHandlerContext, resp, channel.getRemoteAddress());
}
/**
* Get an element from the cache
*
* @param keys the key for the element to lookup
* @return the element, or 'null' in case of cache miss.
*/
private CACHE_ELEMENT[] get(Key... keys) {
return cache.get(keys);
}
/**
* @return the current time in seconds (from epoch), used for expiries, etc.
*/
private static int Now() {
return (int) (System.currentTimeMillis() / 1000);
}
} | Java |
package com.thimbleware.jmemcached.protocol.binary;
import com.thimbleware.jmemcached.Key;
import com.thimbleware.jmemcached.LocalCacheElement;
import com.thimbleware.jmemcached.CacheElement;
import com.thimbleware.jmemcached.protocol.Op;
import com.thimbleware.jmemcached.protocol.CommandMessage;
import com.thimbleware.jmemcached.protocol.exceptions.MalformedCommandException;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.nio.ByteOrder;
/**
*/
@ChannelHandler.Sharable
public class MemcachedBinaryCommandDecoder extends FrameDecoder {
public static final Charset USASCII = Charset.forName("US-ASCII");
public static enum BinaryOp {
Get(0x00, Op.GET, false),
Set(0x01, Op.SET, false),
Add(0x02, Op.ADD, false),
Replace(0x03, Op.REPLACE, false),
Delete(0x04, Op.DELETE, false),
Increment(0x05, Op.INCR, false),
Decrement(0x06, Op.DECR, false),
Quit(0x07, Op.QUIT, false),
Flush(0x08, Op.FLUSH_ALL, false),
GetQ(0x09, Op.GET, false),
Noop(0x0A, null, false),
Version(0x0B, Op.VERSION, false),
GetK(0x0C, Op.GET, false, true),
GetKQ(0x0D, Op.GET, true, true),
Append(0x0E, Op.APPEND, false),
Prepend(0x0F, Op.PREPEND, false),
Stat(0x10, Op.STATS, false),
SetQ(0x11, Op.SET, true),
AddQ(0x12, Op.ADD, true),
ReplaceQ(0x13, Op.REPLACE, true),
DeleteQ(0x14, Op.DELETE, true),
IncrementQ(0x15, Op.INCR, true),
DecrementQ(0x16, Op.DECR, true),
QuitQ(0x17, Op.QUIT, true),
FlushQ(0x18, Op.FLUSH_ALL, true),
AppendQ(0x19, Op.APPEND, true),
PrependQ(0x1A, Op.PREPEND, true);
public byte code;
public Op correspondingOp;
public boolean noreply;
public boolean addKeyToResponse = false;
BinaryOp(int code, Op correspondingOp, boolean noreply) {
this.code = (byte)code;
this.correspondingOp = correspondingOp;
this.noreply = noreply;
}
BinaryOp(int code, Op correspondingOp, boolean noreply, boolean addKeyToResponse) {
this.code = (byte)code;
this.correspondingOp = correspondingOp;
this.noreply = noreply;
this.addKeyToResponse = addKeyToResponse;
}
public static BinaryOp forCommandMessage(CommandMessage msg) {
for (BinaryOp binaryOp : values()) {
if (binaryOp.correspondingOp == msg.op && binaryOp.noreply == msg.noreply && binaryOp.addKeyToResponse == msg.addKeyToResponse) {
return binaryOp;
}
}
return null;
}
}
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception {
// need at least 24 bytes, to get header
if (channelBuffer.readableBytes() < 24) return null;
// get the header
channelBuffer.markReaderIndex();
ChannelBuffer headerBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24);
channelBuffer.readBytes(headerBuffer);
short magic = headerBuffer.readUnsignedByte();
// magic should be 0x80
if (magic != 0x80) {
headerBuffer.resetReaderIndex();
throw new MalformedCommandException("binary request payload is invalid, magic byte incorrect");
}
short opcode = headerBuffer.readUnsignedByte();
short keyLength = headerBuffer.readShort();
short extraLength = headerBuffer.readUnsignedByte();
short dataType = headerBuffer.readUnsignedByte(); // unused
short reserved = headerBuffer.readShort(); // unused
int totalBodyLength = headerBuffer.readInt();
int opaque = headerBuffer.readInt();
long cas = headerBuffer.readLong();
// we want the whole of totalBodyLength; otherwise, keep waiting.
if (channelBuffer.readableBytes() < totalBodyLength) {
channelBuffer.resetReaderIndex();
return null;
}
// This assumes correct order in the enum. If that ever changes, we will have to scan for 'code' field.
BinaryOp bcmd = BinaryOp.values()[opcode];
Op cmdType = bcmd.correspondingOp;
CommandMessage cmdMessage = CommandMessage.command(cmdType);
cmdMessage.noreply = bcmd.noreply;
cmdMessage.cas_key = cas;
cmdMessage.opaque = opaque;
cmdMessage.addKeyToResponse = bcmd.addKeyToResponse;
// get extras. could be empty.
ChannelBuffer extrasBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, extraLength);
channelBuffer.readBytes(extrasBuffer);
// get the key if any
if (keyLength != 0) {
ChannelBuffer keyBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, keyLength);
channelBuffer.readBytes(keyBuffer);
ArrayList<Key> keys = new ArrayList<Key>();
keys.add(new Key(keyBuffer.copy()));
cmdMessage.keys = keys;
if (cmdType == Op.ADD ||
cmdType == Op.SET ||
cmdType == Op.REPLACE ||
cmdType == Op.APPEND ||
cmdType == Op.PREPEND)
{
// TODO these are backwards from the spec, but seem to be what spymemcached demands -- which has the mistake?!
long expire = ((short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0)) * 1000;
short flags = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0);
// the remainder of the message -- that is, totalLength - (keyLength + extraLength) should be the payload
int size = totalBodyLength - keyLength - extraLength;
cmdMessage.element = new LocalCacheElement(new Key(keyBuffer.slice()), flags, expire != 0 && expire < CacheElement.THIRTY_DAYS ? LocalCacheElement.Now() + expire : expire, 0L);
ChannelBuffer data = ChannelBuffers.buffer(size);
channelBuffer.readBytes(data);
cmdMessage.element.setData(data);
} else if (cmdType == Op.INCR || cmdType == Op.DECR) {
long initialValue = extrasBuffer.readUnsignedInt();
long amount = extrasBuffer.readUnsignedInt();
long expiration = extrasBuffer.readUnsignedInt();
cmdMessage.incrAmount = (int) amount;
cmdMessage.incrExpiry = (int) expiration;
}
}
return cmdMessage;
}
}
| Java |
package com.thimbleware.jmemcached.protocol.binary;
import com.thimbleware.jmemcached.protocol.Op;
import com.thimbleware.jmemcached.protocol.ResponseMessage;
import com.thimbleware.jmemcached.protocol.exceptions.UnknownCommandException;
import com.thimbleware.jmemcached.CacheElement;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteOrder;
import java.util.Set;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
*/
// TODO refactor so this can be unit tested separate from netty? scalacheck?
@ChannelHandler.Sharable
public class MemcachedBinaryResponseEncoder<CACHE_ELEMENT extends CacheElement> extends SimpleChannelUpstreamHandler {
private ConcurrentHashMap<Integer, ChannelBuffer> corkedBuffers = new ConcurrentHashMap<Integer, ChannelBuffer>();
final Logger logger = LoggerFactory.getLogger(MemcachedBinaryResponseEncoder.class);
public static enum ResponseCode {
OK(0x0000),
KEYNF(0x0001),
KEYEXISTS(0x0002),
TOOLARGE(0x0003),
INVARG(0x0004),
NOT_STORED(0x0005),
UNKNOWN(0x0081),
OOM(0x00082);
public short code;
ResponseCode(int code) {
this.code = (short)code;
}
}
public ResponseCode getStatusCode(ResponseMessage command) {
Op cmd = command.cmd.op;
if (cmd == Op.GET || cmd == Op.GETS) {
return ResponseCode.OK;
} else if (cmd == Op.SET || cmd == Op.CAS || cmd == Op.ADD || cmd == Op.REPLACE || cmd == Op.APPEND || cmd == Op.PREPEND) {
switch (command.response) {
case EXISTS:
return ResponseCode.KEYEXISTS;
case NOT_FOUND:
return ResponseCode.KEYNF;
case NOT_STORED:
return ResponseCode.NOT_STORED;
case STORED:
return ResponseCode.OK;
}
} else if (cmd == Op.INCR || cmd == Op.DECR) {
return command.incrDecrResponse == null ? ResponseCode.KEYNF : ResponseCode.OK;
} else if (cmd == Op.DELETE) {
switch (command.deleteResponse) {
case DELETED:
return ResponseCode.OK;
case NOT_FOUND:
return ResponseCode.KEYNF;
}
} else if (cmd == Op.STATS) {
return ResponseCode.OK;
} else if (cmd == Op.VERSION) {
return ResponseCode.OK;
} else if (cmd == Op.FLUSH_ALL) {
return ResponseCode.OK;
}
return ResponseCode.UNKNOWN;
}
public ChannelBuffer constructHeader(MemcachedBinaryCommandDecoder.BinaryOp bcmd, ChannelBuffer extrasBuffer, ChannelBuffer keyBuffer, ChannelBuffer valueBuffer, short responseCode, int opaqueValue, long casUnique) {
// take the ResponseMessage and turn it into a binary payload.
ChannelBuffer header = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24);
header.writeByte((byte)0x81); // magic
header.writeByte(bcmd.code); // opcode
short keyLength = (short) (keyBuffer != null ? keyBuffer.capacity() :0);
header.writeShort(keyLength);
int extrasLength = extrasBuffer != null ? extrasBuffer.capacity() : 0;
header.writeByte((byte) extrasLength); // extra length = flags + expiry
header.writeByte((byte)0); // data type unused
header.writeShort(responseCode); // status code
int dataLength = valueBuffer != null ? valueBuffer.capacity() : 0;
header.writeInt(dataLength + keyLength + extrasLength); // data length
header.writeInt(opaqueValue); // opaque
header.writeLong(casUnique);
return header;
}
/**
* Handle exceptions in protocol processing. Exceptions are either client or internal errors. Report accordingly.
*
* @param ctx
* @param e
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
try {
throw e.getCause();
} catch (UnknownCommandException unknownCommand) {
if (ctx.getChannel().isOpen())
ctx.getChannel().write(constructHeader(MemcachedBinaryCommandDecoder.BinaryOp.Noop, null, null, null, (short)0x0081, 0, 0));
} catch (Throwable err) {
logger.error("error", err);
if (ctx.getChannel().isOpen())
ctx.getChannel().close();
}
}
@Override
@SuppressWarnings("unchecked")
public void messageReceived(ChannelHandlerContext channelHandlerContext, MessageEvent messageEvent) throws Exception {
ResponseMessage<CACHE_ELEMENT> command = (ResponseMessage<CACHE_ELEMENT>) messageEvent.getMessage();
Object additional = messageEvent.getMessage();
MemcachedBinaryCommandDecoder.BinaryOp bcmd = MemcachedBinaryCommandDecoder.BinaryOp.forCommandMessage(command.cmd);
// write extras == flags & expiry
ChannelBuffer extrasBuffer = null;
// write key if there is one
ChannelBuffer keyBuffer = null;
if (bcmd.addKeyToResponse && command.cmd.keys != null && command.cmd.keys.size() != 0) {
keyBuffer = ChannelBuffers.wrappedBuffer(command.cmd.keys.get(0).bytes);
}
// write value if there is one
ChannelBuffer valueBuffer = null;
if (command.elements != null) {
extrasBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 4);
CacheElement element = command.elements[0];
extrasBuffer.writeShort((short) (element != null ? element.getExpire() : 0));
extrasBuffer.writeShort((short) (element != null ? element.getFlags() : 0));
if ((command.cmd.op == Op.GET || command.cmd.op == Op.GETS)) {
if (element != null) {
valueBuffer = ChannelBuffers.wrappedBuffer(element.getData());
} else {
valueBuffer = ChannelBuffers.buffer(0);
}
} else if (command.cmd.op == Op.INCR || command.cmd.op == Op.DECR) {
valueBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 8);
valueBuffer.writeLong(command.incrDecrResponse);
}
} else if (command.cmd.op == Op.INCR || command.cmd.op == Op.DECR) {
valueBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 8);
valueBuffer.writeLong(command.incrDecrResponse);
}
long casUnique = 0;
if (command.elements != null && command.elements.length != 0 && command.elements[0] != null) {
casUnique = command.elements[0].getCasUnique();
}
// stats is special -- with it, we write N times, one for each stat, then an empty payload
if (command.cmd.op == Op.STATS) {
// first uncork any corked buffers
if (corkedBuffers.containsKey(command.cmd.opaque)) uncork(command.cmd.opaque, messageEvent.getChannel());
for (Map.Entry<String, Set<String>> statsEntries : command.stats.entrySet()) {
for (String stat : statsEntries.getValue()) {
keyBuffer = ChannelBuffers.wrappedBuffer(ByteOrder.BIG_ENDIAN, statsEntries.getKey().getBytes(MemcachedBinaryCommandDecoder.USASCII));
valueBuffer = ChannelBuffers.wrappedBuffer(ByteOrder.BIG_ENDIAN, stat.getBytes(MemcachedBinaryCommandDecoder.USASCII));
ChannelBuffer headerBuffer = constructHeader(bcmd, extrasBuffer, keyBuffer, valueBuffer, getStatusCode(command).code, command.cmd.opaque, casUnique);
writePayload(messageEvent, extrasBuffer, keyBuffer, valueBuffer, headerBuffer);
}
}
keyBuffer = null;
valueBuffer = null;
ChannelBuffer headerBuffer = constructHeader(bcmd, extrasBuffer, keyBuffer, valueBuffer, getStatusCode(command).code, command.cmd.opaque, casUnique);
writePayload(messageEvent, extrasBuffer, keyBuffer, valueBuffer, headerBuffer);
} else {
ChannelBuffer headerBuffer = constructHeader(bcmd, extrasBuffer, keyBuffer, valueBuffer, getStatusCode(command).code, command.cmd.opaque, casUnique);
// write everything
// is the command 'quiet?' if so, then we append to our 'corked' buffer until a non-corked command comes along
if (bcmd.noreply) {
int totalCapacity = headerBuffer.capacity() + (extrasBuffer != null ? extrasBuffer.capacity() : 0)
+ (keyBuffer != null ? keyBuffer.capacity() : 0) + (valueBuffer != null ? valueBuffer.capacity() : 0);
ChannelBuffer corkedResponse = cork(command.cmd.opaque, totalCapacity);
corkedResponse.writeBytes(headerBuffer);
if (extrasBuffer != null)
corkedResponse.writeBytes(extrasBuffer);
if (keyBuffer != null)
corkedResponse.writeBytes(keyBuffer);
if (valueBuffer != null)
corkedResponse.writeBytes(valueBuffer);
} else {
// first write out any corked responses
if (corkedBuffers.containsKey(command.cmd.opaque)) uncork(command.cmd.opaque, messageEvent.getChannel());
writePayload(messageEvent, extrasBuffer, keyBuffer, valueBuffer, headerBuffer);
}
}
}
private ChannelBuffer cork(int opaque, int totalCapacity) {
if (corkedBuffers.containsKey(opaque)) {
ChannelBuffer corkedResponse = corkedBuffers.get(opaque);
ChannelBuffer oldBuffer = corkedResponse;
corkedResponse = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, totalCapacity + corkedResponse.capacity());
corkedResponse.writeBytes(oldBuffer);
oldBuffer.clear();
corkedBuffers.remove(opaque);
corkedBuffers.put(opaque, corkedResponse);
return corkedResponse;
} else {
ChannelBuffer buffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, totalCapacity);
corkedBuffers.put(opaque, buffer);
return buffer;
}
}
private void uncork(int opaque, Channel channel) {
ChannelBuffer corkedBuffer = corkedBuffers.get(opaque);
assert corkedBuffer != null;
channel.write(corkedBuffer);
corkedBuffers.remove(opaque);
}
private void writePayload(MessageEvent messageEvent, ChannelBuffer extrasBuffer, ChannelBuffer keyBuffer, ChannelBuffer valueBuffer, ChannelBuffer headerBuffer) {
if (messageEvent.getChannel().isOpen()) {
messageEvent.getChannel().write(headerBuffer);
if (extrasBuffer != null)
messageEvent.getChannel().write(extrasBuffer);
if (keyBuffer != null)
messageEvent.getChannel().write(keyBuffer);
if (valueBuffer != null)
messageEvent.getChannel().write(valueBuffer);
}
}
}
| Java |
package com.thimbleware.jmemcached.protocol.binary;
import com.thimbleware.jmemcached.Cache;
import com.thimbleware.jmemcached.protocol.MemcachedCommandHandler;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.DefaultChannelGroup;
public class MemcachedBinaryPipelineFactory implements ChannelPipelineFactory {
private final MemcachedBinaryCommandDecoder decoder = new MemcachedBinaryCommandDecoder();
private final MemcachedCommandHandler memcachedCommandHandler;
private final MemcachedBinaryResponseEncoder memcachedBinaryResponseEncoder = new MemcachedBinaryResponseEncoder();
public MemcachedBinaryPipelineFactory(Cache cache, String version, boolean verbose, int idleTime, DefaultChannelGroup channelGroup) {
memcachedCommandHandler = new MemcachedCommandHandler(cache, version, verbose, idleTime, channelGroup);
}
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
decoder,
memcachedCommandHandler,
memcachedBinaryResponseEncoder
);
}
}
| Java |
/**
* Copyright 2008 ThimbleWare Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached.protocol;
import com.thimbleware.jmemcached.CacheElement;
import com.thimbleware.jmemcached.Key;
import org.jboss.netty.buffer.ChannelBuffer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* The payload object holding the parsed message.
*/
public final class CommandMessage<CACHE_ELEMENT extends CacheElement> implements Serializable {
public Op op;
public CACHE_ELEMENT element;
public List<Key> keys;
public boolean noreply;
public long cas_key;
public int time = 0;
public int opaque;
public boolean addKeyToResponse = false;
public int incrExpiry;
public int incrAmount;
private CommandMessage(Op op) {
this.op = op;
element = null;
}
public void setKey(ChannelBuffer key) {
this.keys = new ArrayList<Key>();
this.keys.add(new Key(key));
}
public void setKeys(List<ChannelBuffer> keys) {
this.keys = new ArrayList<Key>(keys.size());
for (ChannelBuffer key : keys) {
this.keys.add(new Key(key));
}
}
public static CommandMessage command(Op operation) {
return new CommandMessage(operation);
}
} | Java |
package com.thimbleware.jmemcached.storage.mmap;
import com.thimbleware.jmemcached.storage.bytebuffer.BlockStoreFactory;
import com.thimbleware.jmemcached.storage.bytebuffer.ByteBufferBlockStore;
import org.jboss.netty.buffer.ChannelBuffers;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import static java.nio.channels.FileChannel.MapMode.*;
/**
* Memory mapped block storage mechanism with a free-list maintained by TreeMap
*
* Allows memory for storage to be mapped outside of the VM's main memory, and outside the purvey
* of the GC.
*
* Should offer O(Log(N)) search and free of blocks.
*/
public final class MemoryMappedBlockStore extends ByteBufferBlockStore {
private File physicalFile;
private RandomAccessFile fileStorage;
private static final MemoryMappedBlockStoreFactory MEMORY_MAPPED_BLOCK_STORE_FACTORY = new MemoryMappedBlockStoreFactory();
/**
* Construct a new memory mapped block storage against a filename, with a certain size
* and block size.
* @param maxBytes the number of bytes to allocate in the file
* @param file the file to use
* @param blockSizeBytes the size of a block in the store
* @throws java.io.IOException thrown on failure to open the store or map the file
*/
private MemoryMappedBlockStore(long maxBytes, File file, int blockSizeBytes) throws IOException {
super(blockSizeBytes);
storageBuffer = ChannelBuffers.wrappedBuffer(getMemoryMappedFileStorage(maxBytes, file));
initialize(storageBuffer.capacity());
}
public static BlockStoreFactory getFactory() {
return MEMORY_MAPPED_BLOCK_STORE_FACTORY;
}
private MappedByteBuffer getMemoryMappedFileStorage(long maxBytes, File file) throws IOException {
this.physicalFile = file;
// open the file for read-write
fileStorage = new RandomAccessFile(file, "rw");
fileStorage.seek(maxBytes);
return fileStorage.getChannel().map(PRIVATE, 0, maxBytes);
}
@Override
protected void freeResources() throws IOException {
super.freeResources();
// close the actual file
fileStorage.close();
// delete the file; it is no longer of any use
physicalFile.delete();
physicalFile = null;
fileStorage = null;
}
public static class MemoryMappedBlockStoreFactory implements BlockStoreFactory<MemoryMappedBlockStore> {
public MemoryMappedBlockStore manufacture(long sizeBytes, int blockSizeBytes) {
try {
final File tempFile = File.createTempFile("jmemcached", "blockStore");
tempFile.deleteOnExit();
return new MemoryMappedBlockStore(sizeBytes, tempFile, blockSizeBytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java |
package com.thimbleware.jmemcached.storage.bytebuffer;
/**
*/
public interface BlockStoreFactory<BS extends ByteBufferBlockStore> {
BS manufacture(long sizeBytes, int blockSizeBytes);
}
| Java |
package com.thimbleware.jmemcached.storage.bytebuffer;
import com.thimbleware.jmemcached.Key;
import com.thimbleware.jmemcached.LocalCacheElement;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
*/
public final class Partition {
private static final int NUM_BUCKETS = 32768;
ReentrantReadWriteLock storageLock = new ReentrantReadWriteLock();
ChannelBuffer[] buckets = new ChannelBuffer[NUM_BUCKETS];
ByteBufferBlockStore blockStore;
int numberItems;
Partition(ByteBufferBlockStore blockStore) {
this.blockStore = blockStore;
}
public Region find(Key key) {
int bucket = findBucketNum(key);
if (buckets[bucket] == null) return null;
ChannelBuffer regions = buckets[bucket].slice();
regions.readerIndex(0);
while (regions.readableBytes() > 0) {
int totsize = regions.readInt();
int rsize = regions.readInt();
int rusedBlocks = regions.readInt();
int rstartBlock = regions.readInt();
long expiry = regions.readLong();
long timestamp = regions.readLong();
int rkeySize = regions.readInt();
if (rkeySize == key.bytes.capacity()) {
ChannelBuffer rkey = regions.readSlice(rkeySize);
key.bytes.readerIndex(0);
if (rkey.equals(key.bytes)) return new Region(rsize, rusedBlocks, rstartBlock, blockStore.get(rstartBlock, rsize), expiry, timestamp);
} else {
regions.skipBytes(rkeySize);
}
}
return null;
}
public boolean has(Key key) {
int bucket = findBucketNum(key);
if (buckets[bucket] == null) return false;
ChannelBuffer regions = buckets[bucket].slice();
regions.readerIndex(0);
while (regions.readableBytes() > 0) {
int totsize = regions.readInt();
regions.skipBytes(28);
int rkeySize = regions.readInt();
if (rkeySize == key.bytes.capacity()) {
ChannelBuffer rkey = regions.readSlice(rkeySize);
key.bytes.readerIndex(0);
if (rkey.equals(key.bytes)) return true;
} else {
regions.skipBytes(rkeySize);
}
}
return false;
}
private int findBucketNum(Key key) {
int hash = BlockStorageCacheStorage.hash(key.hashCode());
return hash & (buckets.length - 1);
}
public void remove(Key key, Region region) {
int bucket = findBucketNum(key);
ChannelBuffer newRegion = ChannelBuffers.dynamicBuffer(128);
ChannelBuffer regions = buckets[bucket].slice();
if (regions == null) return;
regions.readerIndex(0);
while (regions.readableBytes() > 0) {
// read key portion then region portion
int pos = regions.readerIndex();
int totsize = regions.readInt();
regions.skipBytes(28);
int rkeySize = regions.readInt();
ChannelBuffer rkey = regions.readBytes(rkeySize);
if (rkeySize != key.bytes.capacity() || !rkey.equals(key.bytes)) {
newRegion.writeBytes(regions.slice(pos, regions.readerIndex()));
}
}
buckets[bucket] = newRegion;
numberItems--;
}
public Region add(Key key, LocalCacheElement e) {
Region region = blockStore.alloc(e.bufferSize(), e.getExpire(), System.currentTimeMillis());
e.writeToBuffer(region.slice);
int bucket = findBucketNum(key);
ChannelBuffer outbuf = ChannelBuffers.directBuffer(32 + key.bytes.capacity());
outbuf.writeInt(region.size);
outbuf.writeInt(region.usedBlocks);
outbuf.writeInt(region.startBlock);
outbuf.writeLong(region.expiry);
outbuf.writeLong(region.timestamp);
outbuf.writeInt(key.bytes.capacity());
key.bytes.readerIndex(0);
outbuf.writeBytes(key.bytes);
ChannelBuffer regions = buckets[bucket];
if (regions == null) {
regions = ChannelBuffers.dynamicBuffer(128);
buckets[bucket] = regions;
}
regions.writeInt(outbuf.capacity());
regions.writeBytes(outbuf);
numberItems++;
return region;
}
public void clear() {
for (ChannelBuffer bucket : buckets) {
if (bucket != null)
bucket.clear();
}
blockStore.clear();
numberItems = 0;
}
public Collection<Key> keys() {
Set<Key> keys = new HashSet<Key>();
for (ChannelBuffer regionsa : buckets) {
if (regionsa != null) {
ChannelBuffer regions = regionsa.slice();
regions.readerIndex(0);
while (regions.readableBytes() > 0) {
// read key portion then region portion
int totsize = regions.readInt();
regions.skipBytes(28);
int rkeySize = regions.readInt();
ChannelBuffer rkey = regions.readBytes(rkeySize);
keys.add(new Key(rkey));
}
}
}
return keys;
}
public int getNumberItems() {
return numberItems;
}
}
| Java |
package com.thimbleware.jmemcached.storage.bytebuffer;
import com.thimbleware.jmemcached.Key;
import com.thimbleware.jmemcached.LocalCacheElement;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* Represents a number of allocated blocks in the store
*/
public final class Region {
/**
* Size in bytes of the requested area
*/
public final int size;
/**
* Size in blocks of the requested area
*/
public final int usedBlocks;
/**
* Offset into the memory region
*/
final int startBlock;
final long timestamp;
final long expiry;
/**
* Flag which is true if the region is valid and in use.
* Set to false on free()
*/
public boolean valid = false;
public ChannelBuffer slice;
public Region(int size, int usedBlocks, int startBlock, ChannelBuffer slice, long expiry, long timestamp) {
this.size = size;
this.usedBlocks = usedBlocks;
this.startBlock = startBlock;
this.slice = slice;
this.expiry = expiry;
this.timestamp = timestamp;
this.valid = true;
}
public Key keyFromRegion() {
slice.readerIndex(0);
int length = slice.readInt();
return new Key(slice.slice(slice.readerIndex(), length));
}
public LocalCacheElement toValue() {
slice.readerIndex(0);
return LocalCacheElement.readFromBuffer(slice);
}
}
| Java |
package com.thimbleware.jmemcached.storage.bytebuffer;
import com.thimbleware.jmemcached.Key;
import com.thimbleware.jmemcached.LocalCacheElement;
import com.thimbleware.jmemcached.storage.CacheStorage;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Implementation of the cache using the block buffer storage back end.
*/
public final class BlockStorageCacheStorage implements CacheStorage<Key, LocalCacheElement> {
Partition[] partitions;
volatile int ceilingBytes;
volatile int maximumItems;
volatile int numberItems;
final long maximumSizeBytes;
public BlockStorageCacheStorage(int blockStoreBuckets, int ceilingBytesParam, int blockSizeBytes, long maximumSizeBytes, int maximumItemsVal, BlockStoreFactory factory) {
this.partitions = new Partition[blockStoreBuckets];
long bucketSizeBytes = maximumSizeBytes / blockStoreBuckets;
for (int i = 0; i < blockStoreBuckets; i++) {
this.partitions[i] = new Partition(factory.manufacture(bucketSizeBytes, blockSizeBytes));
}
this.numberItems = 0;
this.ceilingBytes = 0;
this.maximumItems = 0;
this.maximumSizeBytes = maximumSizeBytes;
}
private Partition pickPartition(Key key) {
return partitions[hash(key.hashCode()) & (partitions.length - 1)];
}
public final long getMemoryCapacity() {
long capacity = 0;
for (Partition byteBufferBlockStore : partitions) {
capacity += byteBufferBlockStore.blockStore.getStoreSizeBytes();
}
return capacity;
}
public final long getMemoryUsed() {
long memUsed = 0;
for (Partition byteBufferBlockStore : partitions) {
memUsed += (byteBufferBlockStore.blockStore.getStoreSizeBytes() - byteBufferBlockStore.blockStore.getFreeBytes());
}
return memUsed;
}
public final int capacity() {
return maximumItems;
}
public final void close() throws IOException {
// first clear all items
clear();
// then ask the block store to close
for (Partition byteBufferBlockStore : partitions) {
byteBufferBlockStore.blockStore.close();
}
this.partitions = null;
}
public final LocalCacheElement putIfAbsent(Key key, LocalCacheElement item) {
Partition partition = pickPartition(key);
partition.storageLock.readLock().lock();
try {
Region region = partition.find(key);
// not there? add it
if (region == null) {
partition.storageLock.readLock().unlock();
partition.storageLock.writeLock().lock();
try {
numberItems++;
partition.add(key, item);
} finally {
partition.storageLock.readLock().lock();
partition.storageLock.writeLock().unlock();
}
return null;
} else {
// there? return its value
return region.toValue();
}
} finally {
partition.storageLock.readLock().unlock();
}
}
/**
* {@inheritDoc}
*/
public final boolean remove(Object okey, Object value) {
if (!(okey instanceof Key) || (!(value instanceof LocalCacheElement))) return false;
Key key = (Key) okey;
Partition partition = pickPartition(key);
try {
partition.storageLock.readLock().lock();
Region region = partition.find(key);
if (region == null) return false;
else {
partition.storageLock.readLock().unlock();
partition.storageLock.writeLock().lock();
try {
partition.blockStore.free(region);
partition.remove(key, region);
numberItems++;
return true;
} finally {
partition.storageLock.readLock().lock();
partition.storageLock.writeLock().unlock();
}
}
} finally {
partition.storageLock.readLock().unlock();
}
}
public final boolean replace(Key key, LocalCacheElement original, LocalCacheElement replace) {
Partition partition = pickPartition(key);
partition.storageLock.readLock().lock();
try {
Region region = partition.find(key);
// not there? that's a fail
if (region == null) return false;
// there, check for equivalence of value
LocalCacheElement el = null;
el = region.toValue();
if (!el.equals(original)) {
return false;
} else {
partition.storageLock.readLock().unlock();
partition.storageLock.writeLock().lock();
try {
partition.remove(key, region);
partition.add(key, replace);
return true;
} finally {
partition.storageLock.readLock().lock();
partition.storageLock.writeLock().unlock();
}
}
} finally {
partition.storageLock.readLock().unlock();
}
}
public final LocalCacheElement replace(Key key, LocalCacheElement replace) {
Partition partition = pickPartition(key);
partition.storageLock.readLock().lock();
try {
Region region = partition.find(key);
// not there? that's a fail
if (region == null) return null;
// there,
LocalCacheElement el = null;
el = region.toValue();
partition.storageLock.readLock().unlock();
partition.storageLock.writeLock().lock();
try {
partition.remove(key, region);
partition.add(key, replace);
return el;
} finally {
partition.storageLock.readLock().lock();
partition.storageLock.writeLock().unlock();
}
} finally {
partition.storageLock.readLock().unlock();
}
}
public final int size() {
return numberItems;
}
public final boolean isEmpty() {
return numberItems == 0;
}
public final boolean containsKey(Object okey) {
if (!(okey instanceof Key)) return false;
Key key = (Key) okey;
Partition partition = pickPartition(key);
try {
partition.storageLock.readLock().lock();
return partition.has(key);
} finally {
partition.storageLock.readLock().unlock();
}
}
public final boolean containsValue(Object o) {
throw new UnsupportedOperationException("operation not supported");
}
public final LocalCacheElement get(Object okey) {
if (!(okey instanceof Key)) return null;
Key key = (Key) okey;
Partition partition = pickPartition(key);
try {
partition.storageLock.readLock().lock();
Region region = partition.find(key);
if (region == null) return null;
return region.toValue();
} finally {
partition.storageLock.readLock().unlock();
}
}
public final LocalCacheElement put(final Key key, final LocalCacheElement item) {
Partition partition = pickPartition(key);
partition.storageLock.readLock().lock();
try {
Region region = partition.find(key);
partition.storageLock.readLock().unlock();
partition.storageLock.writeLock().lock();
try {
LocalCacheElement old = null;
if (region != null) {
old = region.toValue();
}
if (region != null) partition.remove(key, region);
partition.add(key, item);
numberItems++;
return old;
} finally {
partition.storageLock.readLock().lock();
partition.storageLock.writeLock().unlock();
}
} finally {
partition.storageLock.readLock().unlock();
}
}
public final LocalCacheElement remove(Object okey) {
if (!(okey instanceof Key)) return null;
Key key = (Key) okey;
Partition partition = pickPartition(key);
try {
partition.storageLock.readLock().lock();
Region region = partition.find(key);
if (region == null) return null;
else {
partition.storageLock.readLock().unlock();
partition.storageLock.writeLock().lock();
try {
LocalCacheElement old = null;
old = region.toValue();
partition.blockStore.free(region);
partition.remove(key, region);
numberItems--;
return old;
} finally {
partition.storageLock.readLock().lock();
partition.storageLock.writeLock().unlock();
}
}
} finally {
partition.storageLock.readLock().unlock();
}
}
public final void putAll(Map<? extends Key, ? extends LocalCacheElement> map) {
// absent, lock the store and put the new value in
for (Entry<? extends Key, ? extends LocalCacheElement> entry : map.entrySet()) {
Key key = entry.getKey();
LocalCacheElement item;
item = entry.getValue();
put(key, item);
}
}
public final void clear() {
for (Partition partition : partitions) {
partition.storageLock.writeLock().lock();
numberItems += partition.keys().size() * - 1;
try {
partition.clear();
} finally {
partition.storageLock.writeLock().unlock();
}
}
}
public Set<Key> keySet() {
Set<Key> keys = new HashSet<Key>();
for (Partition partition : partitions) {
keys.addAll(partition.keys());
}
return keys;
}
public Collection<LocalCacheElement> values() {
throw new UnsupportedOperationException("operation not supported");
}
public Set<Entry<Key, LocalCacheElement>> entrySet() {
throw new UnsupportedOperationException("operation not supported");
}
protected static int hash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
}
| Java |
package com.thimbleware.jmemcached.storage.bytebuffer;
import com.thimbleware.jmemcached.util.OpenBitSet;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.io.IOException;
/**
* Memory mapped block storage mechanism with a free-list maintained by TreeMap
*
* Allows memory for storage to be mapped outside of the VM's main memory, and outside the purvey
* of the GC.
*
* Should offer O(Log(N)) search and free of blocks.
*/
public class ByteBufferBlockStore {
protected ChannelBuffer storageBuffer;
private long freeBytes;
private long storeSizeBytes;
private final int blockSizeBytes;
private OpenBitSet allocated;
private static final ByteBufferBlockStoreFactory BYTE_BUFFER_BLOCK_STORE_FACTORY = new ByteBufferBlockStoreFactory();
/**
* Exception thrown on inability to allocate a new block
*/
public static class BadAllocationException extends RuntimeException {
public BadAllocationException(String s) {
super(s);
}
}
public static BlockStoreFactory getFactory() {
return BYTE_BUFFER_BLOCK_STORE_FACTORY;
}
public static class ByteBufferBlockStoreFactory implements BlockStoreFactory<ByteBufferBlockStore> {
public ByteBufferBlockStore manufacture(long sizeBytes, int blockSizeBytes) {
try {
ChannelBuffer buffer = ChannelBuffers.buffer((int) sizeBytes);
return new ByteBufferBlockStore(buffer, sizeBytes, blockSizeBytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* Construct a new memory mapped block storage against a filename, with a certain size
* and block size.
* @param storageBuffer
* @param blockSizeBytes the size of a block in the store
* @throws java.io.IOException thrown on failure to open the store or map the file
*/
private ByteBufferBlockStore(ChannelBuffer storageBuffer, long sizeBytes, int blockSizeBytes) throws IOException {
this.storageBuffer = storageBuffer;
this.blockSizeBytes = blockSizeBytes;
initialize((int)sizeBytes);
}
/**
* Constructor used only be subclasses, allowing them to provide their own buffer.
*/
protected ByteBufferBlockStore(int blockSizeBytes) {
this.blockSizeBytes = blockSizeBytes;
}
protected void initialize(int storeSizeBytes) {
// set the size of the store in bytes
this.storeSizeBytes = storageBuffer.capacity();
// the number of free bytes starts out as the entire store
freeBytes = storeSizeBytes;
// clear the buffer
storageBuffer.clear();
allocated = new OpenBitSet(storeSizeBytes / blockSizeBytes);
clear();
}
/**
* Rounds up a requested size to the nearest block width.
* @param size the requested size
* @param blockSize the block size to use
* @return the actual mount to use
*/
public static long roundUp( long size, long blockSize ) {
return size - 1L + blockSize - (size - 1L) % blockSize;
}
/**
* Close the store, destroying all data and closing the backing file
* @throws java.io.IOException thrown on failure to close file
*/
public void close() throws IOException {
// clear the region list
clear();
//
freeResources();
// null out the storage to allow the GC to get rid of it
storageBuffer = null;
}
protected void freeResources() throws IOException {
// noop
}
private int markPos(int numBlocks) {
int mark = allocated.mark(numBlocks);
if (mark == -1) throw new BadAllocationException("unable to allocate room; all blocks consumed");
return mark;
}
private void clear(int start, int numBlocks) {
allocated.clear(start, start + numBlocks);
}
/**
* Allocate a region in the block storage
*
* @param desiredSize size (in bytes) desired for the region
* @param expiry expiry time in ms since epoch
*@param timestamp allocation timestamp of the entry
* @return the region descriptor
*/
public Region alloc(int desiredSize, long expiry, long timestamp) {
final long desiredBlockSize = roundUp(desiredSize, blockSizeBytes);
int numBlocks = (int) (desiredBlockSize / blockSizeBytes);
int pos = markPos(numBlocks);
freeBytes -= desiredBlockSize;
// get the buffer to it
int position = pos * blockSizeBytes;
ChannelBuffer slice = storageBuffer.slice(position, desiredSize);
slice.writerIndex(0);
slice.readerIndex(0);
return new Region(desiredSize, numBlocks, pos, slice, expiry, timestamp);
}
public ChannelBuffer get(int startBlock, int size) {
return storageBuffer.slice(startBlock * blockSizeBytes, size);
}
public void free(Region region) {
freeBytes += (region.usedBlocks * blockSizeBytes);
region.valid = false;
region.slice = null;
int pos = region.startBlock;
clear(pos, region.size / blockSizeBytes);
}
public void clear()
{
// say goodbye to the region list
allocated = new OpenBitSet(allocated.size());
// reset the # of free bytes back to the max size
freeBytes = storeSizeBytes;
}
public long getStoreSizeBytes() {
return storeSizeBytes;
}
public int getBlockSizeBytes() {
return blockSizeBytes;
}
public long getFreeBytes() {
return freeBytes;
}
} | Java |
package com.thimbleware.jmemcached.storage;
import com.thimbleware.jmemcached.storage.hash.SizedItem;
import java.io.IOException;
import java.util.concurrent.ConcurrentMap;
/**
* The interface for cache storage. Essentially a concurrent map but with methods for investigating the heap
* state of the storage unit and with additional support for explicit resource-cleanup (close()).
*/
public interface CacheStorage<K, V extends SizedItem> extends ConcurrentMap<K, V> {
/**
* @return the capacity (in bytes) of the storage
*/
long getMemoryCapacity();
/**
* @return the current usage (in bytes) of the storage
*/
long getMemoryUsed();
/**
* @return the capacity (in # of items) of the storage
*/
int capacity();
/**
* Close the storage unit, deallocating any resources it might be currently holding.
* @throws java.io.IOException thrown if IO faults occur anywhere during close.
*/
void close() throws IOException;
}
| Java |
package com.thimbleware.jmemcached.storage.hash;
/*
* Copyright 2009 Benjamin Manes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.thimbleware.jmemcached.storage.CacheStorage;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A {@link ConcurrentMap} with a doubly-linked list running through its entries.
* <p/>
* This class provides the same semantics as a {@link ConcurrentHashMap} in terms of
* iterators, acceptable keys, and concurrency characteristics, but perform slightly
* worse due to the added expense of maintaining the linked list. It differs from
* {@link java.util.LinkedHashMap} in that it does not provide predictable iteration
* order.
* <p/>
* This map is intended to be used for caches and provides the following eviction policies:
* <ul>
* <li> First-in, First-out: Also known as insertion order. This policy has excellent
* concurrency characteristics and an adequate hit rate.
* <li> Second-chance: An enhanced FIFO policy that marks entries that have been retrieved
* and saves them from being evicted until the next pass. This enhances the FIFO policy
* by making it aware of "hot" entries, which increases its hit rate to be equal to an
* LRU's under normal workloads. In the worst case, where all entries have been saved,
* this policy degrades to a FIFO.
* <li> Least Recently Used: An eviction policy based on the observation that entries that
* have been used recently will likely be used again soon. This policy provides a good
* approximation of an optimal algorithm, but suffers by being expensive to maintain.
* The cost of reordering entries on the list during every access operation reduces
* the concurrency and performance characteristics of this policy.
* </ul>
*
* @author <a href="mailto:ben.manes@reardencommerce.com">Ben Manes</a>
* @see http://code.google.com/p/concurrentlinkedhashmap/
*/
public final class ConcurrentLinkedHashMap<K, V extends SizedItem> extends AbstractMap<K, V> implements Serializable, CacheStorage<K, V> {
private static final EvictionListener<?, ?> nullListener = new EvictionListener<Object, Object>() {
public void onEviction(Object key, Object value) {
}
};
private static final long serialVersionUID = 8350170357874293408L;
final ConcurrentMap<K, Node<K, V>> data;
final EvictionListener<K, V> listener;
final AtomicInteger capacity;
final EvictionPolicy policy;
final AtomicInteger length;
final Node<K, V> sentinel;
final Lock lock;
final AtomicLong memoryCapacity;
final AtomicLong memoryUsed;
/**
* Creates a map with the specified eviction policy, maximum capacity, and at the default concurrency level.
*
* @param policy The eviction policy to apply when the size exceeds the maximum capacity.
* @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily.
*/
@SuppressWarnings("unchecked")
public static <K, V extends SizedItem> ConcurrentLinkedHashMap<K, V> create(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity) {
return create(policy, maximumCapacity, maximumMemoryCapacity, 16, (EvictionListener<K, V>) nullListener);
}
/**
* Creates a map with the specified eviction policy, maximum capacity, eviction listener, and at the
* default concurrency level.
*
* @param policy The eviction policy to apply when the size exceeds the maximum capacity.
* @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily.
* @param listener The listener registered for notification when an entry is evicted.
*/
public static <K, V extends SizedItem> ConcurrentLinkedHashMap<K, V> create(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity,
EvictionListener<K, V> listener) {
return create(policy, maximumCapacity, maximumMemoryCapacity, 16, listener);
}
/**
* Creates a map with the specified eviction policy, maximum capacity, and concurrency level.
*
* @param policy The eviction policy to apply when the size exceeds the maximum capacity.
* @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily.
* @param concurrencyLevel The estimated number of concurrently updating threads. The implementation
* performs internal sizing to try to accommodate this many threads.
*/
@SuppressWarnings("unchecked")
public static <K, V extends SizedItem> ConcurrentLinkedHashMap<K, V> create(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity,
int concurrencyLevel) {
return create(policy, maximumCapacity, maximumMemoryCapacity, concurrencyLevel, (EvictionListener<K, V>) nullListener);
}
/**
* Creates a map with the specified eviction policy, maximum capacity, eviction listener, and concurrency level.
*
* @param policy The eviction policy to apply when the size exceeds the maximum capacity.
* @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily.
* @param concurrencyLevel The estimated number of concurrently updating threads. The implementation
* performs internal sizing to try to accommodate this many threads.
* @param listener The listener registered for notification when an entry is evicted.
*/
public static <K, V extends SizedItem> ConcurrentLinkedHashMap<K, V> create(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity,
int concurrencyLevel, EvictionListener<K, V> listener) {
return new ConcurrentLinkedHashMap<K, V>(policy, maximumCapacity, maximumMemoryCapacity, concurrencyLevel, listener);
}
/**
* Creates a map with the specified eviction policy, maximum capacity, eviction listener, and concurrency level.
*
* @param policy The eviction policy to apply when the size exceeds the maximum capacity.
* @param maximumCapacity The maximum capacity to coerces to. The size may exceed it temporarily.
* @param concurrencyLevel The estimated number of concurrently updating threads. The implementation
* performs internal sizing to try to accommodate this many threads.
* @param listener The listener registered for notification when an entry is evicted.
*/
private ConcurrentLinkedHashMap(EvictionPolicy policy, int maximumCapacity, long maximumMemoryCapacity,
int concurrencyLevel, EvictionListener<K, V> listener) {
if ((policy == null) || (maximumCapacity < 0) || (concurrencyLevel <= 0) || (listener == null)) {
throw new IllegalArgumentException();
}
this.data = new ConcurrentHashMap<K, Node<K, V>>(maximumCapacity, 0.75f, concurrencyLevel);
this.capacity = new AtomicInteger(maximumCapacity);
this.length = new AtomicInteger();
this.listener = listener;
this.policy = policy;
this.lock = new ReentrantLock();
this.sentinel = new Node<K, V>(lock);
this.memoryUsed = new AtomicLong(0);
this.memoryCapacity = new AtomicLong(maximumMemoryCapacity);
}
/**
* Determines whether the map has exceeded its capacity.
*
* @return Whether the map has overflowed and an entry should be evicted.
*/
private boolean isOverflow() {
return size() > capacity() || getMemoryUsed() > getMemoryCapacity();
}
public long getMemoryCapacity() {
return memoryCapacity.get();
}
public long getMemoryUsed() {
return memoryUsed.get();
}
/**
* Sets the maximum capacity of the map and eagerly evicts entries until it shrinks to the appropriate size.
*
* @param capacity The maximum capacity of the map.
*/
public void setCapacity(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException();
}
this.capacity.set(capacity);
while (evict()) {
}
}
/**
* Sets the maximum capacity of the map and eagerly evicts entries until it shrinks to the appropriate size.
*
* @param capacity The maximum capacity of the map.
*/
public void setMemoryCapacity(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException();
}
this.memoryCapacity.set(capacity);
while (evict()) {
}
}
/**
* Retrieves the maximum capacity of the map.
*
* @return The maximum capacity.
*/
public int capacity() {
return capacity.get();
}
public void close() {
clear();
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
int size = length.get();
return (size >= 0) ? size : 0;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
for (K key : keySet()) {
remove(key);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsKey(Object key) {
return data.containsKey(key);
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsValue(Object value) {
if (value == null) {
throw new IllegalArgumentException();
}
return data.containsValue(new Node<Object, Object>(null, value, null, lock));
}
/**
* Evicts a single entry if the map exceeds the maximum capacity.
*/
private boolean evict() {
while (isOverflow()) {
Node<K, V> node = sentinel.getNext();
if (node == sentinel) {
return false;
} else if (policy.onEvict(this, node)) {
// Attempt to remove the node if it's still available
if (data.remove(node.getKey(), new Identity(node))) {
length.decrementAndGet();
memoryUsed.addAndGet(-1 * node.getValue().size());
node.remove();
listener.onEviction(node.getKey(), node.getValue());
return true;
}
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public V get(Object key) {
Node<K, V> node = data.get(key);
if (node != null) {
policy.onAccess(this, node);
return node.getValue();
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public V put(K key, V value) {
if (value == null) {
throw new IllegalArgumentException();
}
Node<K, V> old = putIfAbsent(new Node<K, V>(key, value, sentinel, lock));
memoryUsed.addAndGet(value.size());
if (old == null) {
return null;
}
else {
memoryUsed.addAndGet(-1 * old.getValue().size());
return old.getAndSetValue(value);
}
}
/**
* {@inheritDoc}
*/
public V putIfAbsent(K key, V value) {
if (value == null) {
throw new IllegalArgumentException();
}
Node<K, V> old = putIfAbsent(new Node<K, V>(key, value, sentinel, lock));
if (old == null) {
memoryUsed.addAndGet(value.size());
return null;
}
else return old.getValue();
}
/**
* Adds a node to the list and data store if it does not already exist.
*
* @param node An unlinked node to add.
* @return The previous value in the data store.
*/
private Node<K, V> putIfAbsent(Node<K, V> node) {
Node<K, V> old = data.putIfAbsent(node.getKey(), node);
if (old == null) {
length.incrementAndGet();
node.appendToTail();
evict();
} else {
policy.onAccess(this, old);
}
return old;
}
/**
* {@inheritDoc}
*/
@Override
public V remove(Object key) {
Node<K, V> node = data.remove(key);
if (node == null) {
return null;
}
length.decrementAndGet();
memoryUsed.addAndGet(-1 * node.getValue().size());
node.remove();
return node.getValue();
}
/**
* {@inheritDoc}
*/
public boolean remove(Object key, Object value) {
Node<K, V> node = data.get(key);
if ((node != null) && node.value.equals(value) && data.remove(key, new Identity(node))) {
length.decrementAndGet();
memoryUsed.addAndGet(-1 * node.getValue().size());
node.remove();
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public V replace(K key, V value) {
if (value == null) {
throw new IllegalArgumentException();
}
Node<K, V> node = data.get(key);
if (node == null) return null;
else {
memoryUsed.addAndGet(-1 * node.getValue().size());
memoryUsed.addAndGet(value.size());
return node.getAndSetValue(value);
}
}
/**
* {@inheritDoc}
*/
public boolean replace(K key, V oldValue, V newValue) {
if (newValue == null) {
throw new IllegalArgumentException();
}
Node<K, V> node = data.get(key);
if (node == null) return false;
else {
final boolean val = node.casValue(oldValue, newValue);
if (val) {
memoryUsed.addAndGet(-1 * oldValue.size());
memoryUsed.addAndGet(newValue.size());
}
return val;
}
}
/**
* {@inheritDoc}
*/
@Override
public Set<K> keySet() {
return new KeySet();
}
/**
* {@inheritDoc}
*/
@Override
public Collection<V> values() {
return new Values();
}
/**
* {@inheritDoc}
*/
@Override
public Set<Entry<K, V>> entrySet() {
return new EntrySet();
}
/**
* A listener registered for notification when an entry is evicted.
*/
public interface EvictionListener<K, V> {
/**
* A call-back notification that the entry was evicted.
*
* @param key The evicted key.
* @param value The evicted value.
*/
void onEviction(K key, V value);
}
/**
* The replacement policy to apply to determine which entry to discard when the capacity has been reached.
*/
public enum EvictionPolicy {
/**
* Evicts entries based on insertion order.
*/
FIFO() {
@Override
<K, V extends SizedItem> void onAccess(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) {
// do nothing
}
@Override
<K, V extends SizedItem> boolean onEvict(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) {
return true;
}
},
/**
* Evicts entries based on insertion order, but gives an entry a "second chance" if it has been requested recently.
*/
SECOND_CHANCE() {
@Override
<K, V extends SizedItem> void onAccess(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) {
node.setMarked(true);
}
@Override
<K, V extends SizedItem> boolean onEvict(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) {
if (node.isMarked()) {
node.moveToTail();
node.setMarked(false);
return false;
}
return true;
}
},
/**
* Evicts entries based on how recently they are used, with the least recent evicted first.
*/
LRU() {
@Override
<K, V extends SizedItem> void onAccess(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) {
node.moveToTail();
}
@Override
<K, V extends SizedItem> boolean onEvict(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node) {
return true;
}
};
/**
* Performs any operations required by the policy after a node was successfully retrieved.
*/
abstract <K, V extends SizedItem> void onAccess(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node);
/**
* Determines whether to evict the node at the head of the list.
*/
abstract <K, V extends SizedItem> boolean onEvict(ConcurrentLinkedHashMap<K, V> map, Node<K, V> node);
}
/**
* A node on the double-linked list. This list cross-cuts the data store.
*/
@SuppressWarnings("unchecked")
protected static final class Node<K, V> implements Serializable {
private static final long serialVersionUID = 1461281468985304519L;
private static final AtomicReferenceFieldUpdater<Node, Object> valueUpdater =
AtomicReferenceFieldUpdater.newUpdater(Node.class, Object.class, "value");
private static final Node UNLINKED = new Node(null);
private final K key;
private final Lock lock;
private final Node<K, V> sentinel;
private volatile V value;
private volatile boolean marked;
private volatile Node<K, V> prev;
private volatile Node<K, V> next;
/**
* Creates a new sentinel node.
*/
public Node(Lock lock) {
this.sentinel = this;
this.value = null;
this.lock = lock;
this.prev = this;
this.next = this;
this.key = null;
}
/**
* Creates a new, unlinked node.
*/
public Node(K key, V value, Node<K, V> sentinel, Lock lock) {
this.sentinel = sentinel;
this.next = UNLINKED;
this.prev = UNLINKED;
this.value = value;
this.lock = lock;
this.key = key;
}
/**
* Appends the node to the tail of the list.
*/
public void appendToTail() {
lock.lock();
try {
// Allow moveToTail() to no-op or removal to spin-wait
next = sentinel;
// Read the tail on the stack to avoid unnecessary volatile reads
final Node<K, V> tail = sentinel.prev;
sentinel.prev = this;
tail.next = this;
prev = tail;
} finally {
lock.unlock();
}
}
/**
* Removes the node from the list.
* <p/>
* If the node has not yet been appended to the tail it will wait for that operation to complete.
*/
public void remove() {
for (; ;) {
if (isUnlinked()) {
continue; // await appending
}
lock.lock();
try {
if (isUnlinked()) {
continue; // await appending
}
prev.next = next;
next.prev = prev;
next = UNLINKED; // mark as unlinked
} finally {
lock.unlock();
}
return;
}
}
/**
* Moves the node to the tail.
* <p/>
* If the node has been unlinked or is already at the tail, no-ops.
*/
public void moveToTail() {
if (isTail() || isUnlinked()) {
return;
}
lock.lock();
try {
if (isTail() || isUnlinked()) {
return;
}
// unlink
prev.next = next;
next.prev = prev;
// link
next = sentinel; // ordered for isAtTail()
prev = sentinel.prev;
sentinel.prev = this;
prev.next = this;
} finally {
lock.unlock();
}
}
/**
* Checks whether the node is linked on the list chain.
*
* @return Whether the node has not yet been linked on the list.
*/
public boolean isUnlinked() {
return (next == UNLINKED);
}
/**
* Checks whether the node is the last linked on the list chain.
*
* @return Whether the node is at the tail of the list.
*/
public boolean isTail() {
return (next == sentinel);
}
/*
* Key operators
*/
public K getKey() {
return key;
}
/*
* Value operators
*/
public V getValue() {
return (V) valueUpdater.get(this);
}
public V getAndSetValue(V value) {
return (V) valueUpdater.getAndSet(this, value);
}
public boolean casValue(V expect, V update) {
return valueUpdater.compareAndSet(this, expect, update);
}
/*
* Previous node operators
*/
public Node<K, V> getPrev() {
return prev;
}
/*
* Next node operators
*/
public Node<K, V> getNext() {
return next;
}
/*
* Access frequency operators
*/
public boolean isMarked() {
return marked;
}
public void setMarked(boolean marked) {
this.marked = marked;
}
/**
* Only ensures that the values are equal, as the key may be <tt>null</tt> for look-ups.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof Node)) {
return false;
}
V value = getValue();
Node<?, ?> node = (Node<?, ?>) obj;
return (value == null) ? (node.getValue() == null) : value.equals(node.getValue());
}
@Override
public int hashCode() {
return ((key == null) ? 0 : key.hashCode()) ^
((value == null) ? 0 : value.hashCode());
}
@Override
public String toString() {
lock.lock();
try {
return String.format("key=%s - prev=%s ; next=%s", valueOf(key), valueOf(prev.key), valueOf(next.key));
} finally {
lock.unlock();
}
}
private String valueOf(K key) {
return (key == null) ? "sentinel" : key.toString();
}
}
/**
* Allows {@link #equals(Object)} to compare using object identity.
*/
private static final class Identity {
private final Object delegate;
public Identity(Object delegate) {
this.delegate = delegate;
}
@Override
public boolean equals(Object o) {
return (o == delegate);
}
}
/**
* An adapter to safely externalize the keys.
*/
private final class KeySet extends AbstractSet<K> {
private final ConcurrentLinkedHashMap<K, V> map = ConcurrentLinkedHashMap.this;
@Override
public int size() {
return map.size();
}
@Override
public void clear() {
map.clear();
}
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public boolean contains(Object obj) {
return map.containsKey(obj);
}
@Override
public boolean remove(Object obj) {
return (map.remove(obj) != null);
}
@Override
public Object[] toArray() {
return map.data.keySet().toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return map.data.keySet().toArray(array);
}
}
/**
* An adapter to safely externalize the keys.
*/
private final class KeyIterator implements Iterator<K> {
private final EntryIterator iterator = new EntryIterator(ConcurrentLinkedHashMap.this.data.values().iterator());
public boolean hasNext() {
return iterator.hasNext();
}
public K next() {
return iterator.next().getKey();
}
public void remove() {
iterator.remove();
}
}
/**
* An adapter to represent the data store's values in the external type.
*/
private final class Values extends AbstractCollection<V> {
private final ConcurrentLinkedHashMap<K, V> map = ConcurrentLinkedHashMap.this;
@Override
public int size() {
return map.size();
}
@Override
public void clear() {
map.clear();
}
@Override
public Iterator<V> iterator() {
return new ValueIterator();
}
@Override
public boolean contains(Object o) {
return map.containsValue(o);
}
@Override
public Object[] toArray() {
Collection<V> values = new ArrayList<V>(size());
for (V value : this) {
values.add(value);
}
return values.toArray();
}
@Override
public <T> T[] toArray(T[] array) {
Collection<V> values = new ArrayList<V>(size());
for (V value : this) {
values.add(value);
}
return values.toArray(array);
}
}
/**
* An adapter to represent the data store's values in the external type.
*/
private final class ValueIterator implements Iterator<V> {
private final EntryIterator iterator = new EntryIterator(ConcurrentLinkedHashMap.this.data.values().iterator());
public boolean hasNext() {
return iterator.hasNext();
}
public V next() {
return iterator.next().getValue();
}
public void remove() {
iterator.remove();
}
}
/**
* An adapter to represent the data store's entry set in the external type.
*/
private final class EntrySet extends AbstractSet<Entry<K, V>> {
private final ConcurrentLinkedHashMap<K, V> map = ConcurrentLinkedHashMap.this;
@Override
public int size() {
return map.size();
}
@Override
public void clear() {
map.clear();
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator(map.data.values().iterator());
}
@Override
public boolean contains(Object obj) {
if (!(obj instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) obj;
Node<K, V> node = map.data.get(entry.getKey());
return (node != null) && (node.value.equals(entry.getValue()));
}
@Override
public boolean add(Entry<K, V> entry) {
return (map.putIfAbsent(entry.getKey(), entry.getValue()) == null);
}
@Override
public boolean remove(Object obj) {
if (!(obj instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) obj;
return map.remove(entry.getKey(), entry.getValue());
}
@Override
public Object[] toArray() {
Collection<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(size());
for (Entry<K, V> entry : this) {
entries.add(new SimpleEntry<K, V>(entry));
}
return entries.toArray();
}
@Override
public <T> T[] toArray(T[] array) {
Collection<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(size());
for (Entry<K, V> entry : this) {
entries.add(new SimpleEntry<K, V>(entry));
}
return entries.toArray(array);
}
}
/**
* An adapter to represent the data store's entry iterator in the external type.
*/
private final class EntryIterator implements Iterator<Entry<K, V>> {
private final Iterator<Node<K, V>> iterator;
private Entry<K, V> current;
public EntryIterator(Iterator<Node<K, V>> iterator) {
this.iterator = iterator;
}
public boolean hasNext() {
return iterator.hasNext();
}
public Entry<K, V> next() {
current = new NodeEntry(iterator.next());
return current;
}
public void remove() {
if (current == null) {
throw new IllegalStateException();
}
ConcurrentLinkedHashMap.this.remove(current.getKey(), current.getValue());
current = null;
}
}
/**
* An entry that is tied to the map instance to allow updates through the entry or the map to be visible.
*/
private final class NodeEntry implements Entry<K, V> {
private final ConcurrentLinkedHashMap<K, V> map = ConcurrentLinkedHashMap.this;
private final Node<K, V> node;
public NodeEntry(Node<K, V> node) {
this.node = node;
}
public K getKey() {
return node.getKey();
}
public V getValue() {
if (node.isUnlinked()) {
V value = map.get(getKey());
if (value != null) {
return value;
}
}
return node.getValue();
}
public V setValue(V value) {
return map.replace(getKey(), value);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) obj;
return eq(getKey(), entry.getKey()) && eq(getValue(), entry.getValue());
}
@Override
public int hashCode() {
K key = getKey();
V value = getValue();
return ((key == null) ? 0 : key.hashCode()) ^
((value == null) ? 0 : value.hashCode());
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
private boolean eq(Object o1, Object o2) {
return (o1 == null) ? (o2 == null) : o1.equals(o2);
}
}
/**
* This duplicates {@link java.util.AbstractMap.SimpleEntry} until the class is made accessible (public in JDK-6).
*/
private static class SimpleEntry<K, V> implements Entry<K, V> {
private final K key;
private V value;
public SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
public SimpleEntry(Entry<K, V> e) {
this.key = e.getKey();
this.value = e.getValue();
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) obj;
return eq(key, entry.getKey()) && eq(value, entry.getValue());
}
@Override
public int hashCode() {
return ((key == null) ? 0 : key.hashCode()) ^
((value == null) ? 0 : value.hashCode());
}
@Override
public String toString() {
return key + "=" + value;
}
private static boolean eq(Object o1, Object o2) {
return (o1 == null) ? (o2 == null) : o1.equals(o2);
}
}
}
| Java |
package com.thimbleware.jmemcached.storage.hash;
/**
*/
public interface SizedItem {
int size();
}
| Java |
/**
* Copyright 2008 ThimbleWare Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached;
import com.thimbleware.jmemcached.util.BufferUtils;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
/**
* Represents information about a cache entry.
*/
public final class LocalCacheElement implements CacheElement {
private long expire ;
private int flags;
private ChannelBuffer data;
private Key key;
private long casUnique = 0L;
private boolean blocked = false;
private long blockedUntil;
public LocalCacheElement() {
}
public LocalCacheElement(Key key) {
this.key = key;
}
public LocalCacheElement(Key key, int flags, long expire, long casUnique) {
this.key = key;
this.flags = flags;
this.expire = expire;
this.casUnique = casUnique;
}
/**
* @return the current time in seconds
*/
public static int Now() {
return (int) (System.currentTimeMillis() / 1000);
}
public int size() {
return getData().capacity();
}
public LocalCacheElement append(LocalCacheElement appendElement) {
int newLength = size() + appendElement.size();
LocalCacheElement appendedElement = new LocalCacheElement(getKey(), getFlags(), getExpire(), 0L);
ChannelBuffer appended = ChannelBuffers.buffer(newLength);
ChannelBuffer existing = getData();
ChannelBuffer append = appendElement.getData();
appended.writeBytes(existing);
appended.writeBytes(append);
appended.readerIndex(0);
existing.readerIndex(0);
append.readerIndex(0);
appendedElement.setData(appended);
appendedElement.setCasUnique(appendedElement.getCasUnique() + 1);
return appendedElement;
}
public LocalCacheElement prepend(LocalCacheElement prependElement) {
int newLength = size() + prependElement.size();
LocalCacheElement prependedElement = new LocalCacheElement(getKey(), getFlags(), getExpire(), 0L);
ChannelBuffer prepended = ChannelBuffers.buffer(newLength);
ChannelBuffer prepend = prependElement.getData();
ChannelBuffer existing = getData();
prepended.writeBytes(prepend);
prepended.writeBytes(existing);
existing.readerIndex(0);
prepend.readerIndex(0);
prepended.readerIndex(0);
prependedElement.setData(prepended);
prependedElement.setCasUnique(prependedElement.getCasUnique() + 1);
return prependedElement;
}
public static class IncrDecrResult {
int oldValue;
LocalCacheElement replace;
public IncrDecrResult(int oldValue, LocalCacheElement replace) {
this.oldValue = oldValue;
this.replace = replace;
}
}
public IncrDecrResult add(int mod) {
// TODO handle parse failure!
int modVal = BufferUtils.atoi(getData()) + mod; // change value
if (modVal < 0) {
modVal = 0;
} // check for underflow
ChannelBuffer newData = BufferUtils.itoa(modVal);
LocalCacheElement replace = new LocalCacheElement(getKey(), getFlags(), getExpire(), 0L);
replace.setData(newData);
replace.setCasUnique(replace.getCasUnique() + 1);
return new IncrDecrResult(modVal, replace);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LocalCacheElement that = (LocalCacheElement) o;
if (blocked != that.blocked) return false;
if (blockedUntil != that.blockedUntil) return false;
if (casUnique != that.casUnique) return false;
if (expire != that.expire) return false;
if (flags != that.flags) return false;
if (data != null ? !data.equals(that.data) : that.data != null) return false;
if (key != null ? !key.equals(that.key) : that.key != null) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (expire ^ (expire >>> 32));
result = 31 * result + flags;
result = 31 * result + (data != null ? data.hashCode() : 0);
result = 31 * result + (key != null ? key.hashCode() : 0);
result = 31 * result + (int) (casUnique ^ (casUnique >>> 32));
result = 31 * result + (blocked ? 1 : 0);
result = 31 * result + (int) (blockedUntil ^ (blockedUntil >>> 32));
return result;
}
public static LocalCacheElement key(Key key) {
return new LocalCacheElement(key);
}
public long getExpire() {
return expire;
}
public int getFlags() {
return flags;
}
public ChannelBuffer getData() {
data.readerIndex(0);
return data;
}
public Key getKey() {
return key;
}
public long getCasUnique() {
return casUnique;
}
public boolean isBlocked() {
return blocked;
}
public long getBlockedUntil() {
return blockedUntil;
}
public void setCasUnique(long casUnique) {
this.casUnique = casUnique;
}
public void block(long blockedUntil) {
this.blocked = true;
this.blockedUntil = blockedUntil;
}
public void setData(ChannelBuffer data) {
data.readerIndex(0);
this.data = data;
}
public static LocalCacheElement readFromBuffer(ChannelBuffer in) {
int bufferSize = in.readInt();
long expiry = in.readLong();
int keyLength = in.readInt();
ChannelBuffer key = in.slice(in.readerIndex(), keyLength);
in.skipBytes(keyLength);
LocalCacheElement localCacheElement = new LocalCacheElement(new Key(key));
localCacheElement.expire = expiry;
localCacheElement.flags = in.readInt();
int dataLength = in.readInt();
localCacheElement.data = in.slice(in.readerIndex(), dataLength);
in.skipBytes(dataLength);
localCacheElement.casUnique = in.readInt();
localCacheElement.blocked = in.readByte() == 1;
localCacheElement.blockedUntil = in.readLong();
return localCacheElement;
}
public int bufferSize() {
return 4 + 8 + 4 + key.bytes.capacity() + 4 + 4 + 4 + data.capacity() + 8 + 1 + 8;
}
public void writeToBuffer(ChannelBuffer out) {
out.writeInt(bufferSize());
out.writeLong(expire) ;
out.writeInt(key.bytes.capacity());
out.writeBytes(key.bytes);
out.writeInt(flags);
out.writeInt(data.capacity());
out.writeBytes(data);
out.writeLong(casUnique);
out.writeByte(blocked ? 1 : 0);
out.writeLong(blockedUntil);
}
} | Java |
package com.thimbleware.jmemcached;
import java.io.IOException;
import java.util.Set;
import java.util.Map;
/**
*/
public interface Cache<CACHE_ELEMENT extends CacheElement> {
/**
* Enum defining response statuses from set/add type commands
*/
public enum StoreResponse {
STORED, NOT_STORED, EXISTS, NOT_FOUND
}
/**
* Enum defining responses statuses from removal commands
*/
public enum DeleteResponse {
DELETED, NOT_FOUND
}
/**
* Handle the deletion of an item from the cache.
*
* @param key the key for the item
* @param time an amount of time to block this entry in the cache for further writes
* @return the message response
*/
DeleteResponse delete(Key key, int time);
/**
* Add an element to the cache
*
* @param e the element to add
* @return the store response code
*/
StoreResponse add(CACHE_ELEMENT e);
/**
* Replace an element in the cache
*
* @param e the element to replace
* @return the store response code
*/
StoreResponse replace(CACHE_ELEMENT e);
/**
* Append bytes to the end of an element in the cache
*
* @param element the element to append
* @return the store response code
*/
StoreResponse append(CACHE_ELEMENT element);
/**
* Prepend bytes to the end of an element in the cache
*
* @param element the element to append
* @return the store response code
*/
StoreResponse prepend(CACHE_ELEMENT element);
/**
* Set an element in the cache
*
* @param e the element to set
* @return the store response code
*/
StoreResponse set(CACHE_ELEMENT e);
/**
* Set an element in the cache but only if the element has not been touched
* since the last 'gets'
* @param cas_key the cas key returned by the last gets
* @param e the element to set
* @return the store response code
*/
StoreResponse cas(Long cas_key, CACHE_ELEMENT e);
/**
* Increment/decremen t an (integer) element in the cache
* @param key the key to increment
* @param mod the amount to add to the value
* @return the message response
*/
Integer get_add(Key key, int mod);
/**
* Get element(s) from the cache
* @param keys the key for the element to lookup
* @return the element, or 'null' in case of cache miss.
*/
CACHE_ELEMENT[] get(Key ... keys);
/**
* Flush all cache entries
* @return command response
*/
boolean flush_all();
/**
* Flush all cache entries with a timestamp after a given expiration time
* @param expire the flush time in seconds
* @return command response
*/
boolean flush_all(int expire);
/**
* Close the cache, freeing all resources on which it depends.
* @throws IOException
*/
void close() throws IOException;
/**
* @return the # of items in the cache
*/
long getCurrentItems();
/**
* @return the maximum size of the cache (in bytes)
*/
long getLimitMaxBytes();
/**
* @return the current cache usage (in bytes)
*/
long getCurrentBytes();
/**
* @return the number of get commands executed
*/
int getGetCmds();
/**
* @return the number of set commands executed
*/
int getSetCmds();
/**
* @return the number of get hits
*/
int getGetHits();
/**
* @return the number of stats
*/
int getGetMisses();
/**
* Retrieve stats about the cache. If an argument is specified, a specific category of stats is requested.
* @param arg a specific extended stat sub-category
* @return a map of stats
*/
Map<String, Set<String>> stat(String arg);
/**
* Called periodically by the network event loop to process any pending events.
* (such as delete queues, etc.)
*/
void asyncEventPing();
}
| Java |
/**
* Copyright 2008 ThimbleWare Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached;
import com.thimbleware.jmemcached.protocol.binary.MemcachedBinaryPipelineFactory;
import com.thimbleware.jmemcached.protocol.text.MemcachedPipelineFactory;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
/**
* The actual daemon - responsible for the binding and configuration of the network configuration.
*/
public class MemCacheDaemon<CACHE_ELEMENT extends CacheElement> {
final Logger log = LoggerFactory.getLogger(MemCacheDaemon.class);
public static String memcachedVersion = "0.9";
private int frameSize = 32768 * 1024;
private boolean binary = false;
private boolean verbose;
private int idleTime;
private InetSocketAddress addr;
private Cache<CACHE_ELEMENT> cache;
private boolean running = false;
private ServerSocketChannelFactory channelFactory;
private DefaultChannelGroup allChannels;
public MemCacheDaemon() {
}
public MemCacheDaemon(Cache<CACHE_ELEMENT> cache) {
this.cache = cache;
}
/**
* Bind the network connection and start the network processing threads.
*/
public void start() {
// TODO provide tweakable options here for passing in custom executors.
channelFactory =
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
allChannels = new DefaultChannelGroup("jmemcachedChannelGroup");
ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
ChannelPipelineFactory pipelineFactory;
if (binary)
pipelineFactory = createMemcachedBinaryPipelineFactory(cache, memcachedVersion, verbose, idleTime, allChannels);
else
pipelineFactory = createMemcachedPipelineFactory(cache, memcachedVersion, verbose, idleTime, frameSize, allChannels);
bootstrap.setPipelineFactory(pipelineFactory);
bootstrap.setOption("sendBufferSize", 65536 );
bootstrap.setOption("receiveBufferSize", 65536);
Channel serverChannel = bootstrap.bind(addr);
allChannels.add(serverChannel);
log.info("Listening on " + String.valueOf(addr.getHostName()) + ":" + addr.getPort());
running = true;
}
protected ChannelPipelineFactory createMemcachedBinaryPipelineFactory(
Cache cache, String memcachedVersion, boolean verbose, int idleTime, DefaultChannelGroup allChannels) {
return new MemcachedBinaryPipelineFactory(cache, memcachedVersion, verbose, idleTime, allChannels);
}
protected ChannelPipelineFactory createMemcachedPipelineFactory(
Cache cache, String memcachedVersion, boolean verbose, int idleTime, int receiveBufferSize, DefaultChannelGroup allChannels) {
return new MemcachedPipelineFactory(cache, memcachedVersion, verbose, idleTime, receiveBufferSize, allChannels);
}
public void stop() {
log.info("terminating daemon; closing all channels");
ChannelGroupFuture future = allChannels.close();
future.awaitUninterruptibly();
if (!future.isCompleteSuccess()) {
throw new RuntimeException("failure to complete closing all network channels");
}
log.info("channels closed, freeing cache storage");
try {
cache.close();
} catch (IOException e) {
throw new RuntimeException("exception while closing storage", e);
}
channelFactory.releaseExternalResources();
running = false;
log.info("successfully shut down");
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public void setIdleTime(int idleTime) {
this.idleTime = idleTime;
}
public void setAddr(InetSocketAddress addr) {
this.addr = addr;
}
public Cache<CACHE_ELEMENT> getCache() {
return cache;
}
public void setCache(Cache<CACHE_ELEMENT> cache) {
this.cache = cache;
}
public boolean isRunning() {
return running;
}
public boolean isBinary() {
return binary;
}
public void setBinary(boolean binary) {
this.binary = binary;
}
}
| Java |
package com.thimbleware.jmemcached;
import org.jboss.netty.buffer.ChannelBuffer;
import java.util.Arrays;
/**
* Represents a given key for lookup in the cache.
*
* Wraps a byte array with a precomputed hashCode.
*/
public class Key {
public ChannelBuffer bytes;
private int hashCode;
public Key(ChannelBuffer bytes) {
this.bytes = bytes.slice();
this.hashCode = this.bytes.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key1 = (Key) o;
bytes.readerIndex(0);
key1.bytes.readerIndex(0);
if (!bytes.equals(key1.bytes)) return false;
return true;
}
@Override
public int hashCode() {
return hashCode;
}
}
| Java |
package com.thimbleware.jmemcached;
import com.thimbleware.jmemcached.storage.hash.SizedItem;
import org.jboss.netty.buffer.ChannelBuffer;
import java.io.Serializable;
import java.nio.ByteBuffer;
/**
*/
public interface CacheElement extends Serializable, SizedItem {
public final static long THIRTY_DAYS = 2592000000L;
int size();
int hashCode();
long getExpire();
int getFlags();
ChannelBuffer getData();
void setData(ChannelBuffer data);
Key getKey();
long getCasUnique();
void setCasUnique(long casUnique);
boolean isBlocked();
void block(long blockedUntil);
long getBlockedUntil();
CacheElement append(LocalCacheElement element);
CacheElement prepend(LocalCacheElement element);
LocalCacheElement.IncrDecrResult add(int mod);
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached.util;
/**
* Methods for manipulating arrays.
*
* @lucene.internal
*/
final class ArrayUtil {
public static long[] grow(long[] array, int minSize) {
if (array.length < minSize) {
long[] newArray = new long[Math.max(array.length << 1, minSize)];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
} else
return array;
}
public static long[] grow(long[] array) {
return grow(array, 1 + array.length);
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached.util;
/** A variety of high efficiency bit twiddling routines.
* @lucene.internal
*/
final class BitUtil {
/** Returns the number of bits set in the long */
public static int pop(long x) {
/* Hacker's Delight 32 bit pop function:
* http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc
*
int pop(unsigned x) {
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0F0F0F0F;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x0000003F;
}
***/
// 64 bit java version of the C function from above
x = x - ((x >>> 1) & 0x5555555555555555L);
x = (x & 0x3333333333333333L) + ((x >>>2 ) & 0x3333333333333333L);
x = (x + (x >>> 4)) & 0x0F0F0F0F0F0F0F0FL;
x = x + (x >>> 8);
x = x + (x >>> 16);
x = x + (x >>> 32);
return ((int)x) & 0x7F;
}
/*** Returns the number of set bits in an array of longs. */
public static long pop_array(long A[], int wordOffset, int numWords) {
/*
* Robert Harley and David Seal's bit counting algorithm, as documented
* in the revisions of Hacker's Delight
* http://www.hackersdelight.org/revisions.pdf
* http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc
*
* This function was adapted to Java, and extended to use 64 bit words.
* if only we had access to wider registers like SSE from java...
*
* This function can be transformed to compute the popcount of other functions
* on bitsets via something like this:
* sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g'
*
*/
int n = wordOffset+numWords;
long tot=0, tot8=0;
long ones=0, twos=0, fours=0;
int i;
for (i = wordOffset; i <= n - 8; i+=8) {
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA,twosB,foursA,foursB,eights;
// CSA(twosA, ones, ones, A[i], A[i+1])
{
long b=A[i], c=A[i+1];
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
// CSA(twosB, ones, ones, A[i+2], A[i+3])
{
long b=A[i+2], c=A[i+3];
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(twosA, ones, ones, A[i+4], A[i+5])
{
long b=A[i+4], c=A[i+5];
long u=ones^b;
twosA=(ones&b)|(u&c);
ones=u^c;
}
// CSA(twosB, ones, ones, A[i+6], A[i+7])
{
long b=A[i+6], c=A[i+7];
long u=ones^b;
twosB=(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursB=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u=fours^foursA;
eights=(fours&foursA)|(u&foursB);
fours=u^foursB;
}
tot8 += pop(eights);
}
// handle trailing words in a binary-search manner...
// derived from the loop above by setting specific elements to 0.
// the original method in Hackers Delight used a simple for loop:
// for (i = i; i < n; i++) // Add in the last elements
// tot = tot + pop(A[i]);
if (i<=n-4) {
long twosA, twosB, foursA, eights;
{
long b=A[i], c=A[i+1];
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
{
long b=A[i+2], c=A[i+3];
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=4;
}
if (i<=n-2) {
long b=A[i], c=A[i+1];
long u=ones ^ b;
long twosA=(ones & b)|( u & c);
ones=u^c;
long foursA=twos&twosA;
twos=twos^twosA;
long eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=2;
}
if (i<n) {
tot += pop(A[i]);
}
tot += (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones)
+ (tot8<<3);
return tot;
}
/** Returns the popcount or cardinality of the two sets after an intersection.
* Neither array is modified.
*/
public static long pop_intersect(long A[], long B[], int wordOffset, int numWords) {
// generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g'
int n = wordOffset+numWords;
long tot=0, tot8=0;
long ones=0, twos=0, fours=0;
int i;
for (i = wordOffset; i <= n - 8; i+=8) {
long twosA,twosB,foursA,foursB,eights;
// CSA(twosA, ones, ones, (A[i] & B[i]), (A[i+1] & B[i+1]))
{
long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]);
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
// CSA(twosB, ones, ones, (A[i+2] & B[i+2]), (A[i+3] & B[i+3]))
{
long b=(A[i+2] & B[i+2]), c=(A[i+3] & B[i+3]);
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(twosA, ones, ones, (A[i+4] & B[i+4]), (A[i+5] & B[i+5]))
{
long b=(A[i+4] & B[i+4]), c=(A[i+5] & B[i+5]);
long u=ones^b;
twosA=(ones&b)|(u&c);
ones=u^c;
}
// CSA(twosB, ones, ones, (A[i+6] & B[i+6]), (A[i+7] & B[i+7]))
{
long b=(A[i+6] & B[i+6]), c=(A[i+7] & B[i+7]);
long u=ones^b;
twosB=(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursB=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u=fours^foursA;
eights=(fours&foursA)|(u&foursB);
fours=u^foursB;
}
tot8 += pop(eights);
}
if (i<=n-4) {
long twosA, twosB, foursA, eights;
{
long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]);
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
{
long b=(A[i+2] & B[i+2]), c=(A[i+3] & B[i+3]);
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=4;
}
if (i<=n-2) {
long b=(A[i] & B[i]), c=(A[i+1] & B[i+1]);
long u=ones ^ b;
long twosA=(ones & b)|( u & c);
ones=u^c;
long foursA=twos&twosA;
twos=twos^twosA;
long eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=2;
}
if (i<n) {
tot += pop((A[i] & B[i]));
}
tot += (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones)
+ (tot8<<3);
return tot;
}
/** Returns the popcount or cardinality of the union of two sets.
* Neither array is modified.
*/
public static long pop_union(long A[], long B[], int wordOffset, int numWords) {
// generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \| B[\1]\)/g'
int n = wordOffset+numWords;
long tot=0, tot8=0;
long ones=0, twos=0, fours=0;
int i;
for (i = wordOffset; i <= n - 8; i+=8) {
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA,twosB,foursA,foursB,eights;
// CSA(twosA, ones, ones, (A[i] | B[i]), (A[i+1] | B[i+1]))
{
long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]);
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
// CSA(twosB, ones, ones, (A[i+2] | B[i+2]), (A[i+3] | B[i+3]))
{
long b=(A[i+2] | B[i+2]), c=(A[i+3] | B[i+3]);
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(twosA, ones, ones, (A[i+4] | B[i+4]), (A[i+5] | B[i+5]))
{
long b=(A[i+4] | B[i+4]), c=(A[i+5] | B[i+5]);
long u=ones^b;
twosA=(ones&b)|(u&c);
ones=u^c;
}
// CSA(twosB, ones, ones, (A[i+6] | B[i+6]), (A[i+7] | B[i+7]))
{
long b=(A[i+6] | B[i+6]), c=(A[i+7] | B[i+7]);
long u=ones^b;
twosB=(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursB=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u=fours^foursA;
eights=(fours&foursA)|(u&foursB);
fours=u^foursB;
}
tot8 += pop(eights);
}
if (i<=n-4) {
long twosA, twosB, foursA, eights;
{
long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]);
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
{
long b=(A[i+2] | B[i+2]), c=(A[i+3] | B[i+3]);
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=4;
}
if (i<=n-2) {
long b=(A[i] | B[i]), c=(A[i+1] | B[i+1]);
long u=ones ^ b;
long twosA=(ones & b)|( u & c);
ones=u^c;
long foursA=twos&twosA;
twos=twos^twosA;
long eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=2;
}
if (i<n) {
tot += pop((A[i] | B[i]));
}
tot += (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones)
+ (tot8<<3);
return tot;
}
/** Returns the popcount or cardinality of A & ~B
* Neither array is modified.
*/
public static long pop_andnot(long A[], long B[], int wordOffset, int numWords) {
// generated from pop_array via sed 's/A\[\([^]]*\)\]/\(A[\1] \& ~B[\1]\)/g'
int n = wordOffset+numWords;
long tot=0, tot8=0;
long ones=0, twos=0, fours=0;
int i;
for (i = wordOffset; i <= n - 8; i+=8) {
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA,twosB,foursA,foursB,eights;
// CSA(twosA, ones, ones, (A[i] & ~B[i]), (A[i+1] & ~B[i+1]))
{
long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]);
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
// CSA(twosB, ones, ones, (A[i+2] & ~B[i+2]), (A[i+3] & ~B[i+3]))
{
long b=(A[i+2] & ~B[i+2]), c=(A[i+3] & ~B[i+3]);
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(twosA, ones, ones, (A[i+4] & ~B[i+4]), (A[i+5] & ~B[i+5]))
{
long b=(A[i+4] & ~B[i+4]), c=(A[i+5] & ~B[i+5]);
long u=ones^b;
twosA=(ones&b)|(u&c);
ones=u^c;
}
// CSA(twosB, ones, ones, (A[i+6] & ~B[i+6]), (A[i+7] & ~B[i+7]))
{
long b=(A[i+6] & ~B[i+6]), c=(A[i+7] & ~B[i+7]);
long u=ones^b;
twosB=(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursB=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u=fours^foursA;
eights=(fours&foursA)|(u&foursB);
fours=u^foursB;
}
tot8 += pop(eights);
}
if (i<=n-4) {
long twosA, twosB, foursA, eights;
{
long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]);
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
{
long b=(A[i+2] & ~B[i+2]), c=(A[i+3] & ~B[i+3]);
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=4;
}
if (i<=n-2) {
long b=(A[i] & ~B[i]), c=(A[i+1] & ~B[i+1]);
long u=ones ^ b;
long twosA=(ones & b)|( u & c);
ones=u^c;
long foursA=twos&twosA;
twos=twos^twosA;
long eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=2;
}
if (i<n) {
tot += pop((A[i] & ~B[i]));
}
tot += (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones)
+ (tot8<<3);
return tot;
}
public static long pop_xor(long A[], long B[], int wordOffset, int numWords) {
int n = wordOffset+numWords;
long tot=0, tot8=0;
long ones=0, twos=0, fours=0;
int i;
for (i = wordOffset; i <= n - 8; i+=8) {
/*** C macro from Hacker's Delight
#define CSA(h,l, a,b,c) \
{unsigned u = a ^ b; unsigned v = c; \
h = (a & b) | (u & v); l = u ^ v;}
***/
long twosA,twosB,foursA,foursB,eights;
// CSA(twosA, ones, ones, (A[i] ^ B[i]), (A[i+1] ^ B[i+1]))
{
long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]);
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
// CSA(twosB, ones, ones, (A[i+2] ^ B[i+2]), (A[i+3] ^ B[i+3]))
{
long b=(A[i+2] ^ B[i+2]), c=(A[i+3] ^ B[i+3]);
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursA, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(twosA, ones, ones, (A[i+4] ^ B[i+4]), (A[i+5] ^ B[i+5]))
{
long b=(A[i+4] ^ B[i+4]), c=(A[i+5] ^ B[i+5]);
long u=ones^b;
twosA=(ones&b)|(u&c);
ones=u^c;
}
// CSA(twosB, ones, ones, (A[i+6] ^ B[i+6]), (A[i+7] ^ B[i+7]))
{
long b=(A[i+6] ^ B[i+6]), c=(A[i+7] ^ B[i+7]);
long u=ones^b;
twosB=(ones&b)|(u&c);
ones=u^c;
}
//CSA(foursB, twos, twos, twosA, twosB)
{
long u=twos^twosA;
foursB=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
//CSA(eights, fours, fours, foursA, foursB)
{
long u=fours^foursA;
eights=(fours&foursA)|(u&foursB);
fours=u^foursB;
}
tot8 += pop(eights);
}
if (i<=n-4) {
long twosA, twosB, foursA, eights;
{
long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]);
long u=ones ^ b;
twosA=(ones & b)|( u & c);
ones=u^c;
}
{
long b=(A[i+2] ^ B[i+2]), c=(A[i+3] ^ B[i+3]);
long u=ones^b;
twosB =(ones&b)|(u&c);
ones=u^c;
}
{
long u=twos^twosA;
foursA=(twos&twosA)|(u&twosB);
twos=u^twosB;
}
eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=4;
}
if (i<=n-2) {
long b=(A[i] ^ B[i]), c=(A[i+1] ^ B[i+1]);
long u=ones ^ b;
long twosA=(ones & b)|( u & c);
ones=u^c;
long foursA=twos&twosA;
twos=twos^twosA;
long eights=fours&foursA;
fours=fours^foursA;
tot8 += pop(eights);
i+=2;
}
if (i<n) {
tot += pop((A[i] ^ B[i]));
}
tot += (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones)
+ (tot8<<3);
return tot;
}
/* python code to generate ntzTable
def ntz(val):
if val==0: return 8
i=0
while (val&0x01)==0:
i = i+1
val >>= 1
return i
print ','.join([ str(ntz(i)) for i in range(256) ])
***/
/** table of number of trailing zeros in a byte */
public static final byte[] ntzTable = {8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0};
/** Returns number of trailing zeros in a 64 bit long value. */
public static int ntz(long val) {
// A full binary search to determine the low byte was slower than
// a linear search for nextSetBit(). This is most likely because
// the implementation of nextSetBit() shifts bits to the right, increasing
// the probability that the first non-zero byte is in the rhs.
//
// This implementation does a single binary search at the top level only
// so that all other bit shifting can be done on ints instead of longs to
// remain friendly to 32 bit architectures. In addition, the case of a
// non-zero first byte is checked for first because it is the most common
// in dense bit arrays.
int lower = (int)val;
int lowByte = lower & 0xff;
if (lowByte != 0) return ntzTable[lowByte];
if (lower!=0) {
lowByte = (lower>>>8) & 0xff;
if (lowByte != 0) return ntzTable[lowByte] + 8;
lowByte = (lower>>>16) & 0xff;
if (lowByte != 0) return ntzTable[lowByte] + 16;
// no need to mask off low byte for the last byte in the 32 bit word
// no need to check for zero on the last byte either.
return ntzTable[lower>>>24] + 24;
} else {
// grab upper 32 bits
int upper=(int)(val>>32);
lowByte = upper & 0xff;
if (lowByte != 0) return ntzTable[lowByte] + 32;
lowByte = (upper>>>8) & 0xff;
if (lowByte != 0) return ntzTable[lowByte] + 40;
lowByte = (upper>>>16) & 0xff;
if (lowByte != 0) return ntzTable[lowByte] + 48;
// no need to mask off low byte for the last byte in the 32 bit word
// no need to check for zero on the last byte either.
return ntzTable[upper>>>24] + 56;
}
}
/** Returns number of trailing zeros in a 32 bit int value. */
public static int ntz(int val) {
// This implementation does a single binary search at the top level only.
// In addition, the case of a non-zero first byte is checked for first
// because it is the most common in dense bit arrays.
int lowByte = val & 0xff;
if (lowByte != 0) return ntzTable[lowByte];
lowByte = (val>>>8) & 0xff;
if (lowByte != 0) return ntzTable[lowByte] + 8;
lowByte = (val>>>16) & 0xff;
if (lowByte != 0) return ntzTable[lowByte] + 16;
// no need to mask off low byte for the last byte.
// no need to check for zero on the last byte either.
return ntzTable[val>>>24] + 24;
}
/** returns 0 based index of first set bit
* (only works for x!=0)
* <br/> This is an alternate implementation of ntz()
*/
public static int ntz2(long x) {
int n = 0;
int y = (int)x;
if (y==0) {n+=32; y = (int)(x>>>32); } // the only 64 bit shift necessary
if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; }
if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; }
return (ntzTable[ y & 0xff ]) + n;
}
/** returns 0 based index of first set bit
* <br/> This is an alternate implementation of ntz()
*/
public static int ntz3(long x) {
// another implementation taken from Hackers Delight, extended to 64 bits
// and converted to Java.
// Many 32 bit ntz algorithms are at http://www.hackersdelight.org/HDcode/ntz.cc
int n = 1;
// do the first step as a long, all others as ints.
int y = (int)x;
if (y==0) {n+=32; y = (int)(x>>>32); }
if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; }
if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; }
if ((y & 0x0000000F) == 0) { n+=4; y>>>=4; }
if ((y & 0x00000003) == 0) { n+=2; y>>>=2; }
return n - (y & 1);
}
/** returns true if v is a power of two or zero*/
public static boolean isPowerOfTwo(int v) {
return ((v & (v-1)) == 0);
}
/** returns true if v is a power of two or zero*/
public static boolean isPowerOfTwo(long v) {
return ((v & (v-1)) == 0);
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static int nextHighestPowerOfTwo(int v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static long nextHighestPowerOfTwo(long v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
} | Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached.util;
import java.util.Arrays;
import java.io.Serializable;
import java.util.BitSet;
/** An "open" BitSet implementation that allows direct access to the array of words
* storing the bits.
* <p/>
* Unlike java.util.bitset, the fact that bits are packed into an array of longs
* is part of the interface. This allows efficient implementation of other algorithms
* by someone other than the author. It also allows one to efficiently implement
* alternate serialization or interchange formats.
* <p/>
* <code>OpenBitSet</code> is faster than <code>java.util.BitSet</code> in most operations
* and *much* faster at calculating cardinality of sets and results of set operations.
* It can also handle sets of larger cardinality (up to 64 * 2**32-1)
* <p/>
* The goals of <code>OpenBitSet</code> are the fastest implementation possible, and
* maximum code reuse. Extra safety and encapsulation
* may always be built on top, but if that's built in, the cost can never be removed (and
* hence people re-implement their own version in order to get better performance).
* If you want a "safe", totally encapsulated (and slower and limited) BitSet
* class, use <code>java.util.BitSet</code>.
* <p/>
* <h3>Performance Results</h3>
*
Test system: Pentium 4, Sun Java 1.5_06 -server -Xbatch -Xmx64M
<br/>BitSet size = 1,000,000
<br/>Results are java.util.BitSet time divided by OpenBitSet time.
<table border="1">
<tr>
<th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th>
</tr>
<tr>
<th>50% full</th> <td>3.36</td> <td>3.96</td> <td>1.44</td> <td>1.46</td> <td>1.99</td> <td>1.58</td>
</tr>
<tr>
<th>1% full</th> <td>3.31</td> <td>3.90</td> <td> </td> <td>1.04</td> <td> </td> <td>0.99</td>
</tr>
</table>
<br/>
Test system: AMD Opteron, 64 bit linux, Sun Java 1.5_06 -server -Xbatch -Xmx64M
<br/>BitSet size = 1,000,000
<br/>Results are java.util.BitSet time divided by OpenBitSet time.
<table border="1">
<tr>
<th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th>
</tr>
<tr>
<th>50% full</th> <td>2.50</td> <td>3.50</td> <td>1.00</td> <td>1.03</td> <td>1.12</td> <td>1.25</td>
</tr>
<tr>
<th>1% full</th> <td>2.51</td> <td>3.49</td> <td> </td> <td>1.00</td> <td> </td> <td>1.02</td>
</tr>
</table>
*/
public class OpenBitSet implements Cloneable, Serializable {
private static final int OFFSET = 6;
private static final int ELM_SIZE = 1 << OFFSET;
private final static long ALLSET = 0xFFFFFFFFFFFFFFFFL;
private static final long[] TWO_N_ARRAY = new long[] { 0x1L, 0x2L, 0x4L,
0x8L, 0x10L, 0x20L, 0x40L, 0x80L, 0x100L, 0x200L, 0x400L, 0x800L,
0x1000L, 0x2000L, 0x4000L, 0x8000L, 0x10000L, 0x20000L, 0x40000L,
0x80000L, 0x100000L, 0x200000L, 0x400000L, 0x800000L, 0x1000000L,
0x2000000L, 0x4000000L, 0x8000000L, 0x10000000L, 0x20000000L,
0x40000000L, 0x80000000L, 0x100000000L, 0x200000000L, 0x400000000L,
0x800000000L, 0x1000000000L, 0x2000000000L, 0x4000000000L,
0x8000000000L, 0x10000000000L, 0x20000000000L, 0x40000000000L,
0x80000000000L, 0x100000000000L, 0x200000000000L, 0x400000000000L,
0x800000000000L, 0x1000000000000L, 0x2000000000000L,
0x4000000000000L, 0x8000000000000L, 0x10000000000000L,
0x20000000000000L, 0x40000000000000L, 0x80000000000000L,
0x100000000000000L, 0x200000000000000L, 0x400000000000000L,
0x800000000000000L, 0x1000000000000000L, 0x2000000000000000L,
0x4000000000000000L, 0x8000000000000000L };
protected long[] bits;
protected int wlen; // number of words (elements) used in the array
/** Constructs an OpenBitSet large enough to hold numBits.
*
* @param numBits
*/
public OpenBitSet(long numBits) {
bits = new long[bits2words(numBits)];
wlen = bits.length;
}
public OpenBitSet() {
this(64);
}
/** Constructs an OpenBitSet from an existing long[].
* <br/>
* The first 64 bits are in long[0],
* with bit index 0 at the least significant bit, and bit index 63 at the most significant.
* Given a bit index,
* the word containing it is long[index/64], and it is at bit number index%64 within that word.
* <p>
* numWords are the number of elements in the array that contain
* set bits (non-zero longs).
* numWords should be <= bits.length, and
* any existing words in the array at position >= numWords should be zero.
*
*/
public OpenBitSet(long[] bits, int numWords) {
this.bits = bits;
this.wlen = numWords;
}
/** Contructs an OpenBitset from a BitSet
*/
public OpenBitSet(BitSet bits) {
this(bits.length());
}
/** Returns the current capacity in bits (1 greater than the index of the last bit) */
public long capacity() { return bits.length << OFFSET; }
/**
* Returns the current capacity of this set. Included for
* compatibility. This is *not* equal to {@link #cardinality}
*/
public long size() {
return capacity();
}
// @Override -- not until Java 1.6
public int length() {
return bits.length << OFFSET;
}
/** Returns true if there are no set bits */
public boolean isEmpty() { return cardinality()==0; }
/** Expert: returns the long[] storing the bits */
public long[] getBits() { return bits; }
/** Expert: sets a new long[] to use as the bit storage */
public void setBits(long[] bits) { this.bits = bits; }
/** Expert: gets the number of longs in the array that are in use */
public int getNumWords() { return wlen; }
/** Expert: sets the number of longs in the array that are in use */
public void setNumWords(int nWords) { this.wlen=nWords; }
/** Returns true or false for the specified bit index. */
public boolean get(int index) {
int i = index >> OFFSET; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
if (i>=bits.length) return false;
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index.
* The index should be less than the OpenBitSet size
*/
public boolean fastGet(int index) {
int i = index >> OFFSET; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index
*/
public boolean get(long index) {
int i = (int)(index >> OFFSET); // div 64
if (i>=bits.length) return false;
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index.
* The index should be less than the OpenBitSet size.
*/
public boolean fastGet(long index) {
int i = (int)(index >> OFFSET); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/*
// alternate implementation of get()
public boolean get1(int index) {
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
return ((bits[i]>>>bit) & 0x01) != 0;
// this does a long shift and a bittest (on x86) vs
// a long shift, and a long AND, (the test for zero is prob a no-op)
// testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0;
}
*/
/** returns 1 if the bit is set, 0 if not.
* The index should be less than the OpenBitSet size
*/
public int getBit(int index) {
int i = index >> OFFSET; // div 64
int bit = index & 0x3f; // mod 64
return ((int)(bits[i]>>>bit)) & 0x01;
}
/*
public boolean get2(int index) {
int word = index >> 6; // div 64
int bit = index & 0x0000003f; // mod 64
return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed
// we could right shift and check for parity bit, if it was available to us.
}
*/
/** sets a bit, expanding the set size if necessary */
public void set(long index) {
int wordNum = expandingWordNum(index);
int bit = (int)index & 0x3f;
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets the bit at the specified index.
* The index should be less than the OpenBitSet size.
*/
public void fastSet(int index) {
int wordNum = index >> OFFSET; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets the bit at the specified index.
* The index should be less than the OpenBitSet size.
*/
public void fastSet(long index) {
int wordNum = (int)(index >> OFFSET);
int bit = (int)index & 0x3f;
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets a range of bits, expanding the set size if necessary
*
* @param startIndex lower index
* @param endIndex one-past the last bit to set
*/
public void set(long startIndex, long endIndex) {
if (endIndex <= startIndex) return;
int startWord = (int)(startIndex>> OFFSET);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = expandingWordNum(endIndex-1);
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord) {
bits[startWord] |= (startmask & endmask);
return;
}
bits[startWord] |= startmask;
Arrays.fill(bits, startWord+1, endWord, -1L);
bits[endWord] |= endmask;
}
protected int expandingWordNum(long index) {
int wordNum = (int)(index >> OFFSET);
if (wordNum>=wlen) {
ensureCapacity(index+1);
wlen = wordNum+1;
}
return wordNum;
}
/** clears a bit.
* The index should be less than the OpenBitSet size.
*/
public void fastClear(int index) {
int wordNum = index >> OFFSET;
int bit = index & 0x03f;
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
// hmmm, it takes one more instruction to clear than it does to set... any
// way to work around this? If there were only 63 bits per word, we could
// use a right shift of 10111111...111 in binary to position the 0 in the
// correct place (using sign extension).
// Could also use Long.rotateRight() or rotateLeft() *if* they were converted
// by the JVM into a native instruction.
// bits[word] &= Long.rotateLeft(0xfffffffe,bit);
}
/** clears a bit.
* The index should be less than the OpenBitSet size.
*/
public void fastClear(long index) {
int wordNum = (int)(index >> OFFSET); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
/** clears a bit, allowing access beyond the current set size without changing the size.*/
public void clear(long index) {
int wordNum = (int)(index >> OFFSET); // div 64
if (wordNum>=wlen) return;
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
/** Clears a range of bits. Clearing past the end does not change the size of the set.
*
* @param startIndex lower index
* @param endIndex one-past the last bit to clear
*/
public void clear(int startIndex, int endIndex) {
if (endIndex <= startIndex) return;
int startWord = (startIndex>> OFFSET);
if (startWord >= wlen) return;
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ((endIndex-1)>> OFFSET);
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
// invert masks since we are clearing
startmask = ~startmask;
endmask = ~endmask;
if (startWord == endWord) {
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
int middle = Math.min(wlen, endWord);
Arrays.fill(bits, startWord+1, middle, 0L);
if (endWord < wlen) {
bits[endWord] &= endmask;
}
}
/** Clears a range of bits. Clearing past the end does not change the size of the set.
*
* @param startIndex lower index
* @param endIndex one-past the last bit to clear
*/
public void clear(long startIndex, long endIndex) {
if (endIndex <= startIndex) return;
int startWord = (int)(startIndex>> OFFSET);
if (startWord >= wlen) return;
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = (int)((endIndex-1)>> OFFSET);
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
// invert masks since we are clearing
startmask = ~startmask;
endmask = ~endmask;
if (startWord == endWord) {
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
int middle = Math.min(wlen, endWord);
Arrays.fill(bits, startWord+1, middle, 0L);
if (endWord < wlen) {
bits[endWord] &= endmask;
}
}
/** Sets a bit and returns the previous value.
* The index should be less than the OpenBitSet size.
*/
public boolean getAndSet(int index) {
int wordNum = index >> OFFSET; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
boolean val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
/** Sets a bit and returns the previous value.
* The index should be less than the OpenBitSet size.
*/
public boolean getAndSet(long index) {
int wordNum = (int)(index >> OFFSET); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
boolean val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
/** flips a bit.
* The index should be less than the OpenBitSet size.
*/
public void fastFlip(int index) {
int wordNum = index >> OFFSET; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit.
* The index should be less than the OpenBitSet size.
*/
public void fastFlip(long index) {
int wordNum = (int)(index >> OFFSET); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit, expanding the set size if necessary */
public void flip(long index) {
int wordNum = expandingWordNum(index);
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit and returns the resulting bit value.
* The index should be less than the OpenBitSet size.
*/
public boolean flipAndGet(int index) {
int wordNum = index >> OFFSET; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
return (bits[wordNum] & bitmask) != 0;
}
/** flips a bit and returns the resulting bit value.
* The index should be less than the OpenBitSet size.
*/
public boolean flipAndGet(long index) {
int wordNum = (int)(index >> OFFSET); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
return (bits[wordNum] & bitmask) != 0;
}
/** Flips a range of bits, expanding the set size if necessary
*
* @param startIndex lower index
* @param endIndex one-past the last bit to flip
*/
public void flip(long startIndex, long endIndex) {
if (endIndex <= startIndex) return;
int startWord = (int)(startIndex>> OFFSET);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = expandingWordNum(endIndex-1);
/*** Grrr, java shifting wraps around so -1L>>>64 == -1
* for that reason, make sure not to use endmask if the bits to flip will
* be zero in the last word (redefine endWord to be the last changed...)
long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000
long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111
***/
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord) {
bits[startWord] ^= (startmask & endmask);
return;
}
bits[startWord] ^= startmask;
for (int i=startWord+1; i<endWord; i++) {
bits[i] = ~bits[i];
}
bits[endWord] ^= endmask;
}
/*
public static int pop(long v0, long v1, long v2, long v3) {
// derived from pop_array by setting last four elems to 0.
// exchanges one pop() call for 10 elementary operations
// saving about 7 instructions... is there a better way?
long twosA=v0 & v1;
long ones=v0^v1;
long u2=ones^v2;
long twosB =(ones&v2)|(u2&v3);
ones=u2^v3;
long fours=(twosA&twosB);
long twos=twosA^twosB;
return (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones);
}
*/
/** @return the number of set bits */
public long cardinality() {
return BitUtil.pop_array(bits,0,wlen);
}
/** Returns the popcount or cardinality of the intersection of the two sets.
* Neither set is modified.
*/
public static long intersectionCount(OpenBitSet a, OpenBitSet b) {
return BitUtil.pop_intersect(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen));
}
/** Returns the popcount or cardinality of the union of the two sets.
* Neither set is modified.
*/
public static long unionCount(OpenBitSet a, OpenBitSet b) {
long tot = BitUtil.pop_union(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen));
if (a.wlen < b.wlen) {
tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen);
} else if (a.wlen > b.wlen) {
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen);
}
return tot;
}
/** Returns the popcount or cardinality of "a and not b"
* or "intersection(a, not(b))".
* Neither set is modified.
*/
public static long andNotCount(OpenBitSet a, OpenBitSet b) {
long tot = BitUtil.pop_andnot(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen));
if (a.wlen > b.wlen) {
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen);
}
return tot;
}
/** Returns the popcount or cardinality of the exclusive-or of the two sets.
* Neither set is modified.
*/
public static long xorCount(OpenBitSet a, OpenBitSet b) {
long tot = BitUtil.pop_xor(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen));
if (a.wlen < b.wlen) {
tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen);
} else if (a.wlen > b.wlen) {
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen);
}
return tot;
}
/** Returns the index of the first set bit starting at the index specified.
* -1 is returned if there are no more set bits.
*/
public int nextSetBit(int index) {
int i = index>> OFFSET;
if (i>=wlen) return -1;
int subIndex = index & 0x3f; // index within the word
long word = bits[i] >> subIndex; // skip all the bits to the right of index
if (word!=0) {
return (i<< OFFSET) + subIndex + BitUtil.ntz(word);
}
while(++i < wlen) {
word = bits[i];
if (word!=0) return (i<< OFFSET) + BitUtil.ntz(word);
}
return -1;
}
public int mark(int blocks_needed)
{
int count;
int starting_block;
int b = 0;
boolean over_the_top = false;
int wdth = wlen * 64;
while (true) {
if (b < wdth && bits[b >>> OFFSET] == ALLSET) {
/* 64 full blocks. Let's run away from this! */
b = (b & ~0x3f) + 64;
while (b < wdth && bits[b >>> OFFSET] == ALLSET) {
b += 64;
}
}
if (b >= wdth) {
/* Only wrap around once. */
if (!over_the_top) {
b = 0;
over_the_top = true;
continue;
} else {
return -1;
}
}
starting_block = b;
for (count = 0; count < blocks_needed; count++) {
if ((bits[b >>> OFFSET] & (1 << (b & 0x3f))) != 0)
break;
b++;
if (b >= wdth) {
/* time to wrap around if we still haven't */
if (!over_the_top) {
b=0;
over_the_top=true;
break;
} else {
return -1;
}
}
}
if (count == blocks_needed) {
set(starting_block, b+blocks_needed);
return starting_block;
}
b++;
}
}
/** Returns the index of the first set bit starting at the index specified.
* -1 is returned if there are no more set bits.
*/
public long nextSetBit(long index) {
int i = (int)(index>>> OFFSET);
if (i>=wlen) return -1;
int subIndex = (int)index & 0x3f; // index within the word
long word = bits[i] >>> subIndex; // skip all the bits to the right of index
if (word!=0) {
return (((long)i)<< OFFSET) + (subIndex + BitUtil.ntz(word));
}
while(++i < wlen) {
word = bits[i];
if (word!=0) return (((long)i)<< OFFSET) + BitUtil.ntz(word);
}
return -1;
}
@Override
public Object clone() {
try {
OpenBitSet obs = (OpenBitSet)super.clone();
obs.bits = obs.bits.clone(); // hopefully an array clone is as fast(er) than arraycopy
return obs;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
/** this = this AND other */
public void intersect(OpenBitSet other) {
int newLen= Math.min(this.wlen,other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
// testing against zero can be more efficient
int pos=newLen;
while(--pos>=0) {
thisArr[pos] &= otherArr[pos];
}
if (this.wlen > newLen) {
// fill zeros from the new shorter length to the old length
Arrays.fill(bits,newLen,this.wlen,0);
}
this.wlen = newLen;
}
/** this = this OR other */
public void union(OpenBitSet other) {
int newLen = Math.max(wlen,other.wlen);
ensureCapacityWords(newLen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos=Math.min(wlen,other.wlen);
while(--pos>=0) {
thisArr[pos] |= otherArr[pos];
}
if (this.wlen < newLen) {
System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen);
}
this.wlen = newLen;
}
/** Remove all elements set in other. this = this AND_NOT other */
public void remove(OpenBitSet other) {
int idx = Math.min(wlen,other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
while(--idx>=0) {
thisArr[idx] &= ~otherArr[idx];
}
}
/** this = this XOR other */
public void xor(OpenBitSet other) {
int newLen = Math.max(wlen,other.wlen);
ensureCapacityWords(newLen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos=Math.min(wlen,other.wlen);
while(--pos>=0) {
thisArr[pos] ^= otherArr[pos];
}
if (this.wlen < newLen) {
System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen);
}
this.wlen = newLen;
}
// some BitSet compatability methods
//** see {@link intersect} */
public void and(OpenBitSet other) {
intersect(other);
}
//** see {@link union} */
public void or(OpenBitSet other) {
union(other);
}
//** see {@link andNot} */
public void andNot(OpenBitSet other) {
remove(other);
}
/** returns true if the sets have any elements in common */
public boolean intersects(OpenBitSet other) {
int pos = Math.min(this.wlen, other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
while (--pos>=0) {
if ((thisArr[pos] & otherArr[pos])!=0) return true;
}
return false;
}
/** Expand the long[] with the size given as a number of words (64 bit longs).
* getNumWords() is unchanged by this call.
*/
public void ensureCapacityWords(int numWords) {
if (bits.length < numWords) {
bits = ArrayUtil.grow(bits, numWords);
}
}
/** Ensure that the long[] is big enough to hold numBits, expanding it if necessary.
* getNumWords() is unchanged by this call.
*/
public void ensureCapacity(long numBits) {
ensureCapacityWords(bits2words(numBits));
}
/** Lowers numWords, the number of words in use,
* by checking for trailing zero words.
*/
public void trimTrailingZeros() {
int idx = wlen-1;
while (idx>=0 && bits[idx]==0) idx--;
wlen = idx+1;
}
/** returns the number of 64 bit words it would take to hold numBits */
public static int bits2words(long numBits) {
return (int)(((numBits-1)>>> OFFSET)+1);
}
/** returns true if both sets have the same bits set */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OpenBitSet)) return false;
OpenBitSet a;
OpenBitSet b = (OpenBitSet)o;
// make a the larger set.
if (b.wlen > this.wlen) {
a = b; b=this;
} else {
a=this;
}
// check for any set bits out of the range of b
for (int i=a.wlen-1; i>=b.wlen; i--) {
if (a.bits[i]!=0) return false;
}
for (int i=b.wlen-1; i>=0; i--) {
if (a.bits[i] != b.bits[i]) return false;
}
return true;
}
@Override
public int hashCode() {
// Start with a zero hash and use a mix that results in zero if the input is zero.
// This effectively truncates trailing zeros without an explicit check.
long h = 0;
for (int i = bits.length; --i>=0;) {
h ^= bits[i];
h = (h << 1) | (h >>> 63); // rotate left
}
// fold leftmost bits into right and add a constant to prevent
// empty sets from returning 0, which is too common.
return (int)((h>>32) ^ h) + 0x98761234;
}
}
| Java |
package com.thimbleware.jmemcached.util;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.nio.ByteBuffer;
/**
*/
public class BufferUtils {
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
private static final ChannelBuffer LONG_MIN_VALUE_BYTES = ChannelBuffers.wrappedBuffer("-9223372036854775808".getBytes());
// Requires positive x
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
final static byte[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
final static byte [] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
} ;
final static byte [] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
public static int atoi(ChannelBuffer s)
throws NumberFormatException
{
int result = 0;
boolean negative = false;
int i = 0, len = s.capacity();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
byte firstChar = s.getByte(0);
if (firstChar < '0') { // Possible leading "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else
throw new NumberFormatException();
if (len == 1) // Cannot have lone "-"
throw new NumberFormatException();
i++;
}
multmin = limit / 10;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.getByte(i++),10);
if (digit < 0) {
throw new NumberFormatException();
}
if (result < multmin) {
throw new NumberFormatException();
}
result *= 10;
if (result < limit + digit) {
throw new NumberFormatException();
}
result -= digit;
}
} else {
throw new NumberFormatException();
}
return negative ? result : -result;
}
public static long atol(ChannelBuffer s)
throws NumberFormatException
{
long result = 0;
boolean negative = false;
int i = 0, len = s.capacity();
long limit = -Long.MAX_VALUE;
long multmin;
int digit;
if (len > 0) {
byte firstChar = s.getByte(0);
if (firstChar < '0') { // Possible leading "-"
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else
throw new NumberFormatException();
if (len == 1) // Cannot have lone "-"
throw new NumberFormatException();
i++;
}
multmin = limit / 10;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.getByte(i++),10);
if (digit < 0) {
throw new NumberFormatException();
}
if (result < multmin) {
throw new NumberFormatException();
}
result *= 10;
if (result < limit + digit) {
throw new NumberFormatException();
}
result -= digit;
}
} else {
throw new NumberFormatException();
}
return negative ? result : -result;
}
/** Blatant copy of Integer.toString, but returning a byte array instead of a String, as
* string charset decoding/encoding was killing us on performance.
* @param i integer to convert
* @return byte[] array containing literal ASCII char representation
*/
public static ChannelBuffer itoa(int i) {
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
ChannelBuffer buf = ChannelBuffers.buffer(size);
getChars(i, size, buf);
return buf;
}
public static ChannelBuffer ltoa(long i) {
if (i == Long.MIN_VALUE)
return LONG_MIN_VALUE_BYTES;
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
ChannelBuffer buf = ChannelBuffers.buffer(size);
getChars(i, size, buf);
return buf;
}
/**
* Places characters representing the integer i into the
* character array buf. The characters are placed into
* the buffer backwards starting with the least significant
* digit at the specified index (exclusive), and working
* backwards from there.
*
* Will fail if i == Long.MIN_VALUE
*/
static void getChars(long i, int index, ChannelBuffer buf) {
long q;
int r;
int charPos = index;
byte sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
buf.setByte(--charPos, DigitOnes[r]);
buf.setByte(--charPos, DigitTens[r]);
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int)i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
buf.setByte(--charPos, DigitOnes[r]);
buf.setByte(--charPos, DigitTens[r]);
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16+3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
buf.setByte(--charPos, digits[r]);
i2 = q2;
if (i2 == 0) break;
}
if (sign != 0) {
buf.setByte(--charPos, sign);
}
buf.writerIndex(buf.capacity());
}
static void getChars(int i, int index, ChannelBuffer buf) {
int q, r;
int charPos = index;
byte sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Generate two digits per iteration
while (i >= 65536) {
q = i / 100;
// really: r = i - (q * 100);
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
buf.setByte(--charPos, DigitOnes[r]);
buf.setByte(--charPos, DigitTens[r]);
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
for (;;) {
q = (i * 52429) >>> (16+3);
r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
buf.setByte(--charPos, digits[r]);
i = q;
if (i == 0) break;
}
if (sign != 0) {
buf.setByte(--charPos, sign);
}
buf.writerIndex(buf.capacity());
}
// Requires positive x
static int stringSize(long x) {
long p = 10;
for (int i=1; i<19; i++) {
if (x < p)
return i;
p = 10*p;
}
return 19;
}
}
| Java |
/**
* Copyright 2008 ThimbleWare Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached;
import com.thimbleware.jmemcached.storage.CacheStorage;
import org.jboss.netty.buffer.ChannelBuffers;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Set;
import java.util.concurrent.*;
/**
* Default implementation of the cache handler, supporting local memory cache elements.
*/
public final class CacheImpl extends AbstractCache<LocalCacheElement> implements Cache<LocalCacheElement> {
final CacheStorage<Key, LocalCacheElement> storage;
final DelayQueue<DelayedMCElement> deleteQueue;
private final ScheduledExecutorService scavenger;
/**
* @inheritDoc
*/
public CacheImpl(CacheStorage<Key, LocalCacheElement> storage) {
super();
this.storage = storage;
deleteQueue = new DelayQueue<DelayedMCElement>();
scavenger = Executors.newScheduledThreadPool(1);
scavenger.scheduleAtFixedRate(new Runnable(){
public void run() {
asyncEventPing();
}
}, 10, 2, TimeUnit.SECONDS);
}
/**
* @inheritDoc
*/
public DeleteResponse delete(Key key, int time) {
boolean removed = false;
// delayed remove
if (time != 0) {
// block the element and schedule a delete; replace its entry with a blocked element
LocalCacheElement placeHolder = new LocalCacheElement(key, 0, 0, 0L);
placeHolder.setData(ChannelBuffers.buffer(0));
placeHolder.block(Now() + (long)time);
storage.replace(key, placeHolder);
// this must go on a queue for processing later...
deleteQueue.add(new DelayedMCElement(placeHolder));
} else
removed = storage.remove(key) != null;
if (removed) return DeleteResponse.DELETED;
else return DeleteResponse.NOT_FOUND;
}
/**
* @inheritDoc
*/
public StoreResponse add(LocalCacheElement e) {
final long origCasUnique = e.getCasUnique();
e.setCasUnique(casCounter.getAndIncrement());
final boolean stored = storage.putIfAbsent(e.getKey(), e) == null;
// we should restore the former cas so that the object isn't left dirty
if (!stored) {
e.setCasUnique(origCasUnique);
}
return stored ? StoreResponse.STORED : StoreResponse.NOT_STORED;
}
/**
* @inheritDoc
*/
public StoreResponse replace(LocalCacheElement e) {
return storage.replace(e.getKey(), e) != null ? StoreResponse.STORED : StoreResponse.NOT_STORED;
}
/**
* @inheritDoc
*/
public StoreResponse append(LocalCacheElement element) {
LocalCacheElement old = storage.get(element.getKey());
if (old == null || isBlocked(old) || isExpired(old)) {
getMisses.incrementAndGet();
return StoreResponse.NOT_FOUND;
}
else {
return storage.replace(old.getKey(), old, old.append(element)) ? StoreResponse.STORED : StoreResponse.NOT_STORED;
}
}
/**
* @inheritDoc
*/
public StoreResponse prepend(LocalCacheElement element) {
LocalCacheElement old = storage.get(element.getKey());
if (old == null || isBlocked(old) || isExpired(old)) {
getMisses.incrementAndGet();
return StoreResponse.NOT_FOUND;
}
else {
return storage.replace(old.getKey(), old, old.prepend(element)) ? StoreResponse.STORED : StoreResponse.NOT_STORED;
}
}
/**
* @inheritDoc
*/
public StoreResponse set(LocalCacheElement e) {
setCmds.incrementAndGet();//update stats
e.setCasUnique(casCounter.getAndIncrement());
storage.put(e.getKey(), e);
return StoreResponse.STORED;
}
/**
* @inheritDoc
*/
public StoreResponse cas(Long cas_key, LocalCacheElement e) {
// have to get the element
LocalCacheElement element = storage.get(e.getKey());
if (element == null || isBlocked(element)) {
getMisses.incrementAndGet();
return StoreResponse.NOT_FOUND;
}
if (element.getCasUnique() == cas_key) {
// casUnique matches, now set the element
e.setCasUnique(casCounter.getAndIncrement());
if (storage.replace(e.getKey(), element, e)) return StoreResponse.STORED;
else {
getMisses.incrementAndGet();
return StoreResponse.NOT_FOUND;
}
} else {
// cas didn't match; someone else beat us to it
return StoreResponse.EXISTS;
}
}
/**
* @inheritDoc
*/
public Integer get_add(Key key, int mod) {
LocalCacheElement old = storage.get(key);
if (old == null || isBlocked(old) || isExpired(old)) {
getMisses.incrementAndGet();
return null;
} else {
LocalCacheElement.IncrDecrResult result = old.add(mod);
return storage.replace(old.getKey(), old, result.replace) ? result.oldValue : null;
}
}
protected boolean isBlocked(CacheElement e) {
return e.isBlocked() && e.getBlockedUntil() > Now();
}
protected boolean isExpired(CacheElement e) {
return e.getExpire() != 0 && e.getExpire() < Now();
}
/**
* @inheritDoc
*/
public LocalCacheElement[] get(Key ... keys) {
getCmds.incrementAndGet();//updates stats
LocalCacheElement[] elements = new LocalCacheElement[keys.length];
int x = 0;
int hits = 0;
int misses = 0;
for (Key key : keys) {
LocalCacheElement e = storage.get(key);
if (e == null || isExpired(e) || e.isBlocked()) {
misses++;
elements[x] = null;
} else {
hits++;
elements[x] = e;
}
x++;
}
getMisses.addAndGet(misses);
getHits.addAndGet(hits);
return elements;
}
/**
* @inheritDoc
*/
public boolean flush_all() {
return flush_all(0);
}
/**
* @inheritDoc
*/
public boolean flush_all(int expire) {
// TODO implement this, it isn't right... but how to handle efficiently? (don't want to linear scan entire cacheStorage)
storage.clear();
return true;
}
/**
* @inheritDoc
*/
public void close() throws IOException {
scavenger.shutdown();;
storage.close();
}
/**
* @inheritDoc
*/
@Override
protected Set<Key> keys() {
return storage.keySet();
}
/**
* @inheritDoc
*/
@Override
public long getCurrentItems() {
return storage.size();
}
/**
* @inheritDoc
*/
@Override
public long getLimitMaxBytes() {
return storage.getMemoryCapacity();
}
/**
* @inheritDoc
*/
@Override
public long getCurrentBytes() {
return storage.getMemoryUsed();
}
/**
* @inheritDoc
*/
@Override
public void asyncEventPing() {
DelayedMCElement toDelete = deleteQueue.poll();
if (toDelete != null) {
storage.remove(toDelete.element.getKey());
}
}
/**
* Delayed key blocks get processed occasionally.
*/
protected static class DelayedMCElement implements Delayed {
private CacheElement element;
public DelayedMCElement(CacheElement element) {
this.element = element;
}
public long getDelay(TimeUnit timeUnit) {
return timeUnit.convert(element.getBlockedUntil() - Now(), TimeUnit.MILLISECONDS);
}
public int compareTo(Delayed delayed) {
if (!(delayed instanceof CacheImpl.DelayedMCElement))
return -1;
else
return element.getKey().toString().compareTo(((DelayedMCElement) delayed).element.getKey().toString());
}
}
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package com.thimbleware.jmemcached.test;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
/**
* Finds currently available server ports.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
* @see <a href="http://www.iana.org/assignments/port-numbers">IANA.org</a>
*/
public class AvailablePortFinder {
/**
* The minimum number of server port number.
*/
public static final int MIN_PORT_NUMBER = 1;
/**
* The maximum number of server port number.
*/
public static final int MAX_PORT_NUMBER = 49151;
/**
* Creates a new instance.
*/
private AvailablePortFinder() {
// Do nothing
}
/**
* Returns the {@link Set} of currently available port numbers
* ({@link Integer}). This method is identical to
* <code>getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER)</code>.
*
* WARNING: this can take a very long time.
*/
public static Set<Integer> getAvailablePorts() {
return getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER);
}
/**
* Gets the next available port starting at the lowest port number.
*
* @throws NoSuchElementException if there are no ports available
*/
public static int getNextAvailable() {
return getNextAvailable(MIN_PORT_NUMBER);
}
/**
* Gets the next available port starting at a port.
*
* @param fromPort the port to scan for availability
* @throws NoSuchElementException if there are no ports available
*/
public static int getNextAvailable(int fromPort) {
if (fromPort < MIN_PORT_NUMBER || fromPort > MAX_PORT_NUMBER) {
throw new IllegalArgumentException("Invalid start port: "
+ fromPort);
}
for (int i = fromPort; i <= MAX_PORT_NUMBER; i++) {
if (available(i)) {
return i;
}
}
throw new NoSuchElementException("Could not find an available port "
+ "above " + fromPort);
}
/**
* Checks to see if a specific port is available.
*
* @param port the port to check for availability
*/
public static boolean available(int port) {
if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
throw new IllegalArgumentException("Invalid start port: " + port);
}
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
// Do nothing
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
}
/**
* Returns the {@link Set} of currently avaliable port numbers ({@link Integer})
* between the specified port range.
*
* @throws IllegalArgumentException if port range is not between
* {@link #MIN_PORT_NUMBER} and {@link #MAX_PORT_NUMBER} or
* <code>fromPort</code> if greater than <code>toPort</code>.
*/
public static Set<Integer> getAvailablePorts(int fromPort, int toPort) {
if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER
|| fromPort > toPort) {
throw new IllegalArgumentException("Invalid port range: "
+ fromPort + " ~ " + toPort);
}
Set<Integer> result = new TreeSet<Integer>();
for (int i = fromPort; i <= toPort; i++) {
ServerSocket s = null;
try {
s = new ServerSocket(i);
result.add(new Integer(i));
} catch (IOException e) {
// Do nothing
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
}
return result;
}
} | Java |
/**
* Copyright 2008 ThimbleWare Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thimbleware.jmemcached;
import com.thimbleware.jmemcached.storage.bytebuffer.BlockStorageCacheStorage;
import com.thimbleware.jmemcached.storage.CacheStorage;
import com.thimbleware.jmemcached.storage.bytebuffer.BlockStoreFactory;
import com.thimbleware.jmemcached.storage.bytebuffer.ByteBufferBlockStore;
import org.apache.commons.cli.*;
import java.net.InetSocketAddress;
import com.thimbleware.jmemcached.util.Bytes;
import com.thimbleware.jmemcached.storage.hash.ConcurrentLinkedHashMap;
import com.thimbleware.jmemcached.storage.mmap.MemoryMappedBlockStore;
/**
* Command line interface to the Java memcache daemon.
*
* Arguments in general parallel those of the C implementation.
*/
public class Main {
public static void main(String[] args) throws Exception {
// look for external log4j.properties
// setup command line options
Options options = new Options();
options.addOption("h", "help", false, "print this help screen");
options.addOption("bl", "block-store", false, "use external (from JVM) heap");
options.addOption("f", "mapped-file", false, "use external (from JVM) heap through a memory mapped file");
options.addOption("bs", "block-size", true, "block size (in bytes) for external memory mapped file allocator. default is 8 bytes");
options.addOption("i", "idle", true, "disconnect after idle <x> seconds");
options.addOption("p", "port", true, "port to listen on");
options.addOption("m", "memory", true, "max memory to use; in bytes, specify K, kb, M, GB for larger units");
options.addOption("c", "ceiling", true, "ceiling memory to use; in bytes, specify K, kb, M, GB for larger units");
options.addOption("l", "listen", true, "Address to listen on");
options.addOption("s", "size", true, "max items");
options.addOption("b", "binary", false, "binary protocol mode");
options.addOption("V", false, "Show version number");
options.addOption("v", false, "verbose (show commands)");
// read command line options
CommandLineParser parser = new PosixParser();
CommandLine cmdline = parser.parse(options, args);
if (cmdline.hasOption("help") || cmdline.hasOption("h")) {
System.out.println("Memcached Version " + MemCacheDaemon.memcachedVersion);
System.out.println("http://thimbleware.com/projects/memcached\n");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar memcached.jar", options);
return;
}
if (cmdline.hasOption("V")) {
System.out.println("Memcached Version " + MemCacheDaemon.memcachedVersion);
return;
}
int port = 11211;
if (cmdline.hasOption("p")) {
port = Integer.parseInt(cmdline.getOptionValue("p"));
} else if (cmdline.hasOption("port")) {
port = Integer.parseInt(cmdline.getOptionValue("port"));
}
InetSocketAddress addr = new InetSocketAddress(port);
if (cmdline.hasOption("l")) {
addr = new InetSocketAddress(cmdline.getOptionValue("l"), port);
} else if (cmdline.hasOption("listen")) {
addr = new InetSocketAddress(cmdline.getOptionValue("listen"), port);
}
int max_size = 1000000;
if (cmdline.hasOption("s"))
max_size = (int)Bytes.valueOf(cmdline.getOptionValue("s")).bytes();
else if (cmdline.hasOption("size"))
max_size = (int)Bytes.valueOf(cmdline.getOptionValue("size")).bytes();
System.out.println("Setting max cache elements to " + String.valueOf(max_size));
int idle = -1;
if (cmdline.hasOption("i")) {
idle = Integer.parseInt(cmdline.getOptionValue("i"));
} else if (cmdline.hasOption("idle")) {
idle = Integer.parseInt(cmdline.getOptionValue("idle"));
}
boolean memoryMapped = false;
if (cmdline.hasOption("f")) {
memoryMapped = true;
} else if (cmdline.hasOption("mapped-file")) {
memoryMapped = true;
}
boolean blockStore = false;
if (cmdline.hasOption("bl")) {
blockStore = true;
} else if (cmdline.hasOption("block-store")) {
blockStore = true;
}
boolean verbose = false;
if (cmdline.hasOption("v")) {
verbose = true;
}
long ceiling;
if (cmdline.hasOption("c")) {
ceiling = Bytes.valueOf(cmdline.getOptionValue("c")).bytes();
System.out.println("Setting ceiling memory size to " + Bytes.bytes(ceiling).megabytes() + "M");
} else if (cmdline.hasOption("ceiling")) {
ceiling = Bytes.valueOf(cmdline.getOptionValue("ceiling")).bytes();
System.out.println("Setting ceiling memory size to " + Bytes.bytes(ceiling).megabytes() + "M");
} else if (!memoryMapped ){
ceiling = 1024000;
System.out.println("Setting ceiling memory size to default limit of " + Bytes.bytes(ceiling).megabytes() + "M");
} else {
System.out.println("ERROR : ceiling memory size mandatory when external memory mapped file is specified");
return;
}
boolean binary = false;
if (cmdline.hasOption("b")) {
binary = true;
}
int blockSize = 8;
if (!memoryMapped && (cmdline.hasOption("bs") || cmdline.hasOption("block-size"))) {
System.out.println("WARN : block size option is only valid for memory mapped external heap storage; ignoring");
} else if (cmdline.hasOption("bs")) {
blockSize = Integer.parseInt(cmdline.getOptionValue("bs"));
} else if (cmdline.hasOption("block-size")) {
blockSize = Integer.parseInt(cmdline.getOptionValue("block-size"));
}
long maxBytes;
if (cmdline.hasOption("m")) {
maxBytes = Bytes.valueOf(cmdline.getOptionValue("m")).bytes();
System.out.println("Setting max memory size to " + Bytes.bytes(maxBytes).gigabytes() + "GB");
} else if (cmdline.hasOption("memory")) {
maxBytes = Bytes.valueOf(cmdline.getOptionValue("memory")).bytes();
System.out.println("Setting max memory size to " + Bytes.bytes(maxBytes).gigabytes() + "GB");
} else if (!memoryMapped) {
maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Setting max memory size to JVM limit of " + Bytes.bytes(maxBytes).gigabytes() + "GB");
} else {
System.out.println("ERROR : max memory size and ceiling size are mandatory when external memory mapped file is specified");
return;
}
if (!memoryMapped && !blockStore && maxBytes > Runtime.getRuntime().maxMemory()) {
System.out.println("ERROR : JVM heap size is not big enough. use '-Xmx" + String.valueOf(maxBytes / 1024000) + "m' java argument before the '-jar' option.");
return;
} else if ((memoryMapped || !blockStore) && maxBytes > Integer.MAX_VALUE) {
System.out.println("ERROR : when external memory mapped, memory size may not exceed the size of Integer.MAX_VALUE (" + Bytes.bytes(Integer.MAX_VALUE).gigabytes() + "GB");
return;
}
// create daemon and start it
final MemCacheDaemon<LocalCacheElement> daemon = new MemCacheDaemon<LocalCacheElement>();
CacheStorage<Key, LocalCacheElement> storage;
if (blockStore) {
BlockStoreFactory blockStoreFactory = ByteBufferBlockStore.getFactory();
storage = new BlockStorageCacheStorage(8, (int)ceiling, blockSize, maxBytes, max_size, blockStoreFactory);
} else if (memoryMapped) {
BlockStoreFactory blockStoreFactory = MemoryMappedBlockStore.getFactory();
storage = new BlockStorageCacheStorage(8, (int)ceiling, blockSize, maxBytes, max_size, blockStoreFactory);
}
else {
storage = ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, max_size, maxBytes);
}
daemon.setCache(new CacheImpl(storage));
daemon.setBinary(binary);
daemon.setAddr(addr);
daemon.setIdleTime(idle);
daemon.setVerbose(verbose);
daemon.start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
if (daemon.isRunning()) daemon.stop();
}
}));
}
}
| Java |
/**
* Taken and adapted from the Apache Wicket source.
*/
/*
* ==============================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.thimbleware.jmemcached.util;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Represents an immutable byte count. These static factory methods allow easy
* construction of value objects using either long values like bytes(2034) or
* megabytes(3):
* <p>
* <ul>
* <li>Bytes.bytes(long)
* <li>Bytes.kilobytes(long)
* <li>Bytes.megabytes(long)
* <li>Bytes.gigabytes(long)
* <li>Bytes.terabytes(long)
* </ul>
* <p>
* or double precision floating point values like megabytes(3.2):
* <p>
* <ul>
* <li>Bytes.bytes(double)
* <li>Bytes.kilobytes(double)
* <li>Bytes.megabytes(double)
* <li>Bytes.gigabytes(double)
* <li>Bytes.terabytes(double)
* </ul>
* <p>
* In the case of bytes(double), the value will be rounded off to the nearest
* integer byte count using Math.round().
* <p>
* The precise number of bytes in a Bytes object can be retrieved by calling
* bytes(). Approximate values for different units can be retrieved as double
* precision values using these methods:
* <p>
* <ul>
* <li>kilobytes()
* <li>megabytes()
* <li>gigabytes()
* <li>terabytes()
* </ul>
* <p>
* Also, value objects can be constructed from strings, optionally using a
* Locale with valueOf(String) and valueOf(String,Locale). The string may
* contain a decimal or floating point number followed by optional whitespace
* followed by a unit (nothing for bytes, K for kilobyte, M for megabytes, G for
* gigabytes or T for terabytes) optionally followed by a B (for bytes). Any of
* these letters can be any case. So, examples of permissible string values are:
* <p>
* <ul>
* <li>37 (37 bytes)
* <li>2.3K (2.3 kilobytes)
* <li>2.5 kb (2.5 kilobytes)
* <li>4k (4 kilobytes)
* <li>35.2GB (35.2 gigabytes)
* <li>1024M (1024 megabytes)
* </ul>
* <p>
* Note that if the Locale was not US, the values might substitute "," for "."
* as that is the custom in Euroland.
* <p>
* The toString() methods is smart enough to convert a
* given value object to the most appropriate units for the given value.
*
* @author Jonathan Locke
*/
public final class Bytes
{
/** Pattern for string parsing. */
private static final Pattern valuePattern = Pattern.compile(
"([0-9]+([\\.,][0-9]+)?)\\s*(|K|M|G|T)B?", Pattern.CASE_INSENSITIVE);
/** Maximum bytes value */
public static Bytes MAX = bytes(Long.MAX_VALUE);
private long value;
/**
* Private constructor forces use of static factory methods.
*
* @param bytes
* Number of bytes
*/
private Bytes(final long bytes)
{
this.value = bytes;
}
/**
* Instantiate immutable Bytes value object..
*
* @param bytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes bytes(final long bytes)
{
return new Bytes(bytes);
}
/**
* Instantiate immutable Bytes value object..
*
* @param kilobytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes kilobytes(final long kilobytes)
{
return bytes(kilobytes * 1024);
}
/**
* Instantiate immutable Bytes value object..
*
* @param megabytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes megabytes(final long megabytes)
{
return kilobytes(megabytes * 1024);
}
/**
* Instantiate immutable Bytes value object..
*
* @param gigabytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes gigabytes(final long gigabytes)
{
return megabytes(gigabytes * 1024);
}
/**
* Instantiate immutable Bytes value object..
*
* @param terabytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes terabytes(final long terabytes)
{
return gigabytes(terabytes * 1024);
}
/**
* Instantiate immutable Bytes value object..
*
* @param bytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes bytes(final double bytes)
{
return bytes(Math.round(bytes));
}
/**
* Instantiate immutable Bytes value object..
*
* @param kilobytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes kilobytes(final double kilobytes)
{
return bytes(kilobytes * 1024.0);
}
/**
* Instantiate immutable Bytes value object..
*
* @param megabytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes megabytes(final double megabytes)
{
return kilobytes(megabytes * 1024.0);
}
/**
* Instantiate immutable Bytes value object..
*
* @param gigabytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes gigabytes(final double gigabytes)
{
return megabytes(gigabytes * 1024.0);
}
/**
* Instantiate immutable Bytes value object..
*
* @param terabytes
* Value to convert
* @return Input as Bytes
*/
public static Bytes terabytes(final double terabytes)
{
return gigabytes(terabytes * 1024.0);
}
/**
* Gets the byte count represented by this value object.
*
* @return Byte count
*/
public final long bytes()
{
return value;
}
/**
* Gets the byte count in kilobytes.
*
* @return The value in kilobytes
*/
public final double kilobytes()
{
return value / 1024.0;
}
/**
* Gets the byte count in megabytes.
*
* @return The value in megabytes
*/
public final double megabytes()
{
return kilobytes() / 1024.0;
}
/**
* Gets the byte count in gigabytes.
*
* @return The value in gigabytes
*/
public final double gigabytes()
{
return megabytes() / 1024.0;
}
/**
* Gets the byte count in terabytes.
*
* @return The value in terabytes
*/
public final double terabytes()
{
return gigabytes() / 1024.0;
}
/**
* Converts a string to a number of bytes. Strings consist of a floating
* point value followed by K, M, G or T for kilobytes, megabytes, gigabytes
* or terabytes, respectively. The abbreviations KB, MB, GB and TB are also
* accepted. Matching is case insensitive.
*
* @param string
* The string to convert
* @param locale
* The Locale to be used for transformation
* @return The Bytes value for the string
* @throws NumberFormatException
*/
public static Bytes valueOf(final String string, final Locale locale)
throws NumberFormatException
{
final Matcher matcher = valuePattern.matcher(string);
// Valid input?
if (matcher.matches())
{
try
{
// Get double precision value
final double value = NumberFormat.getNumberInstance(locale).parse(matcher.group(1))
.doubleValue();
// Get units specified
final String units = matcher.group(3);
if (units.equalsIgnoreCase(""))
{
return bytes(value);
}
else if (units.equalsIgnoreCase("K"))
{
return kilobytes(value);
}
else if (units.equalsIgnoreCase("M"))
{
return megabytes(value);
}
else if (units.equalsIgnoreCase("G"))
{
return gigabytes(value);
}
else if (units.equalsIgnoreCase("T"))
{
return terabytes(value);
}
else
{
throw new NumberFormatException("Units not recognized: " + string);
}
}
catch (ParseException e)
{
throw new NumberFormatException("Unable to parse numeric part: " + string);
}
}
else
{
throw new NumberFormatException("Unable to parse bytes: " + string);
}
}
/**
* Converts a string to a number of bytes. Strings consist of a floating
* point value followed by K, M, G or T for kilobytes, megabytes, gigabytes
* or terabytes, respectively. The abbreviations KB, MB, GB and TB are also
* accepted. Matching is case insensitive.
*
* @param string
* The string to convert
* @return The Bytes value for the string
* @throws NumberFormatException
*/
public static Bytes valueOf(final String string) throws NumberFormatException
{
return valueOf(string, Locale.getDefault());
}
/**
* Converts this byte count to a string using the given locale.
*
* @return The string for this byte count
*/
public String toString()
{
if (value >= 0)
{
if (terabytes() >= 1.0)
{
return unitString(gigabytes(), "T");
}
if (gigabytes() >= 1.0)
{
return unitString(gigabytes(), "G");
}
if (megabytes() >= 1.0)
{
return unitString(megabytes(), "M");
}
if (kilobytes() >= 1.0)
{
return unitString(kilobytes(), "K");
}
return Long.toString(value) + " bytes";
}
else
{
return "N/A";
}
}
/**
* Convert value to formatted floating point number and units.
*
* @param value
* The value
* @param units
* The units
* @return The formatted string
*/
private String unitString(final double value, final String units)
{
return "" + units;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.base.BenchmarkHelpers.SampleMatcherConfig;
import com.google.common.collect.Lists;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* Benchmark for the {@link CharMatcher} class.
*
*
* @author David Beaumont
* @author Kevin Bourrillion
* @author David Richter
*/
public class CharMatcherBenchmark {
// Caliper injects params automatically
// Overall configuration
@Param SampleMatcherConfig config;
// Length of string to match against
@Param({"64", "1024"}) int length;
// Percent of string that the CharMatcher matches
@Param({"0", "10", "50", "100"}) int percent;
// Whether to use a precomputed CharMatcher
@Param("true") boolean precomputed;
enum Size {
DEFAULT,
SMALL;
}
@Param Size size;
// Whether to ensure there is a matching character in the first position
// to force the trimming code to run.
@Param("false") boolean forceSlow;
// Use web-derived sampler.
@Param("false") boolean web;
private CharMatcher matcher;
private String string;
// Caliper invokes setUp() after injecting params
@BeforeExperiment void setUp() {
this.matcher = precomputed ? config.matcher.precomputed() : config.matcher;
if (size == Size.SMALL) {
BitSet tmp = new BitSet();
matcher.setBits(tmp);
int matchedCharCount = tmp.cardinality();
this.matcher = SmallCharMatcher.from(tmp, "");
}
this.string = checkString(length, percent, config.matchingChars,
new Random(), forceSlow, web);
}
// Caliper recognizes int-parameter methods beginning with "time"
@Benchmark int trimAndCollapseFromString(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += matcher.trimAndCollapseFrom(string, '!').length();
}
return dummy;
}
@Benchmark int matches(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += matcher.matches(string.charAt(i % string.length())) ? 1 : 0;
}
return dummy;
}
private static final String NONMATCHING_CHARS =
"abcdefghijklmnopqrstuvwxyz0123456789";
private static String checkString(int length, int percent,
String matchingChars, Random rand, boolean forceSlow, boolean web) {
// Check whether we should ignore everything else and pull from the web.
if (web) {
StringBuilder builder = new StringBuilder(length);
CharSamples sampler = new CharSamples(rand);
for (int i = 0; i < length; i++) {
int cp = sampler.nextCodePoint();
builder.appendCodePoint(cp);
}
return builder.toString();
}
// Use a shuffled index array to ensure constant percentage of matching
// characters
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < length; i++) {
list.add(i);
}
Collections.shuffle(list, rand);
if (forceSlow) {
// Move zero index to front to force a matching character (if percent > 0)
list.set(list.indexOf(0), list.get(0));
list.set(0, 0);
}
// Get threshold in the range [0, length], rounding up to ensure that non
// zero percent values result in a non-zero threshold (so we always have at
// least one matching character).
int threshold = ((percent * length) + 99) / 100;
StringBuilder builder = new StringBuilder(length);
for (int n = 0; n < length; n++) {
builder.append(randomCharFrom(
list.get(n) >= threshold ? NONMATCHING_CHARS : matchingChars, rand));
}
return builder.toString();
}
private static char randomCharFrom(String s, Random rand) {
return s.charAt(rand.nextInt(s.length()));
}
/**
* Provides samples on a random distribution derived from the web.
*
* Adapted from data provided by Mark Davis.
*
* @author Christopher Swenson
*/
static class CharSamples {
static {
populateProb1();
populateProb2();
populateChars1();
populateChars2();
}
private final Random random;
public CharSamples(Random random) {
this.random = random;
}
public int nextCodePoint() {
int needle = random.nextInt(sum);
int l = 0;
int r = prob.length - 1;
int c = prob.length / 2;
int lv = prob[l];
int rv = prob[r];
int cv = prob[c];
while (true) {
if (needle == cv) {
return chars[c - 1];
} else if ((lv <= needle) && (needle < cv)) {
return chars[l];
} else if (needle == rv) {
return chars[r];
} else if (needle < cv) {
rv = cv;
r = c;
c = l + (r - l) / 2;
cv = prob[c];
} else if (needle == cv) {
return chars[c];
} else {
lv = cv;
l = c;
c = l + (r - l) / 2;
cv = prob[c];
}
}
}
private int sum = 69552218;
private static int[] prob;
private static void populateProb1() {
prob = new int[10003];
int[] temp = new int[] {0, 2998461, 11968276, 18768077, 22489668,
25564867, 28566474, 31178037, 33583728, 35906053, 38220254, 40430228,
42605383, 44136051, 45417665, 46672307, 46782210, 47875442, 48928896,
49849977, 49926463, 50685835, 51384820, 51997588, 52562977, 53114810,
53662681, 54154198, 54201051, 54247649, 54709396, 55150464, 55558189,
55956271, 56255010, 56537443, 56790560, 57034843, 57274138, 57485651,
57690645, 57894136, 58095179, 58290586, 58478703, 58657046, 58833174,
58979618, 59118214, 59252316, 59383011, 59511468, 59616000, 59719717,
59822765, 59924337, 60018141, 60102715, 60103512, 60111276, 60187497,
60261002, 60332050, 60400395, 60463530, 60525044, 60586535, 60592498,
60651542, 60708760, 60765356, 60820799, 60876057, 60926360, 60976475,
61026421, 61074255, 61118922, 61163456, 61207355, 61251147, 61293399,
61334924, 61375951, 61416927, 61457584, 61497222, 61501126, 61539952,
61577967, 61615858, 61652895, 61689599, 61726065, 61762110, 61796817,
61831379, 61865281, 61898336, 61930814, 61963212, 61995571, 62027746,
62059880, 62091953, 62123862, 62155726, 62187494, 62218025, 62247942,
62277854, 62307509, 62336275, 62364822, 62393339, 62421575, 62449112,
62476556, 62503994, 62531165, 62533882, 62536554, 62563178, 62589569,
62615931, 62641977, 62667819, 62670393, 62672941, 62698398, 62723810,
62748828, 62773421, 62773660, 62797528, 62820871, 62823180, 62845858,
62868387, 62890814, 62913180, 62935449, 62957034, 62978440, 62999686,
63020821, 63041849, 63062713, 63082956, 63102958, 63122877, 63142650,
63162263, 63181752, 63201214, 63220472, 63239711, 63258362, 63276998,
63295503, 63313936, 63332203, 63350395, 63368456, 63386448, 63388247,
63405634, 63407359, 63424261, 63441134, 63457698, 63474247, 63490783,
63507308, 63523723, 63539975, 63556168, 63572196, 63587834, 63603467,
63619061, 63634602, 63650139, 63665668, 63681137, 63696535, 63698072,
63713405, 63728710, 63743997, 63759244, 63774378, 63789477, 63804212,
63818898, 63833577, 63848192, 63862616, 63877034, 63891215, 63905360,
63919315, 63933131, 63946873, 63960526, 63974167, 63987674, 64001139,
64014592, 64028011, 64041415, 64054809, 64068126, 64081417, 64094632,
64107536, 64120332, 64133044, 64145616, 64158121, 64170496, 64182865,
64195233, 64207588, 64219849, 64232094, 64244320, 64256504, 64257719,
64269791, 64281807, 64293783, 64305588, 64306765, 64318504, 64330211,
64341904, 64353578, 64365252, 64366419, 64378068, 64389716, 64401322,
64412871, 64424406, 64425552, 64426689, 64437977, 64449132, 64460284,
64471315, 64482340, 64493269, 64503956, 64514601, 64525226, 64535778,
64546326, 64556767, 64567140, 64577453, 64587746, 64598011, 64608256,
64608358, 64618492, 64628579, 64638653, 64648727, 64658764, 64668799,
64678680, 64688543, 64698398, 64708082, 64717757, 64727380, 64736982,
64746557, 64756118, 64765654, 64775155, 64784592, 64794024, 64803433,
64812780, 64822087, 64831283, 64840465, 64849520, 64858567, 64867599,
64876612, 64885585, 64894553, 64903472, 64912373, 64921249, 64930038,
64938750, 64947452, 64948320, 64956991, 64965638, 64974277, 64982885,
64991466, 65000015, 65008563, 65017094, 65025571, 65033995, 65042379,
65050716, 65059035, 65067338, 65075627, 65076455, 65084727, 65092982,
65101144, 65109266, 65117373, 65125479, 65133578, 65141657, 65149726,
65150531, 65158555, 65166553, 65174472, 65182377, 65190260, 65198136,
65205979, 65206763, 65214595, 65222402, 65230135, 65237858, 65245556,
65253253, 65260922, 65261686, 65269318, 65276950, 65284569, 65292163,
65299687, 65307200, 65307275, 65314762, 65322226, 65329664, 65337073,
65344451, 65351800, 65359136, 65366462, 65373775, 65381087, 65388284,
65395469, 65402651, 65409830, 65417003, 65424168, 65431331, 65438487,
65445595, 65452672, 65459721, 65466766, 65473795, 65480823, 65487847,
65494824, 65501797, 65508770, 65515732, 65522693, 65529646, 65536520,
65537207, 65537893, 65538579, 65545430, 65552241, 65559039, 65565814,
65572562, 65579296, 65586020, 65592716, 65593382, 65600037, 65606605,
65613147, 65619640, 65626071, 65632496, 65638918, 65645310, 65645945,
65652280, 65652912, 65659168, 65665415, 65671631, 65677833, 65684025,
65684641, 65690780, 65696909, 65703021, 65709132, 65715239, 65721340,
65727438, 65733535, 65739617, 65745695, 65751753, 65757765, 65763760,
65769744, 65775699, 65781646, 65787588, 65793525, 65799461, 65805374,
65811283, 65817190, 65823078, 65823666, 65824253, 65830101, 65835942,
65841755, 65847563, 65853354, 65859098, 65864810, 65870519, 65876183,
65881822, 65887437, 65893045, 65898651, 65904246, 65909707, 65915151,
65920583, 65925999, 65931410, 65936817, 65942193, 65947567, 65952934,
65958289, 65963637, 65968969, 65974293, 65974825, 65980140, 65985417,
65990672, 65995914, 66001153, 66006392, 66011615, 66012137, 66017334,
66022528, 66027719, 66032905, 66033422, 66038587, 66043749, 66048910,
66054066, 66059218, 66064370, 66069493, 66070005, 66075122, 66080220,
66085315, 66090410, 66095497, 66100582, 66105664, 66110746, 66115813,
66120879, 66125928, 66130971, 66131475, 66136498, 66141516, 66146527,
66151533, 66156526, 66161499, 66166472, 66171429, 66176377, 66181315,
66186228, 66186719, 66191625, 66196528, 66196577, 66201473, 66206365,
66206854, 66211740, 66216606, 66221467, 66226320, 66231162, 66231645,
66236468, 66241285, 66246076, 66250853, 66255621, 66260387, 66265121,
66269852, 66274579, 66279293, 66284006, 66288711, 66293414, 66298061,
66302706, 66307341, 66311963, 66316582, 66321199, 66325797, 66330382,
66334965, 66339540, 66344108, 66348674, 66353233, 66357788, 66362332,
66366874, 66371412, 66375949, 66380462, 66384963, 66385008, 66389507,
66393988, 66398461, 66402913, 66407358, 66411800, 66416227, 66420650,
66421092, 66425506, 66429903, 66434282, 66438657, 66443011, 66447364,
66451711, 66456043, 66460374, 66464695, 66469009, 66473318, 66477619,
66481905, 66486174, 66490433, 66494685, 66498930, 66503172, 66507405,
66511629, 66515843, 66520045, 66524244, 66528437, 66532628, 66536801,
66540968, 66545132, 66549288, 66553436, 66557577, 66561711, 66565840,
66569963, 66570004, 66574103, 66578201, 66582298, 66582707, 66583115,
66587194, 66591270, 66595323, 66599360, 66603386, 66607410, 66611432,
66615421, 66619394, 66623366, 66623763, 66627728, 66631691, 66635652,
66639601, 66643544, 66647482, 66651390, 66655298, 66659177, 66663029,
66666880, 66670725, 66674569, 66678395, 66682219, 66686042, 66689844,
66693646, 66697442, 66701236, 66705023, 66708801, 66712574, 66716338,
66720099, 66723857, 66727581, 66731302, 66735016, 66738729, 66742440,
66746147, 66749838, 66753521, 66757203, 66757571, 66761249, 66764927,
66768604, 66772257, 66775909, 66779541, 66783159, 66786773, 66790376,
66793962, 66797546, 66801127, 66804703, 66808262, 66811818, 66815367,
66818912, 66822449, 66825986, 66829521, 66833055, 66836582, 66840106,
66843624, 66847140, 66850656, 66854170, 66857658, 66861130, 66864598,
66868064, 66871527, 66874984, 66878430, 66881873, 66885312, 66888746,
66892179, 66895608, 66899030, 66902433, 66905822, 66909208, 66912593,
66915978, 66919361, 66922743, 66926120, 66929492, 66932854, 66936205,
66939548, 66942882, 66946210, 66949528, 66949859, 66953164, 66956467,
66959762, 66960091, 66963379, 66966665, 66969950, 66973229, 66976498,
66979762, 66983021, 66986279, 66989531, 66992782, 66996030, 66999275,
67002518, 67005760, 67008993, 67012220, 67015446, 67018671, 67018993,
67022210, 67025425, 67028640, 67031851, 67035058, 67038263, 67041459,
67044653, 67047839, 67051016, 67054190, 67057359, 67060524, 67063687,
67066836, 67069985, 67073112, 67076238, 67079355, 67082471, 67085585,
67088688, 67091790, 67094862, 67095169, 67098228, 67101266, 67101568,
67104586, 67107601, 67110615, 67110618, 67110621, 67113616, 67116609,
67119594, 67122578, 67125559, 67128533, 67131506, 67134473, 67137436,
67140397, 67143358, 67146316, 67149268, 67152216, 67155163, 67158106,
67161049, 67163991, 67166929, 67167222, 67170149, 67173074, 67175993,
67178907, 67181820, 67184732, 67187640, 67190545, 67193440, 67193729,
67196611, 67199490, 67202361, 67205225, 67208088, 67208374, 67211232,
67214088, 67216942, 67219795, 67222648, 67225497, 67228341, 67231184,
67231468, 67231752, 67234590, 67237424, 67240250, 67243069, 67245884,
67248698, 67251505, 67254310, 67257109, 67259903, 67262692, 67265473,
67265751, 67268529, 67271305, 67274079, 67276851, 67279620, 67282388,
67285155, 67287917, 67290675, 67293433, 67296185, 67298937, 67299212,
67301957, 67304700, 67307442, 67310183, 67312919, 67315644, 67318366,
67321087, 67323805, 67326518, 67329224, 67331930, 67331957, 67334652,
67337347, 67340039, 67342725, 67345383, 67348017, 67350646, 67353274,
67355896, 67358502, 67361108, 67363707, 67366305, 67368903, 67371499,
67374088, 67376677, 67379265, 67381850, 67384431, 67384689, 67387266,
67389841, 67392403, 67394964, 67397525, 67397781, 67400338, 67402890,
67405435, 67407979, 67410522, 67413058, 67415590, 67418115, 67420637,
67423158, 67423410, 67425925, 67428434, 67430942, 67433448, 67435952,
67438456, 67440953, 67443448, 67445941, 67446190, 67446439, 67448925,
67451408, 67453886, 67456359, 67458828, 67461289, 67463747, 67466201,
67468640, 67471077, 67473514, 67475948, 67478379, 67478622, 67481044,
67483466, 67485887, 67488300, 67488541, 67490945, 67493342, 67495737,
67498130, 67500519, 67502886, 67505248, 67507610, 67509969, 67512326,
67514681, 67514916, 67517263, 67519605, 67521947, 67524283, 67526618,
67528949, 67531278, 67533606, 67535931, 67538254, 67540576, 67542898,
67545217, 67547535, 67549852, 67552168, 67554484, 67556799, 67559112,
67561425, 67563731, 67566034, 67566057, 67568355, 67570651, 67570880,
67573165, 67575449, 67577733, 67580011, 67582284, 67584546, 67586803,
67589060, 67591315, 67593569, 67595817, 67598064, 67600303, 67602540,
67604776, 67607003, 67609227, 67611449, 67613666, 67615878, 67616099,
67618306, 67620513, 67622701, 67624888, 67627074, 67629256, 67631437,
67631655, 67633831, 67635996, 67636212, 67638368, 67640522, 67642669,
67644814, 67646957, 67649094, 67651228, 67653359, 67655488, 67657613,
67659737, 67659949, 67660161, 67662279, 67664392, 67666501, 67668609,
67670712, 67670733, 67672832, 67674930, 67677025, 67679119, 67679328,
67681415, 67683499, 67685582, 67685790, 67687869, 67689943, 67692016,
67692223, 67694292, 67696359, 67698420, 67700476, 67702531, 67704585,
67704790, 67706839, 67708886, 67710931, 67712976, 67715019, 67717058,
67719096, 67721131, 67723166, 67723369, 67725396, 67727421, 67729443,
67731464, 67733480, 67735496, 67737505, 67737507, 67739505, 67741499,
67743493, 67745487, 67747480, 67749473, 67749672, 67749871, 67751859,
67753842, 67755823, 67757804, 67758002, 67759979, 67761956, 67763927,
67765898, 67767867, 67769836, 67771802, 67773766, 67775729, 67775925,
67777878, 67779822, 67781765, 67783706, 67785645, 67787584, 67789521,
67791457, 67793391, 67795324, 67797256, 67799187, 67801112, 67803035,
67804948, 67805139, 67807046, 67808951, 67810850, 67812744, 67814625,
67814813, 67815001, 67816875, 67818748, 67820620, 67822492, 67822679,
67824547, 67826413, 67828276, 67830137, 67830323, 67832181, 67834039,
67835895, 67837751, 67839606, 67841460, 67843311, 67845160, 67847008,
67848856, 67850698, 67850882, 67852720, 67854558, 67856395, 67856578,
67858405, 67860227, 67862048, 67862230, 67862412, 67864231, 67866048,
67867865, 67869682, 67871486, 67873285, 67875082, 67876877, 67878672,
67880467, 67882261, 67884054, 67885846, 67887635, 67889422, 67891209,
67892994, 67894775, 67896550, 67898323, 67900092, 67901854, 67902030,
67903781, 67905532, 67905707, 67907456, 67909203, 67910949, 67912682,
67914411, 67916139, 67917864, 67919589, 67921312, 67923034, 67924755,
67926471, 67928182, 67928353, 67930062, 67931771, 67933479, 67935181,
67936882, 67936899, 67938598, 67940294, 67941990, 67943685, 67945378,
67947063, 67948746, 67950429, 67952112, 67953785, 67955453, 67955619,
67957277, 67958934, 67960587, 67962238, 67962403, 67962568, 67962733,
67964382, 67966030, 67967676, 67969322, 67970966, 67972608, 67974249,
67974413, 67976046, 67977677, 67977840, 67979467, 67981094, 67982720,
67984338, 67985950, 67987561, 67987722, 67989331, 67990939, 67992547,
67994154, 67995761, 67997368, 67998971, 68000573, 68002174, 68002190,
68003789, 68005388, 68006985, 68008581, 68010176, 68011768, 68013356,
68014940, 68016522, 68016680, 68016838, 68018416, 68019994, 68021571,
68023147, 68024723, 68026296, 68027868, 68029439, 68029596, 68031162,
68032724, 68034286, 68034442, 68034598, 68036157, 68037716, 68039273,
68040827, 68042380, 68043932, 68045481, 68047024, 68048567, 68050106,
68051641, 68051794, 68053323, 68054849, 68056374, 68057898, 68059417,
68060934, 68062451, 68063967, 68065480, 68066991, 68067142, 68068651,
68070157, 68071660, 68071675, 68071690, 68073187, 68074678, 68074827,
68076316, 68077805, 68079293, 68080780, 68082265, 68083750, 68085232,
68086713, 68088194, 68089673, 68091149, 68092623, 68094096, 68095568,
68095715, 68095862, 68097331, 68098796, 68100261, 68101726, 68103190,
68104654, 68106116, 68107575, 68109033, 68110490, 68111945, 68113396,
68114845, 68116294, 68117741, 68119184, 68119328, 68120765, 68122201,
68123633, 68125064, 68125207, 68126633, 68128059, 68129483, 68130906,
68132328, 68133749, 68135154, 68135168, 68136567, 68137966, 68139365,
68140762, 68142156, 68143550, 68144943, 68146336, 68147729, 68149120,
68150511, 68151902, 68152041, 68153429, 68154816, 68156203, 68157588,
68158970, 68160352, 68161731, 68163110, 68164486, 68165861, 68167233,
68167370, 68168738, 68168874, 68170229, 68171584, 68172937, 68174282,
68175625, 68176966, 68177100, 68177234, 68177368, 68177502, 68178839,
68180175, 68181511, 68182844, 68184177, 68185509, 68186838, 68188166,
68189493, 68190819, 68192144, 68193466, 68194788, 68196109, 68197427,
68198744, 68200060, 68201375, 68202688, 68204000, 68205311, 68205442,
68205573, 68206880, 68208187, 68209491, 68210794, 68212097, 68213398,
68214697, 68215996, 68217293, 68218589, 68219885, 68221180, 68222474,
68223766, 68223895, 68225183, 68226470, 68227755, 68229040, 68230324,
68231607, 68232889, 68234167, 68235443, 68236719, 68237994, 68239269,
68240543, 68241817, 68243090, 68244362, 68245634, 68246903, 68248172,
68249441, 68250709, 68251977, 68253245, 68254509, 68255772, 68257035,
68258296, 68259555, 68260813, 68262068, 68263322, 68264576, 68265829,
68267082, 68268335, 68269587, 68270836, 68272083, 68273330, 68274574,
68275817, 68277060, 68278302, 68279543, 68280781, 68282018, 68283253,
68284485, 68285714, 68286943, 68288171, 68289393, 68290615, 68291836,
68293055, 68294272, 68295488, 68296702, 68297916, 68299129, 68300341,
68300462, 68301669, 68302873, 68304077, 68305281, 68306485, 68307687,
68308888, 68310089, 68311290, 68311302, 68312501, 68313699, 68314897,
68316094, 68317291, 68318486, 68318605, 68319793, 68320981, 68322168,
68323354, 68324539, 68325724, 68326909, 68328093, 68329275, 68330457,
68331639, 68331757, 68332935, 68334112, 68335289, 68336466, 68337640,
68338813, 68339982, 68341148, 68342313, 68343474, 68343590, 68344749,
68345908, 68347065, 68348221, 68349377, 68350532, 68351686, 68352840,
68353992, 68354107, 68354222, 68355370, 68356516, 68357654, 68358792,
68359926, 68361053, 68362179, 68363301, 68364423, 68365544, 68366659,
68367772, 68368884, 68368995, 68369106, 68370215, 68371323, 68372430,
68373537, 68374643, 68375749, 68376852, 68377953, 68379052, 68380151,
68381249, 68382346, 68383442, 68384537, 68385632, 68386726, 68387820,
68388913, 68390006, 68391099, 68392191, 68393280, 68394368, 68395455,
68396542, 68397626, 68398710, 68399794, 68400877, 68401959, 68403041,
68404123, 68405204, 68406285, 68407366, 68408447, 68409528, 68409636,
68409744, 68410822, 68411900, 68412978, 68414051, 68415123, 68416192,
68417259, 68418325, 68419391, 68420452, 68421513, 68422572, 68423631,
68424690, 68425749, 68426808, 68427867, 68428924, 68429981, 68431037,
68432093, 68433147, 68434200, 68435249, 68436298, 68437346, 68438394,
68439442, 68440489, 68441533, 68442576, 68443619, 68444657, 68445694,
68446730, 68447764, 68447867, 68447970, 68448998, 68450025, 68451052,
68452077, 68453102, 68454125, 68455147, 68456169, 68457187, 68458205,
68459223, 68460241, 68461258, 68462274, 68463289, 68464303, 68465317,
68466329, 68466430, 68466531, 68467540, 68468548, 68469555, 68470560,
68471565, 68472568, 68473570, 68474572, 68475574, 68475575, 68475576,
68476575, 68477573, 68478570, 68479566, 68480562, 68481557, 68482551,
68483545, 68484539, 68484638, 68484737, 68484836, 68485825, 68486811,
68487796, 68488777, 68488875, 68488973, 68489952, 68490931, 68491908,
68492884, 68493859, 68494834, 68495809, 68496783, 68497756, 68498728,
68498825, 68498922, 68499890, 68500858, 68501825, 68502791, 68503757,
68504720, 68505683, 68506645, 68506741, 68507700, 68508658, 68509611,
68510562, 68511513, 68512464, 68513415, 68514366, 68515317, 68515412,
68515507, 68515602, 68515697, 68515792, 68515887, 68516836, 68517785,
68518734, 68519683, 68520631, 68521578, 68522525, 68523470, 68524413,
68525354, 68526295, 68527236, 68528173, 68529109, 68530045, 68530981,
68531915, 68532849, 68533781, 68534713, 68535645, 68536576, 68537507,
68537600, 68537693, 68538622, 68539550, 68540476, 68541399, 68542320,
68542412, 68542504, 68543423, 68544342, 68545260, 68546176, 68547092,
68548007, 68548922, 68549834, 68550745, 68551656, 68551747, 68552655,
68553560, 68554465, 68555370, 68556274, 68557177, 68558080, 68558982,
68559883, 68560784, 68561685, 68561694, 68562592, 68563490, 68564388,
68565285, 68566181, 68567077, 68567973, 68568869, 68569765, 68570659,
68571552, 68572444, 68573336, 68574228, 68575120, 68576011, 68576902,
68576991, 68577880, 68578768, 68579655, 68580541, 68581427, 68582313,
68583196, 68584078, 68584960, 68585841, 68585929, 68586808, 68587685,
68588561, 68589437, 68590313, 68591189, 68592065, 68592940, 68593027,
68593894, 68594760, 68595626, 68596492, 68597356, 68598218, 68599077,
68599936, 68600795, 68601652, 68602508, 68603363, 68604217, 68605070,
68605922, 68606774, 68607626, 68608477, 68608562, 68609411, 68610260,
68611107, 68611954, 68612800, 68613646, 68614491, 68615336, 68616179,
68617021, 68617862, 68618703, 68618787, 68618871, 68619710, 68620548,
68621386, 68622222, 68623058, 68623893, 68624728, 68625563, 68626397,
68627231, 68628064, 68628896, 68629728, 68630559, 68631390, 68632219,
68633047, 68633875, 68634702, 68635529, 68636356, 68637183, 68638009,
68638833, 68639656, 68640478, 68641299, 68642120, 68642202, 68643021,
68643840, 68644659, 68645477, 68646294, 68647111, 68647927, 68648743,
68649559, 68650373, 68651187, 68651998, 68652803, 68653607, 68654410,
68655213, 68656016, 68656818, 68657620, 68657628, 68658427, 68659226,
68660024, 68660822, 68661620, 68662417, 68663214, 68664010, 68664806,
68665601, 68666395, 68667189, 68667982, 68668774, 68669565, 68670356,
68671147, 68671935, 68672723, 68673509, 68674295, 68675079, 68675862,
68675940, 68676719, 68677498, 68678275, 68679051, 68679826, 68680601,
68681375, 68682149, 68682922, 68683694, 68684466, 68685237, 68685314,
68685391, 68686160, 68686929, 68687697, 68688464, 68689230, 68689996,
68690760, 68691523, 68692285, 68693046, 68693122, 68693198, 68693956,
68694713, 68695468, 68696222, 68696976, 68697730, 68698483, 68699235,
68699986, 68700737, 68701486, 68702235, 68702984, 68703732, 68704480,
68705226, 68705972, 68706718, 68707463, 68708208, 68708953, 68709697,
68710440, 68711183, 68711926, 68712667, 68713408, 68714145, 68714882,
68715618, 68716354, 68717090, 68717825, 68718559, 68719292, 68720024,
68720753, 68721482, 68722209, 68722935, 68723660, 68724384, 68725108,
68725832, 68726555, 68727278, 68728001, 68728723, 68728795, 68729514,
68730233, 68730951, 68731669, 68732385, 68733101, 68733816, 68734528,
68735240, 68735951, 68736022, 68736093, 68736164, 68736235, 68736944,
68737653, 68738362, 68739069, 68739775, 68740481, 68741187, 68741892,
68742597, 68743301, 68744005, 68744707, 68745409, 68746110, 68746811,
68746818, 68746825, 68747524, 68748223, 68748922, 68749620, 68750315,
68751009, 68751703, 68752397, 68753090, 68753783, 68754474, 68755165,
68755856, 68755925, 68755994, 68756683, 68757371, 68758059, 68758746,
68759433, 68760119, 68760805, 68761488, 68762171, 68762852, 68763533,
68764214, 68764893, 68765572, 68766251, 68766930, 68767608, 68768286,
68768963, 68769640, 68770316, 68770992, 68771667, 68772342, 68773015,
68773688, 68774360, 68775032, 68775703, 68776374, 68776441, 68777110,
68777777, 68778444, 68779111, 68779778, 68780444, 68781110, 68781776,
68782441, 68783106, 68783770, 68784432, 68785094, 68785755, 68786416,
68786482, 68786548, 68787207, 68787866, 68788524, 68789182, 68789840,
68790497, 68791154, 68791810, 68792466, 68793122, 68793777, 68794432,
68795087, 68795741, 68796395, 68797048, 68797700, 68798352, 68799004,
68799656, 68800307, 68800372, 68800437, 68801086, 68801735, 68802384,
68803033, 68803681, 68804329, 68804976, 68805621, 68806265, 68806908,
68807551, 68808194, 68808836, 68809477, 68810118, 68810759, 68811400,
68811464, 68811528, 68811592, 68812230, 68812868, 68813506, 68814141,
68814776, 68815411, 68816045, 68816679, 68817311, 68817943, 68818571,
68819199, 68819826, 68820452, 68821078, 68821704, 68822329, 68822954,
68823579, 68824203, 68824826, 68825449, 68826071, 68826133, 68826195,
68826257, 68826319, 68826381, 68827000, 68827619, 68828237, 68828855,
68829473, 68830090, 68830707, 68831323, 68831938, 68832553, 68833167,
68833781, 68834395, 68835008, 68835621, 68836233, 68836842, 68837450,
68838057, 68838663, 68839269, 68839874, 68840479, 68841084, 68841689,
68842293, 68842897, 68843501, 68844105, 68844708, 68845310, 68845912,
68845918, 68845924, 68845930, 68845936, 68846535, 68847134, 68847733,
68848332, 68848930, 68849527, 68850124, 68850720, 68851315, 68851909,
68852503, 68853096, 68853688, 68854280, 68854872, 68855464, 68856056,
68856115, 68856174, 68856233, 68856822, 68857411, 68858000, 68858589,
68859178, 68859766, 68860353, 68860939, 68861523, 68862107, 68862691,
68863274, 68863857, 68864438, 68865019, 68865600, 68865658, 68866237,
68866816, 68867395, 68867973, 68868551, 68869129, 68869706, 68870283,
68870860, 68871437, 68872013, 68872589, 68873164, 68873739, 68874313,
68874887, 68875461, 68876035, 68876609, 68877183, 68877756, 68878329,
68878901, 68879473, 68880045, 68880617, 68881188, 68881759, 68882328,
68882897, 68883465, 68884033, 68884601, 68885169, 68885735, 68886301,
68886865, 68887428, 68887991, 68888554, 68889116, 68889678, 68890239,
68890295, 68890854, 68891412, 68891969, 68892526, 68893083, 68893639,
68894195, 68894751, 68895307, 68895862, 68896416, 68896970, 68897524,
68898078, 68898631, 68899182, 68899733, 68900284, 68900835, 68901386,
68901937, 68902488, 68902543, 68902598, 68902653, 68902708, 68903257,
68903806, 68904354, 68904902, 68905450, 68905996, 68906540, 68907084,
68907628, 68908172, 68908716, 68909260, 68909803, 68910345, 68910887,
68911429, 68911971, 68912512, 68913053, 68913594, 68913648, 68914187,
68914725, 68915262, 68915798, 68916334, 68916870, 68917406, 68917941,
68918475, 68919009, 68919543, 68920076, 68920608, 68921140, 68921672,
68922204, 68922735, 68923266, 68923797, 68924328, 68924859, 68925390,
68925919, 68926448, 68926975, 68927502, 68928029, 68928555, 68929081,
68929606, 68930131, 68930656, 68931180, 68931703, 68932226, 68932749,
68933271, 68933792, 68934313, 68934365, 68934884, 68935403, 68935922,
68936440, 68936957, 68937474, 68937991, 68938507, 68939023, 68939538,
68940053, 68940567, 68941081, 68941595, 68942108, 68942621, 68943133,
68943645, 68944157, 68944669, 68945180, 68945231, 68945282, 68945333,
68945842, 68946351, 68946860, 68947369, 68947877, 68948385, 68948893,
68949400, 68949906, 68950412, 68950918, 68951424, 68951929, 68952434,
68952938, 68953441, 68953944, 68954447, 68954949, 68955450, 68955949,
68956448, 68956947, 68957445, 68957943, 68958441, 68958938, 68959435,
68959932, 68960429, 68960926, 68961422, 68961917, 68962412, 68962907,
68963401, 68963894, 68964387, 68964880, 68965373, 68965866, 68966359,
68966852, 68967345, 68967837, 68968329, 68968821, 68968870, 68968919,
68968968, 68969457, 68969945, 68970432, 68970919, 68971405, 68971891,
68972376, 68972861, 68973346, 68973831, 68974315, 68974797, 68975278,
68975759, 68976240, 68976288, 68976336, 68976815, 68977294, 68977772,
68978250, 68978727, 68979204, 68979680, 68980156, 68980632, 68981108,
68981583, 68982057, 68982530, 68983003, 68983475, 68983947, 68984419,
68984891, 68985363, 68985834, 68986305, 68986352, 68986399, 68986868,
68987337, 68987806, 68988275, 68988743, 68989211, 68989679, 68990147,
68990615, 68991082, 68991549, 68992016, 68992482, 68992948, 68993414,
68993879, 68994344, 68994809, 68995274, 68995739, 68996203, 68996667,
68997131, 68997595, 68998058, 68998521, 68998983, 68999444, 68999905,
69000366, 69000827, 69001288, 69001746, 69002204, 69002661, 69003118,
69003575, 69004032, 69004488, 69004944, 69005400, 69005855, 69006310,
69006765, 69007220, 69007674, 69008128, 69008582, 69009036, 69009489,
69009942, 69010395, 69010847, 69011299, 69011751, 69012203, 69012655,
69013106, 69013557, 69013602, 69013647, 69014096, 69014545, 69014993,
69015441, 69015889, 69016337, 69016785, 69017232, 69017679, 69018126,
69018573, 69019019, 69019465, 69019911, 69020357, 69020802, 69021247,
69021692, 69022137, 69022581, 69023025, 69023469, 69023913, 69024356,
69024798, 69025240, 69025682, 69026124, 69026565, 69027006, 69027447,
69027491, 69027929, 69028366, 69028803, 69029238, 69029673, 69030108,
69030543, 69030977, 69031410, 69031843, 69032275, 69032318, 69032361,
69032404, 69032447, 69032876, 69033305, 69033734, 69034163, 69034592,
69035020, 69035448, 69035876, 69036302, 69036727, 69037152, 69037577,
69038002, 69038427, 69038852, 69039276, 69039699, 69040121, 69040543,
69040964, 69041385, 69041806, 69042227, 69042648, 69042690, 69043109,
69043528, 69043947, 69044366, 69044785, 69045203, 69045619, 69046034,
69046449, 69046863, 69047275, 69047687, 69048099, 69048511, 69048923,
69049335, 69049746, 69050157, 69050198, 69050239, 69050280, 69050689,
69051098, 69051507, 69051916, 69052323, 69052730, 69053137, 69053544,
69053950, 69054356, 69054761, 69055166, 69055570, 69055974, 69056377,
69056780, 69057183, 69057586, 69057989, 69058392, 69058795, 69059197,
69059599, 69060000, 69060401, 69060802, 69061203, 69061600, 69061997,
69062394, 69062790, 69063186, 69063582, 69063978, 69064373, 69064768,
69065163, 69065558, 69065953, 69066348, 69066742, 69067136, 69067530,
69067924, 69068317, 69068710, 69069102, 69069493, 69069884, 69070275,
69070314, 69070353, 69070392, 69070431, 69070820, 69071209, 69071597,
69071985, 69072373, 69072760, 69073146, 69073531, 69073916, 69074301,
69074685, 69075069, 69075453, 69075836, 69076219, 69076602, 69076984,
69077365, 69077746, 69078127, 69078165, 69078203, 69078241, 69078620,
69078999, 69079378, 69079757, 69080136, 69080514, 69080892, 69081270,
69081648, 69082026, 69082404, 69082782, 69083160, 69083538, 69083915,
69084292, 69084669, 69085046, 69085422, 69085798, 69086174, 69086550,
69086925, 69087300, 69087675, 69088050, 69088424, 69088798, 69089172,
69089545, 69089918, 69090291, 69090664, 69091037, 69091409, 69091781,
69092153, 69092525, 69092896, 69093267, 69093638, 69094009, 69094046,
69094083, 69094120, 69094157, 69094194, 69094231, 69094600, 69094969,
69095337, 69095705, 69096073, 69096441, 69096809, 69097177, 69097545,
69097912, 69098279, 69098645, 69099011, 69099377, 69099742, 69100107,
69100472, 69100837, 69101201, 69101565, 69101928, 69102291, 69102654,
69103016, 69103378, 69103740, 69104101, 69104462, 69104823, 69105184,
69105220, 69105256, 69105292, 69105651, 69106010, 69106369, 69106728,
69107087, 69107446, 69107805, 69108163, 69108521, 69108879, 69109237,
69109595, 69109952, 69110309, 69110666, 69111023, 69111380, 69111736,
69112092, 69112448, 69112803, 69113158, 69113513, 69113867, 69114221,
69114574, 69114927, 69115280, 69115633, 69115985, 69116337, 69116689,
69117040, 69117075, 69117110, 69117145, 69117180, 69117215, 69117564,
69117913, 69118262, 69118611, 69118959, 69119307, 69119654, 69120001,
69120348, 69120695, 69121041, 69121387, 69121733, 69122078, 69122422,
69122766, 69123109, 69123452, 69123794, 69124136, 69124478, 69124819,
69125160, 69125501, 69125842, 69126183, 69126217, 69126251, 69126285,
69126319, 69126353, 69126692, 69127031, 69127370, 69127709, 69128047,
69128385, 69128723, 69129060, 69129397, 69129734, 69130070, 69130406,
69130742, 69131077, 69131411, 69131745, 69132079, 69132413, 69132746,
69133079, 69133411, 69133743, 69134075, 69134406, 69134737, 69135068,
69135101, 69135134, 69135167, 69135200, 69135233, 69135266, 69135299,
69135628, 69135957, 69136286, 69136615, 69136944, 69137272, 69137600,
69137927, 69138254, 69138581, 69138908, 69139234, 69139560, 69139886,
69140212, 69140538, 69140863, 69141188, 69141513, 69141838, 69142162,
69142486, 69142810, 69143134, 69143457, 69143780, 69144103, 69144425,
69144747, 69145069, 69145391, 69145713, 69146034, 69146355, 69146676,
69146997, 69147029, 69147061, 69147093, 69147125, 69147157, 69147476,
69147794, 69148112, 69148430, 69148748, 69149066, 69149383, 69149700,
69150017, 69150334, 69150650, 69150966, 69151281, 69151596, 69151911,
69152226, 69152540, 69152854, 69153168, 69153482, 69153796, 69154110,
69154422, 69154734, 69155046, 69155358, 69155670, 69155981, 69156292,
69156603, 69156634, 69156665, 69156696, 69157005, 69157314, 69157623,
69157932, 69158240, 69158548, 69158856, 69159164, 69159472, 69159780,
69160087, 69160394, 69160701, 69161007, 69161313, 69161619, 69161925,
69162230, 69162535, 69162840, 69163145, 69163449, 69163753, 69164057,
69164360, 69164663, 69164966, 69165269, 69165572, 69165875, 69166177,
69166479, 69166781, 69167083, 69167385, 69167687, 69167989, 69168291,
69168593, 69168895, 69169196, 69169497, 69169798, 69170099, 69170400,
69170701, 69170704, 69170707, 69170710, 69171009, 69171308, 69171607,
69171905, 69172203, 69172501, 69172798, 69173095, 69173392, 69173688,
69173984, 69174280, 69174576, 69174872, 69175168, 69175463, 69175758,
69176053, 69176348, 69176643, 69176938, 69177233, 69177528, 69177823,
69178117, 69178411, 69178704, 69178997, 69179290, 69179583, 69179876,
69180168, 69180460, 69180752, 69181044, 69181335, 69181364, 69181393,
69181682, 69181971, 69182260, 69182548, 69182836, 69183124, 69183412,
69183700, 69183988, 69184276, 69184563, 69184850, 69185137, 69185424,
69185711, 69185998, 69186284, 69186570, 69186856, 69187142, 69187428,
69187713, 69187998, 69188283, 69188568, 69188853, 69189138, 69189423,
69189708, 69189993, 69190277, 69190561, 69190845, 69191128, 69191411,
69191693, 69191975, 69192257, 69192539, 69192820, 69193101, 69193382,
69193663, 69193944, 69194225, 69194506, 69194534, 69194562, 69194590,
69194869, 69195148, 69195427, 69195706, 69195985, 69196264, 69196542,
69196820, 69197098, 69197376, 69197653, 69197930, 69198207, 69198484,
69198761, 69199038, 69199314, 69199590, 69199866, 69200140, 69200414,
69200688, 69200962, 69201235, 69201508, 69201781, 69202054, 69202326,
69202598, 69202870, 69203142, 69203414, 69203686, 69203958, 69204230,
69204501, 69204772, 69205043, 69205314, 69205341, 69205368, 69205395,
69205422, 69205449, 69205718, 69205987, 69206256, 69206525, 69206794,
69207063, 69207332, 69207601, 69207869, 69208137, 69208405, 69208672,
69208939, 69209206, 69209473, 69209740, 69210006, 69210272, 69210538,
69210804, 69211070, 69211336, 69211602, 69211867, 69212132, 69212397,
69212662, 69212927, 69213191, 69213455, 69213719, 69213983, 69214247,
69214511, 69214775, 69215038, 69215301, 69215564, 69215827, 69216089,
69216351, 69216613, 69216875, 69217136, 69217397, 69217658, 69217919,
69218180, 69218441, 69218702, 69218963, 69218989, 69219015, 69219041,
69219067, 69219093, 69219352, 69219611, 69219870, 69220129, 69220387,
69220645, 69220903, 69221161, 69221419, 69221677, 69221935, 69222193,
69222450, 69222707, 69222964, 69223221, 69223478, 69223735, 69223991,
69224247, 69224502, 69224757, 69225012, 69225267, 69225522, 69225777,
69226032, 69226287, 69226542, 69226797, 69227051, 69227305, 69227559,
69227812, 69228065, 69228318, 69228571, 69228824, 69229077, 69229330,
69229582, 69229834, 69230086, 69230338, 69230590, 69230842, 69231094,
69231346, 69231597, 69231848, 69232099, 69232350, 69232601, 69232852,
69232877, 69232902, 69232927, 69232952, 69232977, 69233002, 69233251,
69233500, 69233748, 69233996, 69234244, 69234492, 69234739, 69234986,
69235233, 69235480, 69235727, 69235974, 69236220, 69236466, 69236711,
69236956, 69237201, 69237446, 69237690, 69237934, 69238178, 69238421,
69238663, 69238905, 69239147, 69239389, 69239631, 69239873, 69240114,
69240355, 69240596, 69240837, 69241078, 69241319, 69241560, 69241801,
69241825, 69241849, 69241873, 69241897, 69241921, 69241945, 69242184,
69242423, 69242662, 69242901, 69243140, 69243379, 69243618, 69243856,
69244094, 69244332, 69244570, 69244808, 69245045, 69245282, 69245519,
69245756, 69245992, 69246228, 69246463, 69246698, 69246933, 69247168,
69247403, 69247637, 69247871, 69248105, 69248339, 69248573, 69248807,
69249041, 69249275, 69249509, 69249742, 69249975, 69250208, 69250441,
69250674, 69250907, 69251140, 69251372, 69251604, 69251836, 69252068,
69252300, 69252532, 69252764, 69252996, 69253228, 69253460, 69253692,
69253924, 69254155, 69254386, 69254617, 69254848, 69255079, 69255310,
69255541, 69255772, 69256003, 69256234, 69256257, 69256280, 69256303,
69256326, 69256349, 69256372, 69256395, 69256418, 69256647, 69256876,
69257105, 69257333, 69257561, 69257789, 69258016, 69258243, 69258470,
69258697, 69258924, 69259150, 69259376, 69259602, 69259828, 69260054,
69260279, 69260504, 69260729, 69260954, 69261179, 69261404, 69261629,
69261853, 69262077, 69262301, 69262525, 69262749, 69262973, 69263196,
69263419, 69263642, 69263865, 69264088, 69264311, 69264534, 69264757,
69264979, 69265201, 69265423, 69265645, 69265867, 69266089, 69266311,
69266533, 69266754, 69266975, 69267196, 69267417, 69267439, 69267461,
69267483, 69267505, 69267527, 69267549, 69267768, 69267987, 69268206,
69268424, 69268642, 69268860, 69269077, 69269294, 69269511, 69269728,
69269944, 69270160, 69270376, 69270592, 69270808, 69271024, 69271240,
69271456, 69271672, 69271887, 69272102, 69272317, 69272532, 69272747,
69272962, 69273176, 69273390, 69273604, 69273818, 69274032, 69274246,
69274460, 69274674, 69274888, 69275101, 69275314, 69275527, 69275740,
69275953, 69276166, 69276379, 69276592, 69276805, 69277018, 69277231,
69277443, 69277655, 69277867, 69278078, 69278289, 69278500, 69278711,
69278922, 69279133, 69279344, 69279555, 69279766, 69279977, 69279998,
69280019, 69280040, 69280061, 69280082, 69280103, 69280312, 69280521,
69280730, 69280939, 69281148, 69281356, 69281564, 69281772, 69281980,
69282188, 69282396, 69282604, 69282812, 69283020, 69283228, 69283435,
69283642, 69283849, 69284056, 69284263, 69284470, 69284676, 69284882,
69285087, 69285291, 69285495, 69285698, 69285901, 69286104, 69286307,
69286510, 69286713, 69286915, 69287117, 69287319, 69287521, 69287723,
69287925, 69288127, 69288329, 69288531, 69288732, 69288933, 69289134,
69289335, 69289536, 69289737, 69289938, 69290139, 69290141, 69290143,
69290342, 69290541, 69290740, 69290939, 69291138, 69291337, 69291535,
69291733, 69291931, 69292128, 69292325, 69292522, 69292719, 69292916,
69293113, 69293310, 69293507, 69293703, 69293899, 69294095, 69294291,
69294487, 69294683, 69294879, 69295075, 69295270, 69295465, 69295660,
69295855, 69296050, 69296245, 69296440, 69296635, 69296830, 69297024,
69297218, 69297412, 69297606, 69297800, 69297994, 69298188, 69298381,
69298574, 69298767, 69298960, 69299153, 69299346, 69299539, 69299731,
69299923, 69300115, 69300307, 69300498, 69300689, 69300880, 69301071,
69301262, 69301453, 69301644, 69301835, 69302026, 69302217, 69302236,
69302255, 69302274, 69302293, 69302312, 69302501, 69302690, 69302879,
69303068, 69303257, 69303446, 69303635, 69303823, 69304011, 69304199,
69304387, 69304575, 69304763, 69304951, 69305139, 69305327, 69305514,
69305701, 69305888, 69306075, 69306262, 69306449, 69306636, 69306823,
69307009, 69307195, 69307381, 69307567, 69307753, 69307939, 69308125,
69308310, 69308495, 69308680, 69308865, 69309050, 69309235, 69309420,
69309604, 69309788, 69309972, 69310156, 69310340, 69310524, 69310708,
69310892, 69311076, 69311260, 69311444, 69311628, 69311811, 69311994,
69312177, 69312360, 69312543, 69312726, 69312909, 69313092, 69313275,
69313458, 69313641, 69313823, 69314005, 69314187, 69314369, 69314551,
69314733, 69314915, 69315097, 69315279, 69315460, 69315478, 69315496,
69315514, 69315532, 69315550, 69315568, 69315586, 69315604, 69315783,
69315962, 69316141, 69316320, 69316499, 69316678, 69316857, 69317036,
69317215, 69317393, 69317571, 69317749, 69317927, 69318105, 69318283,
69318461, 69318639, 69318817, 69318995, 69319173, 69319351, 69319528,
69319705, 69319882, 69320059, 69320236, 69320413, 69320590, 69320767,
69320944, 69321121, 69321298, 69321475, 69321651, 69321827, 69322003,
69322178, 69322353, 69322528, 69322703, 69322878, 69323053, 69323228,
69323403, 69323578, 69323752, 69323926, 69324100, 69324274, 69324448,
69324622, 69324796, 69324970, 69325144, 69325318, 69325491, 69325664,
69325837, 69326010, 69326183, 69326356, 69326529, 69326702, 69326875,
69327048, 69327221, 69327393, 69327565, 69327737, 69327909, 69328081,
69328253, 69328425, 69328596, 69328767, 69328938, 69329109, 69329280,
69329451, 69329622, 69329793, 69329964, 69329981, 69329998, 69330015,
69330032, 69330049, 69330066, 69330083, 69330100, 69330117, 69330286,
69330455, 69330624, 69330793, 69330962, 69331131, 69331300, 69331468,
69331636, 69331804, 69331972, 69332139, 69332306, 69332473, 69332640,
69332807, 69332974, 69333140, 69333306, 69333472, 69333638, 69333804,
69333970, 69334136, 69334301, 69334466, 69334631, 69334796, 69334961,
69335126, 69335291, 69335456, 69335621, 69335786, 69335951, 69336116,
69336281, 69336446, 69336611, 69336775, 69336939, 69337103, 69337267,
69337431, 69337595, 69337759, 69337922, 69338085, 69338248, 69338411,
69338574, 69338736, 69338898, 69339060, 69339222, 69339384, 69339546,
69339708, 69339870, 69340032, 69340194, 69340356, 69340518, 69340680,
69340841, 69341002, 69341163, 69341324, 69341485, 69341646, 69341807,
69341968, 69342129, 69342290, 69342306, 69342322, 69342338, 69342354,
69342370, 69342386, 69342402, 69342418, 69342434, 69342593, 69342752,
69342911, 69343070, 69343229, 69343388, 69343547, 69343705, 69343863,
69344021, 69344179, 69344337, 69344495, 69344652, 69344809, 69344966,
69345123, 69345280, 69345437, 69345594, 69345751, 69345908, 69346065,
69346222, 69346378, 69346534, 69346690, 69346846, 69347002, 69347158,
69347314, 69347470, 69347626, 69347782, 69347938, 69348094, 69348249,
69348404, 69348559, 69348714, 69348869, 69349024, 69349179, 69349334,
69349489, 69349644, 69349798, 69349952, 69350106, 69350260, 69350414,
69350568, 69350722, 69350876, 69351030, 69351184, 69351338, 69351492,
69351646, 69351800, 69351953, 69352106, 69352259, 69352412, 69352565,
69352718, 69352871, 69353023, 69353175, 69353327, 69353479, 69353631,
69353783, 69353935, 69354087, 69354238, 69354389, 69354540, 69354691,
69354842, 69354993, 69355144, 69355159, 69355174, 69355189, 69355204,
69355219, 69355234, 69355249, 69355264, 69355279, 69355428, 69355577,
69355726, 69355875, 69356024, 69356173, 69356322, 69356471, 69356620,
69356769, 69356918, 69357067, 69357216, 69357365, 69357514, 69357663,
69357811, 69357959, 69358107, 69358255, 69358403, 69358551, 69358699,
69358847, 69358994, 69359141, 69359288, 69359435, 69359582, 69359729,
69359876, 69360023, 69360170, 69360317, 69360464, 69360611, 69360758,
69360905, 69361052, 69361199, 69361346, 69361492, 69361638, 69361784,
69361930, 69362076, 69362222, 69362368, 69362514, 69362659, 69362804,
69362949, 69363094, 69363239, 69363384, 69363529, 69363674, 69363819,
69363964, 69364109, 69364254, 69364399, 69364543, 69364687, 69364831,
69364975, 69365119, 69365263, 69365407, 69365551, 69365695, 69365839,
69365983, 69366126, 69366269, 69366412, 69366555, 69366698, 69366841,
69366984, 69367127, 69367269, 69367411, 69367553, 69367695, 69367837,
69367979, 69368121, 69368263, 69368405, 69368547, 69368688, 69368829,
69368970, 69369111, 69369252, 69369393, 69369534, 69369675, 69369816,
69369957, 69370098, 69370112, 69370126, 69370140, 69370154, 69370168,
69370182, 69370196, 69370335, 69370474, 69370613, 69370752, 69370891,
69371030, 69371169, 69371308, 69371447, 69371585, 69371723, 69371861,
69371999, 69372137, 69372275, 69372412, 69372549, 69372686, 69372823,
69372960, 69373097, 69373234, 69373371, 69373508, 69373645, 69373782,
69373919, 69374056, 69374193, 69374330, 69374467, 69374604, 69374741,
69374878, 69375015, 69375151, 69375287, 69375423, 69375559, 69375695,
69375831, 69375967, 69376103, 69376239, 69376375, 69376511, 69376646,
69376781, 69376916, 69377051, 69377186, 69377321, 69377456, 69377591,
69377726, 69377861, 69377996, 69378131, 69378266, 69378400, 69378534,
69378668, 69378802, 69378936, 69379070, 69379204, 69379338, 69379472,
69379605, 69379738, 69379871, 69380004, 69380137, 69380270, 69380403,
69380536, 69380669, 69380802, 69380935, 69381067, 69381199, 69381331,
69381463, 69381595, 69381727, 69381859, 69381990, 69382121, 69382252,
69382383, 69382514, 69382645, 69382776, 69382907, 69383038, 69383051,
69383064, 69383077, 69383090, 69383103, 69383116, 69383129, 69383142,
69383155, 69383168, 69383181, 69383194, 69383207, 69383336, 69383465,
69383594, 69383723, 69383852, 69383981, 69384110, 69384239, 69384368,
69384497, 69384625, 69384753, 69384881, 69385009, 69385137, 69385265,
69385392, 69385519, 69385646, 69385773, 69385900, 69386027, 69386154,
69386281, 69386408, 69386535, 69386662, 69386789, 69386915, 69387041,
69387167, 69387293, 69387419, 69387545, 69387671, 69387797, 69387923,
69388049, 69388175, 69388301, 69388427, 69388553, 69388678, 69388803,
69388928, 69389053, 69389178, 69389303, 69389428, 69389553, 69389678,
69389803, 69389928, 69390053, 69390178, 69390303, 69390428, 69390553,
69390678, 69390803, 69390927, 69391051, 69391175, 69391299, 69391423,
69391547, 69391671, 69391795, 69391919, 69392042, 69392165, 69392288,
69392411, 69392534, 69392657, 69392780, 69392903, 69393026, 69393149,
69393272, 69393395, 69393518, 69393640, 69393762, 69393884, 69394006,
69394128, 69394250, 69394372, 69394494, 69394616, 69394738, 69394860,
69394982, 69395104, 69395225, 69395346, 69395467, 69395588, 69395709,
69395830, 69395951, 69396072, 69396193, 69396314, 69396435, 69396556,
69396677, 69396798, 69396810, 69396822, 69396834, 69396846, 69396858,
69396870, 69396989, 69397108, 69397227, 69397346, 69397465, 69397584,
69397703, 69397822, 69397941, 69398060, 69398179, 69398297, 69398415,
69398533, 69398651, 69398769, 69398887, 69399005, 69399123, 69399241,
69399359, 69399477, 69399595, 69399712, 69399829, 69399946, 69400063,
69400180, 69400297, 69400414, 69400531, 69400648, 69400765, 69400882,
69400998, 69401114, 69401230, 69401346, 69401462, 69401578, 69401694,
69401810, 69401926, 69402042, 69402158, 69402273, 69402388, 69402503,
69402618, 69402733, 69402848, 69402963, 69403078, 69403193, 69403308,
69403422, 69403536, 69403650, 69403764, 69403878, 69403992, 69404106,
69404220, 69404334, 69404447, 69404560, 69404673, 69404786, 69404899,
69405012, 69405125, 69405238, 69405351, 69405464, 69405577, 69405690,
69405803, 69405915, 69406027, 69406139, 69406251, 69406363, 69406475,
69406587, 69406699, 69406811, 69406923, 69407035, 69407147, 69407259,
69407371, 69407483, 69407595, 69407707, 69407818, 69407929, 69408040,
69408151, 69408262, 69408373, 69408484, 69408595, 69408706, 69408817,
69408928, 69409039, 69409150, 69409161, 69409172, 69409183, 69409194,
69409205, 69409216, 69409227, 69409238, 69409347, 69409456, 69409565,
69409674, 69409783, 69409892, 69410001, 69410110, 69410219, 69410328,
69410437, 69410546, 69410655, 69410764, 69410873, 69410982, 69411091,
69411200, 69411309, 69411418, 69411526, 69411634, 69411742, 69411850,
69411958, 69412066, 69412174, 69412282, 69412390, 69412498, 69412606,
69412714, 69412822, 69412930, 69413037, 69413144, 69413251, 69413358,
69413465, 69413572, 69413679, 69413786, 69413893, 69414000, 69414106,
69414212, 69414318, 69414424, 69414530, 69414636, 69414742, 69414848,
69414954, 69415060, 69415166, 69415272, 69415378, 69415483, 69415588,
69415693, 69415798, 69415903, 69416008, 69416113, 69416218, 69416323,
69416428, 69416533, 69416638, 69416743, 69416847, 69416951, 69417055,
69417159, 69417263, 69417367, 69417471, 69417575, 69417679, 69417783,
69417887, 69417991, 69418095, 69418198, 69418301, 69418404, 69418507,
69418610, 69418713, 69418816, 69418919, 69419022, 69419125, 69419228,
69419331, 69419433, 69419535, 69419637, 69419739, 69419841, 69419943,
69420045, 69420147, 69420249, 69420351, 69420453, 69420555, 69420657,
69420759, 69420860, 69420961, 69421062, 69421163, 69421264, 69421365,
69421466, 69421567, 69421668, 69421769, 69421870, 69421971, 69422072,
69422173, 69422274, 69422375, 69422376, 69422377, 69422378, 69422379,
69422380, 69422381, 69422382, 69422383, 69422384, 69422385, 69422386,
69422387, 69422388, 69422389, 69422390, 69422391, 69422490, 69422589,
69422688, 69422787, 69422886, 69422985, 69423084, 69423183, 69423282,
69423381, 69423480, 69423579, 69423678, 69423777, 69423876, 69423975,
69424073, 69424171, 69424269, 69424367, 69424465, 69424563, 69424661,
69424759, 69424857, 69424954, 69425051, 69425148, 69425245, 69425342,
69425439, 69425536, 69425633, 69425730, 69425827, 69425924, 69426021,
69426118, 69426214, 69426310, 69426406, 69426502, 69426598, 69426694,
69426790, 69426886, 69426982, 69427078, 69427174, 69427270, 69427366,
69427462, 69427558, 69427653, 69427748, 69427843, 69427938, 69428033,
69428128, 69428223, 69428318, 69428413, 69428508, 69428603, 69428698,
69428793, 69428888, 69428982, 69429076, 69429170, 69429264, 69429358,
69429452, 69429546, 69429640, 69429734, 69429828, 69429922, 69430016,
69430110, 69430204, 69430298, 69430392, 69430486, 69430580, 69430673,
69430766, 69430859, 69430952, 69431045, 69431138, 69431231, 69431324,
69431417, 69431510, 69431603, 69431696, 69431789, 69431882, 69431975,
69432068, 69432161, 69432254, 69432347, 69432439, 69432531, 69432623,
69432715, 69432807, 69432899, 69432991, 69433083, 69433175, 69433267,
69433359, 69433450, 69433541, 69433632, 69433723, 69433814, 69433905,
69433996, 69434087, 69434178, 69434269, 69434360, 69434451, 69434542,
69434633, 69434724, 69434733, 69434742, 69434751, 69434760, 69434769,
69434778, 69434787, 69434796, 69434805, 69434814, 69434823, 69434912,
69435001, 69435090, 69435179, 69435268, 69435357, 69435446, 69435535,
69435624, 69435713, 69435801, 69435889, 69435977, 69436065, 69436153,
69436241, 69436329, 69436417, 69436505, 69436593, 69436681, 69436769,
69436857, 69436944, 69437031, 69437118, 69437205, 69437292, 69437379,
69437466, 69437553, 69437640, 69437727, 69437814, 69437901, 69437988,
69438075, 69438161, 69438247, 69438333, 69438419, 69438505, 69438591,
69438677, 69438763, 69438849, 69438935, 69439021, 69439107, 69439193,
69439278, 69439363, 69439448, 69439533, 69439618, 69439703, 69439788,
69439873, 69439958, 69440043, 69440128, 69440213, 69440298, 69440382,
69440466, 69440550, 69440634, 69440718, 69440802, 69440886, 69440970,
69441054, 69441138, 69441222, 69441306, 69441390, 69441474, 69441557,
69441640, 69441723, 69441806, 69441889, 69441972, 69442055, 69442138,
69442221, 69442304, 69442387, 69442470, 69442553, 69442636, 69442719,
69442802, 69442885, 69442967, 69443049, 69443131, 69443213, 69443295,
69443377, 69443459, 69443541, 69443623, 69443705, 69443787, 69443869,
69443951, 69444033, 69444115, 69444197, 69444279, 69444361, 69444443,
69444524, 69444605, 69444686, 69444767, 69444848, 69444929, 69445010,
69445091, 69445172, 69445253, 69445334, 69445415, 69445496, 69445577,
69445585, 69445593, 69445601, 69445609, 69445617, 69445625, 69445633,
69445641, 69445649, 69445657, 69445665, 69445673, 69445681, 69445689,
69445697, 69445705, 69445713, 69445721, 69445729, 69445737, 69445816,
69445895, 69445974, 69446053, 69446132, 69446211, 69446290, 69446369,
69446448, 69446527, 69446606, 69446685, 69446764, 69446843, 69446922,
69447001, 69447080, 69447159, 69447238, 69447317, 69447396, 69447475,
69447553, 69447631, 69447709, 69447787, 69447865, 69447943, 69448021,
69448099, 69448177, 69448255, 69448333, 69448411, 69448489, 69448567,
69448645, 69448722, 69448799, 69448876, 69448953, 69449030, 69449107,
69449184, 69449261, 69449338, 69449415, 69449492, 69449569, 69449646,
69449723, 69449800, 69449876, 69449952, 69450028, 69450104, 69450180,
69450256, 69450332, 69450408, 69450484, 69450560, 69450636, 69450712,
69450788, 69450864, 69450940, 69451016, 69451092, 69451168, 69451244,
69451320, 69451395, 69451470, 69451545, 69451620, 69451695, 69451770,
69451845, 69451920, 69451995, 69452070, 69452145, 69452220, 69452295,
69452370, 69452445, 69452520, 69452595, 69452670, 69452745, 69452820,
69452895, 69452970, 69453044, 69453118, 69453192, 69453266, 69453340,
69453414, 69453488, 69453562, 69453636, 69453710, 69453784, 69453858,
69453932, 69454006, 69454080, 69454154, 69454228, 69454302, 69454376,
69454450, 69454524, 69454598, 69454671, 69454744, 69454817, 69454890,
69454963, 69455036, 69455109, 69455182, 69455255, 69455328, 69455401,
69455474, 69455547, 69455620, 69455693, 69455766, 69455839, 69455912,
69455985, 69456058, 69456130, 69456202, 69456274, 69456346, 69456418,
69456490, 69456562, 69456634, 69456706, 69456778, 69456850, 69456922,
69456994, 69457066, 69457138, 69457210, 69457281, 69457352, 69457423,
69457494, 69457565, 69457636, 69457707, 69457778, 69457849, 69457920,
69457991, 69458062, 69458133, 69458204, 69458275, 69458346, 69458417,
69458488, 69458559, 69458630, 69458701, 69458772, 69458843, 69458850,
69458857, 69458864, 69458871, 69458878, 69458885, 69458892, 69458899,
69458906, 69458913, 69458920, 69458927, 69458934, 69458941, 69459010,
69459079, 69459148, 69459217, 69459286, 69459355, 69459424, 69459493,
69459562, 69459631, 69459700, 69459769, 69459838, 69459907, 69459976,
69460045, 69460114, 69460183, 69460252, 69460321, 69460390, 69460459,
69460528, 69460596, 69460664, 69460732, 69460800, 69460868, 69460936};
System.arraycopy(temp, 0, prob, 0, temp.length);
}
private static void populateProb2() {
int[] temp = new int[] {
69461004, 69461072, 69461140, 69461208, 69461276, 69461344, 69461412,
69461480, 69461548, 69461616, 69461684, 69461751, 69461818, 69461885,
69461952, 69462019, 69462086, 69462153, 69462220, 69462287, 69462354,
69462421, 69462488, 69462555, 69462622, 69462689, 69462756, 69462823,
69462889, 69462955, 69463021, 69463087, 69463153, 69463219, 69463285,
69463351, 69463417, 69463483, 69463549, 69463615, 69463681, 69463747,
69463813, 69463879, 69463945, 69464011, 69464077, 69464143, 69464209,
69464275, 69464341, 69464407, 69464473, 69464539, 69464605, 69464670,
69464735, 69464800, 69464865, 69464930, 69464995, 69465060, 69465125,
69465190, 69465255, 69465320, 69465385, 69465450, 69465515, 69465580,
69465645, 69465710, 69465775, 69465840, 69465905, 69465969, 69466033,
69466097, 69466161, 69466225, 69466289, 69466353, 69466417, 69466481,
69466545, 69466609, 69466673, 69466737, 69466801, 69466864, 69466927,
69466990, 69467053, 69467116, 69467179, 69467242, 69467305, 69467368,
69467431, 69467494, 69467557, 69467620, 69467683, 69467746, 69467809,
69467872, 69467935, 69467998, 69468061, 69468124, 69468187, 69468250,
69468313, 69468375, 69468437, 69468499, 69468561, 69468623, 69468685,
69468747, 69468809, 69468871, 69468933, 69468995, 69469057, 69469119,
69469181, 69469243, 69469305, 69469366, 69469427, 69469488, 69469549,
69469610, 69469671, 69469732, 69469793, 69469854, 69469915, 69469976,
69470037, 69470098, 69470159, 69470220, 69470281, 69470342, 69470403,
69470464, 69470525, 69470586, 69470647, 69470708, 69470714, 69470720,
69470726, 69470732, 69470738, 69470744, 69470750, 69470756, 69470762,
69470768, 69470774, 69470780, 69470786, 69470792, 69470798, 69470804,
69470810, 69470816, 69470822, 69470828, 69470834, 69470840, 69470846,
69470852, 69470858, 69470864, 69470870, 69470876, 69470882, 69470888,
69470894, 69470900, 69470959, 69471018, 69471077, 69471136, 69471195,
69471254, 69471313, 69471372, 69471431, 69471490, 69471549, 69471608,
69471667, 69471726, 69471785, 69471844, 69471903, 69471962, 69472021,
69472080, 69472139, 69472197, 69472255, 69472313, 69472371, 69472429,
69472487, 69472545, 69472603, 69472661, 69472719, 69472777, 69472835,
69472893, 69472951, 69473009, 69473067, 69473125, 69473183, 69473241,
69473299, 69473357, 69473415, 69473473, 69473531, 69473589, 69473647,
69473705, 69473762, 69473819, 69473876, 69473933, 69473990, 69474047,
69474104, 69474161, 69474218, 69474275, 69474332, 69474389, 69474446,
69474503, 69474560, 69474617, 69474674, 69474731, 69474788, 69474845,
69474902, 69474959, 69475016, 69475072, 69475128, 69475184, 69475240,
69475296, 69475352, 69475408, 69475464, 69475520, 69475576, 69475632,
69475688, 69475744, 69475800, 69475856, 69475912, 69475968, 69476024,
69476080, 69476136, 69476192, 69476248, 69476304, 69476360, 69476416,
69476471, 69476526, 69476581, 69476636, 69476691, 69476746, 69476801,
69476856, 69476911, 69476966, 69477021, 69477076, 69477131, 69477186,
69477241, 69477296, 69477351, 69477406, 69477461, 69477516, 69477571,
69477626, 69477681, 69477736, 69477791, 69477846, 69477901, 69477956,
69478010, 69478064, 69478118, 69478172, 69478226, 69478280, 69478334,
69478388, 69478442, 69478496, 69478550, 69478604, 69478658, 69478712,
69478766, 69478820, 69478874, 69478928, 69478982, 69479036, 69479090,
69479144, 69479197, 69479250, 69479303, 69479356, 69479409, 69479462,
69479515, 69479568, 69479621, 69479674, 69479727, 69479780, 69479833,
69479886, 69479939, 69479992, 69480045, 69480098, 69480151, 69480204,
69480257, 69480310, 69480363, 69480416, 69480468, 69480520, 69480572,
69480624, 69480676, 69480728, 69480780, 69480832, 69480884, 69480936,
69480988, 69481040, 69481092, 69481144, 69481196, 69481248, 69481300,
69481352, 69481404, 69481456, 69481508, 69481560, 69481612, 69481664,
69481716, 69481768, 69481820, 69481872, 69481924, 69481976, 69482028,
69482080, 69482132, 69482184, 69482236, 69482288, 69482339, 69482390,
69482441, 69482492, 69482543, 69482594, 69482645, 69482696, 69482747,
69482798, 69482849, 69482900, 69482951, 69483002, 69483053, 69483104,
69483155, 69483206, 69483257, 69483308, 69483359, 69483410, 69483461,
69483512, 69483563, 69483614, 69483665, 69483716, 69483767, 69483772,
69483777, 69483782, 69483787, 69483792, 69483797, 69483802, 69483807,
69483812, 69483817, 69483822, 69483827, 69483832, 69483837, 69483842,
69483847, 69483852, 69483857, 69483862, 69483867, 69483872, 69483877,
69483926, 69483975, 69484024, 69484073, 69484122, 69484171, 69484220,
69484269, 69484318, 69484367, 69484416, 69484465, 69484514, 69484563,
69484612, 69484661, 69484710, 69484759, 69484808, 69484857, 69484906,
69484955, 69485004, 69485053, 69485102, 69485151, 69485200, 69485249,
69485298, 69485347, 69485396, 69485445, 69485494, 69485543, 69485592,
69485641, 69485690, 69485739, 69485788, 69485837, 69485886, 69485935,
69485984, 69486033, 69486082, 69486131, 69486180, 69486229, 69486278,
69486326, 69486374, 69486422, 69486470, 69486518, 69486566, 69486614,
69486662, 69486710, 69486758, 69486806, 69486854, 69486902, 69486950,
69486998, 69487046, 69487094, 69487142, 69487190, 69487238, 69487286,
69487333, 69487380, 69487427, 69487474, 69487521, 69487568, 69487615,
69487662, 69487709, 69487756, 69487803, 69487850, 69487897, 69487944,
69487991, 69488038, 69488085, 69488132, 69488179, 69488226, 69488273,
69488320, 69488366, 69488412, 69488458, 69488504, 69488550, 69488596,
69488642, 69488688, 69488734, 69488780, 69488826, 69488872, 69488918,
69488964, 69489010, 69489056, 69489102, 69489148, 69489194, 69489240,
69489286, 69489332, 69489378, 69489424, 69489470, 69489516, 69489562,
69489608, 69489654, 69489700, 69489746, 69489792, 69489837, 69489882,
69489927, 69489972, 69490017, 69490062, 69490107, 69490152, 69490197,
69490242, 69490287, 69490332, 69490377, 69490422, 69490467, 69490512,
69490557, 69490602, 69490647, 69490692, 69490737, 69490782, 69490827,
69490872, 69490917, 69490962, 69491007, 69491052, 69491097, 69491142,
69491187, 69491232, 69491277, 69491322, 69491367, 69491411, 69491455,
69491499, 69491543, 69491587, 69491631, 69491675, 69491719, 69491763,
69491807, 69491851, 69491895, 69491939, 69491983, 69492027, 69492071,
69492115, 69492159, 69492203, 69492247, 69492291, 69492335, 69492379,
69492423, 69492467, 69492511, 69492555, 69492599, 69492643, 69492686,
69492729, 69492772, 69492815, 69492858, 69492901, 69492944, 69492987,
69493030, 69493073, 69493116, 69493159, 69493202, 69493245, 69493288,
69493331, 69493374, 69493417, 69493460, 69493503, 69493546, 69493589,
69493632, 69493675, 69493718, 69493761, 69493804, 69493847, 69493890,
69493933, 69493976, 69494019, 69494062, 69494105, 69494148, 69494191,
69494234, 69494277, 69494320, 69494363, 69494406, 69494449, 69494492,
69494535, 69494577, 69494619, 69494661, 69494703, 69494745, 69494787,
69494829, 69494871, 69494913, 69494955, 69494997, 69495039, 69495081,
69495123, 69495165, 69495207, 69495249, 69495291, 69495333, 69495375,
69495417, 69495459, 69495501, 69495543, 69495585, 69495627, 69495669,
69495711, 69495753, 69495795, 69495837, 69495879, 69495921, 69495963,
69496005, 69496047, 69496089, 69496131, 69496172, 69496213, 69496254,
69496295, 69496336, 69496377, 69496418, 69496459, 69496500, 69496541,
69496582, 69496623, 69496664, 69496705, 69496746, 69496787, 69496828,
69496869, 69496910, 69496951, 69496992, 69497033, 69497074, 69497115,
69497156, 69497197, 69497238, 69497279, 69497320, 69497361, 69497402,
69497443, 69497484, 69497525, 69497566, 69497607, 69497648, 69497689,
69497693, 69497697, 69497701, 69497705, 69497709, 69497713, 69497717,
69497721, 69497725, 69497729, 69497733, 69497737, 69497741, 69497745,
69497749, 69497753, 69497757, 69497761, 69497765, 69497769, 69497773,
69497777, 69497781, 69497785, 69497789, 69497793, 69497797, 69497801,
69497805, 69497809, 69497813, 69497817, 69497821, 69497825, 69497829,
69497868, 69497907, 69497946, 69497985, 69498024, 69498063, 69498102,
69498141, 69498180, 69498219, 69498258, 69498297, 69498336, 69498375,
69498414, 69498453, 69498492, 69498531, 69498570, 69498609, 69498648,
69498687, 69498726, 69498765, 69498804, 69498843, 69498882, 69498921,
69498960, 69498999, 69499038, 69499077, 69499116, 69499155, 69499193,
69499231, 69499269, 69499307, 69499345, 69499383, 69499421, 69499459,
69499497, 69499535, 69499573, 69499611, 69499649, 69499687, 69499725,
69499763, 69499801, 69499839, 69499877, 69499915, 69499953, 69499991,
69500029, 69500067, 69500105, 69500143, 69500181, 69500219, 69500257,
69500295, 69500333, 69500371, 69500409, 69500447, 69500484, 69500521,
69500558, 69500595, 69500632, 69500669, 69500706, 69500743, 69500780,
69500817, 69500854, 69500891, 69500928, 69500965, 69501002, 69501039,
69501076, 69501113, 69501150, 69501187, 69501224, 69501261, 69501298,
69501335, 69501372, 69501409, 69501446, 69501483, 69501520, 69501557,
69501594, 69501631, 69501667, 69501703, 69501739, 69501775, 69501811,
69501847, 69501883, 69501919, 69501955, 69501991, 69502027, 69502063,
69502099, 69502135, 69502171, 69502207, 69502243, 69502279, 69502315,
69502351, 69502387, 69502423, 69502459, 69502495, 69502531, 69502567,
69502603, 69502639, 69502675, 69502711, 69502747, 69502783, 69502819,
69502855, 69502891, 69502927, 69502963, 69502999, 69503035, 69503071,
69503107, 69503143, 69503179, 69503214, 69503249, 69503284, 69503319,
69503354, 69503389, 69503424, 69503459, 69503494, 69503529, 69503564,
69503599, 69503634, 69503669, 69503704, 69503739, 69503774, 69503809,
69503844, 69503879, 69503914, 69503949, 69503984, 69504019, 69504054,
69504089, 69504124, 69504159, 69504194, 69504229, 69504264, 69504299,
69504334, 69504369, 69504404, 69504439, 69504474, 69504509, 69504544,
69504579, 69504614, 69504649, 69504684, 69504719, 69504754, 69504789,
69504824, 69504859, 69504894, 69504929, 69504964, 69504999, 69505034,
69505068, 69505102, 69505136, 69505170, 69505204, 69505238, 69505272,
69505306, 69505340, 69505374, 69505408, 69505442, 69505476, 69505510,
69505544, 69505578, 69505612, 69505646, 69505680, 69505714, 69505748,
69505782, 69505816, 69505850, 69505884, 69505918, 69505952, 69505986,
69506020, 69506054, 69506088, 69506122, 69506156, 69506190, 69506224,
69506258, 69506292, 69506326, 69506360, 69506394, 69506427, 69506460,
69506493, 69506526, 69506559, 69506592, 69506625, 69506658, 69506691,
69506724, 69506757, 69506790, 69506823, 69506856, 69506889, 69506922,
69506955, 69506988, 69507021, 69507054, 69507087, 69507120, 69507153,
69507186, 69507219, 69507252, 69507285, 69507318, 69507351, 69507384,
69507417, 69507450, 69507483, 69507516, 69507549, 69507582, 69507615,
69507648, 69507681, 69507714, 69507747, 69507780, 69507813, 69507846,
69507879, 69507912, 69507945, 69507978, 69508011, 69508044, 69508077,
69508110, 69508143, 69508176, 69508209, 69508242, 69508275, 69508308,
69508341, 69508373, 69508405, 69508437, 69508469, 69508501, 69508533,
69508565, 69508597, 69508629, 69508661, 69508693, 69508725, 69508757,
69508789, 69508821, 69508853, 69508885, 69508917, 69508949, 69508981,
69509013, 69509045, 69509077, 69509109, 69509141, 69509173, 69509205,
69509237, 69509269, 69509301, 69509333, 69509365, 69509397, 69509429,
69509461, 69509493, 69509525, 69509557, 69509589, 69509621, 69509653,
69509685, 69509717, 69509748, 69509779, 69509810, 69509841, 69509872,
69509903, 69509934, 69509965, 69509996, 69510027, 69510058, 69510089,
69510120, 69510151, 69510182, 69510213, 69510244, 69510275, 69510306,
69510337, 69510368, 69510399, 69510430, 69510461, 69510492, 69510523,
69510554, 69510585, 69510616, 69510647, 69510678, 69510709, 69510740,
69510771, 69510802, 69510833, 69510864, 69510895, 69510926, 69510957,
69510988, 69511019, 69511050, 69511053, 69511056, 69511059, 69511062,
69511065, 69511068, 69511071, 69511074, 69511077, 69511080, 69511083,
69511086, 69511089, 69511092, 69511095, 69511098, 69511101, 69511104,
69511107, 69511110, 69511113, 69511116, 69511119, 69511122, 69511125,
69511128, 69511131, 69511134, 69511137, 69511140, 69511143, 69511146,
69511149, 69511152, 69511155, 69511158, 69511161, 69511164, 69511167,
69511170, 69511173, 69511176, 69511179, 69511182, 69511185, 69511188,
69511191, 69511194, 69511197, 69511200, 69511203, 69511206, 69511209,
69511212, 69511241, 69511270, 69511299, 69511328, 69511357, 69511386,
69511415, 69511444, 69511473, 69511502, 69511531, 69511560, 69511589,
69511618, 69511647, 69511676, 69511705, 69511734, 69511763, 69511792,
69511821, 69511850, 69511879, 69511908, 69511937, 69511966, 69511995,
69512024, 69512053, 69512082, 69512111, 69512140, 69512169, 69512198,
69512227, 69512256, 69512285, 69512314, 69512343, 69512372, 69512401,
69512430, 69512459, 69512488, 69512517, 69512545, 69512573, 69512601,
69512629, 69512657, 69512685, 69512713, 69512741, 69512769, 69512797,
69512825, 69512853, 69512881, 69512909, 69512937, 69512965, 69512993,
69513021, 69513049, 69513077, 69513105, 69513133, 69513161, 69513189,
69513217, 69513245, 69513273, 69513301, 69513329, 69513357, 69513385,
69513413, 69513441, 69513469, 69513497, 69513525, 69513553, 69513581,
69513609, 69513637, 69513665, 69513693, 69513721, 69513749, 69513777,
69513805, 69513833, 69513861, 69513889, 69513916, 69513943, 69513970,
69513997, 69514024, 69514051, 69514078, 69514105, 69514132, 69514159,
69514186, 69514213, 69514240, 69514267, 69514294, 69514321, 69514348,
69514375, 69514402, 69514429, 69514456, 69514483, 69514510, 69514537,
69514564, 69514591, 69514618, 69514645, 69514672, 69514699, 69514726,
69514753, 69514780, 69514807, 69514834, 69514861, 69514888, 69514915,
69514942, 69514969, 69514996, 69515023, 69515050, 69515077, 69515104,
69515131, 69515158, 69515185, 69515212, 69515239, 69515266, 69515293,
69515320, 69515347, 69515374, 69515401, 69515428, 69515455, 69515482,
69515509, 69515536, 69515563, 69515590, 69515617, 69515644, 69515670,
69515696, 69515722, 69515748, 69515774, 69515800, 69515826, 69515852,
69515878, 69515904, 69515930, 69515956, 69515982, 69516008, 69516034,
69516060, 69516086, 69516112, 69516138, 69516164, 69516190, 69516216,
69516242, 69516268, 69516294, 69516320, 69516346, 69516372, 69516398,
69516424, 69516450, 69516476, 69516502, 69516528, 69516554, 69516580,
69516606, 69516632, 69516658, 69516684, 69516710, 69516736, 69516762,
69516788, 69516814, 69516840, 69516866, 69516892, 69516918, 69516944,
69516970, 69516996, 69517022, 69517048, 69517074, 69517100, 69517126,
69517152, 69517178, 69517204, 69517230, 69517256, 69517282, 69517308,
69517334, 69517359, 69517384, 69517409, 69517434, 69517459, 69517484,
69517509, 69517534, 69517559, 69517584, 69517609, 69517634, 69517659,
69517684, 69517709, 69517734, 69517759, 69517784, 69517809, 69517834,
69517859, 69517884, 69517909, 69517934, 69517959, 69517984, 69518009,
69518034, 69518059, 69518084, 69518109, 69518134, 69518159, 69518184,
69518209, 69518234, 69518259, 69518284, 69518309, 69518334, 69518359,
69518384, 69518409, 69518434, 69518459, 69518484, 69518509, 69518534,
69518559, 69518584, 69518609, 69518634, 69518659, 69518684, 69518709,
69518734, 69518759, 69518784, 69518809, 69518834, 69518859, 69518884,
69518909, 69518934, 69518958, 69518982, 69519006, 69519030, 69519054,
69519078, 69519102, 69519126, 69519150, 69519174, 69519198, 69519222,
69519246, 69519270, 69519294, 69519318, 69519342, 69519366, 69519390,
69519414, 69519438, 69519462, 69519486, 69519510, 69519534, 69519558,
69519582, 69519606, 69519630, 69519654, 69519678, 69519702, 69519726,
69519750, 69519774, 69519798, 69519822, 69519846, 69519870, 69519894,
69519918, 69519942, 69519966, 69519990, 69520014, 69520038, 69520062,
69520086, 69520110, 69520134, 69520158, 69520182, 69520206, 69520230,
69520254, 69520278, 69520302, 69520326, 69520350, 69520374, 69520398,
69520422, 69520446, 69520470, 69520494, 69520518, 69520542, 69520566,
69520590, 69520614, 69520638, 69520662, 69520686, 69520710, 69520734,
69520758, 69520781, 69520804, 69520827, 69520850, 69520873, 69520896,
69520919, 69520942, 69520965, 69520988, 69521011, 69521034, 69521057,
69521080, 69521103, 69521126, 69521149, 69521172, 69521195, 69521218,
69521241, 69521264, 69521287, 69521310, 69521333, 69521356, 69521379,
69521402, 69521425, 69521448, 69521471, 69521494, 69521517, 69521540,
69521563, 69521586, 69521609, 69521632, 69521655, 69521678, 69521701,
69521724, 69521747, 69521770, 69521793, 69521816, 69521839, 69521862,
69521885, 69521908, 69521931, 69521954, 69521977, 69522000, 69522023,
69522046, 69522069, 69522092, 69522115, 69522138, 69522160, 69522182,
69522204, 69522226, 69522248, 69522270, 69522292, 69522314, 69522336,
69522358, 69522380, 69522402, 69522424, 69522446, 69522468, 69522490,
69522512, 69522534, 69522556, 69522578, 69522600, 69522622, 69522644,
69522666, 69522688, 69522710, 69522732, 69522754, 69522776, 69522798,
69522820, 69522842, 69522864, 69522886, 69522908, 69522930, 69522952,
69522974, 69522996, 69523018, 69523040, 69523062, 69523084, 69523106,
69523128, 69523150, 69523172, 69523194, 69523216, 69523238, 69523260,
69523282, 69523304, 69523326, 69523348, 69523370, 69523392, 69523414,
69523436, 69523458, 69523480, 69523502, 69523524, 69523546, 69523568,
69523590, 69523612, 69523634, 69523656, 69523678, 69523700, 69523722,
69523744, 69523765, 69523786, 69523807, 69523828, 69523849, 69523870,
69523891, 69523912, 69523933, 69523954, 69523975, 69523996, 69524017,
69524038, 69524059, 69524080, 69524101, 69524122, 69524143, 69524164,
69524185, 69524206, 69524227, 69524248, 69524269, 69524290, 69524311,
69524332, 69524353, 69524374, 69524395, 69524416, 69524437, 69524458,
69524479, 69524500, 69524521, 69524542, 69524563, 69524584, 69524605,
69524626, 69524647, 69524668, 69524689, 69524710, 69524731, 69524752,
69524773, 69524794, 69524815, 69524836, 69524857, 69524878, 69524899,
69524920, 69524941, 69524962, 69524983, 69525004, 69525025, 69525046,
69525067, 69525088, 69525109, 69525130, 69525151, 69525172, 69525193,
69525214, 69525235, 69525256, 69525277, 69525298, 69525319, 69525340,
69525361, 69525382, 69525403, 69525424, 69525445, 69525466, 69525487,
69525508, 69525529, 69525550, 69525571, 69525592, 69525594, 69525596,
69525598, 69525600, 69525602, 69525604, 69525606, 69525608, 69525610,
69525612, 69525614, 69525616, 69525618, 69525620, 69525622, 69525624,
69525626, 69525628, 69525630, 69525632, 69525634, 69525636, 69525638,
69525640, 69525642, 69525644, 69525646, 69525648, 69525650, 69525652,
69525654, 69525656, 69525658, 69525660, 69525662, 69525664, 69525666,
69525668, 69525670, 69525672, 69525674, 69525676, 69525678, 69525680,
69525682, 69525684, 69525686, 69525688, 69525690, 69525692, 69525694,
69525696, 69525698, 69525700, 69525702, 69525704, 69525706, 69525708,
69525710, 69525712, 69525714, 69525716, 69525718, 69525720, 69525722,
69525724, 69525726, 69525728, 69525730, 69525732, 69525734, 69525736,
69525738, 69525740, 69525742, 69525744, 69525746, 69525748, 69525750,
69525752, 69525754, 69525756, 69525758, 69525760, 69525762, 69525764,
69525766, 69525768, 69525770, 69525772, 69525774, 69525776, 69525778,
69525780, 69525782, 69525784, 69525786, 69525788, 69525790, 69525792,
69525794, 69525796, 69525815, 69525834, 69525853, 69525872, 69525891,
69525910, 69525929, 69525948, 69525967, 69525986, 69526005, 69526024,
69526043, 69526062, 69526081, 69526100, 69526119, 69526138, 69526157,
69526176, 69526195, 69526214, 69526233, 69526252, 69526271, 69526290,
69526309, 69526328, 69526347, 69526366, 69526385, 69526404, 69526423,
69526442, 69526461, 69526480, 69526499, 69526518, 69526537, 69526556,
69526575, 69526594, 69526613, 69526632, 69526651, 69526670, 69526689,
69526708, 69526727, 69526746, 69526765, 69526784, 69526803, 69526822,
69526841, 69526860, 69526879, 69526898, 69526917, 69526936, 69526955,
69526974, 69526993, 69527012, 69527031, 69527050, 69527069, 69527088,
69527107, 69527126, 69527145, 69527164, 69527183, 69527202, 69527221,
69527240, 69527259, 69527278, 69527297, 69527316, 69527335, 69527354,
69527373, 69527392, 69527411, 69527429, 69527447, 69527465, 69527483,
69527501, 69527519, 69527537, 69527555, 69527573, 69527591, 69527609,
69527627, 69527645, 69527663, 69527681, 69527699, 69527717, 69527735,
69527753, 69527771, 69527789, 69527807, 69527825, 69527843, 69527861,
69527879, 69527897, 69527915, 69527933, 69527951, 69527969, 69527987,
69528005, 69528023, 69528041, 69528059, 69528077, 69528095, 69528113,
69528131, 69528149, 69528167, 69528185, 69528203, 69528221, 69528239,
69528257, 69528275, 69528293, 69528311, 69528329, 69528347, 69528365,
69528383, 69528401, 69528419, 69528437, 69528455, 69528473, 69528491,
69528509, 69528527, 69528545, 69528563, 69528581, 69528599, 69528617,
69528635, 69528653, 69528671, 69528689, 69528707, 69528725, 69528743,
69528761, 69528779, 69528797, 69528814, 69528831, 69528848, 69528865,
69528882, 69528899, 69528916, 69528933, 69528950, 69528967, 69528984,
69529001, 69529018, 69529035, 69529052, 69529069, 69529086, 69529103,
69529120, 69529137, 69529154, 69529171, 69529188, 69529205, 69529222,
69529239, 69529256, 69529273, 69529290, 69529307, 69529324, 69529341,
69529358, 69529375, 69529392, 69529409, 69529426, 69529443, 69529460,
69529477, 69529494, 69529511, 69529528, 69529545, 69529562, 69529579,
69529596, 69529613, 69529630, 69529647, 69529664, 69529681, 69529698,
69529715, 69529732, 69529749, 69529766, 69529783, 69529800, 69529817,
69529834, 69529851, 69529868, 69529885, 69529902, 69529919, 69529936,
69529953, 69529970, 69529987, 69530004, 69530021, 69530038, 69530055,
69530072, 69530089, 69530106, 69530123, 69530140, 69530157, 69530174,
69530191, 69530208, 69530225, 69530242, 69530259, 69530276, 69530293,
69530310, 69530327, 69530344, 69530361, 69530378, 69530395, 69530412,
69530429, 69530446, 69530463, 69530480, 69530497, 69530514, 69530531,
69530548, 69530565, 69530582, 69530599, 69530616, 69530633, 69530650,
69530666, 69530682, 69530698, 69530714, 69530730, 69530746, 69530762,
69530778, 69530794, 69530810, 69530826, 69530842, 69530858, 69530874,
69530890, 69530906, 69530922, 69530938, 69530954, 69530970, 69530986,
69531002, 69531018, 69531034, 69531050, 69531066, 69531082, 69531098,
69531114, 69531130, 69531146, 69531162, 69531178, 69531194, 69531210,
69531226, 69531242, 69531258, 69531274, 69531290, 69531306, 69531322,
69531338, 69531354, 69531370, 69531386, 69531402, 69531418, 69531434,
69531450, 69531466, 69531482, 69531498, 69531514, 69531530, 69531546,
69531562, 69531578, 69531594, 69531610, 69531626, 69531642, 69531658,
69531674, 69531690, 69531706, 69531722, 69531738, 69531754, 69531770,
69531786, 69531802, 69531818, 69531834, 69531850, 69531866, 69531882,
69531898, 69531914, 69531930, 69531946, 69531962, 69531978, 69531994,
69532010, 69532026, 69532042, 69532058, 69532074, 69532090, 69532106,
69532122, 69532138, 69532154, 69532170, 69532186, 69532202, 69532218,
69532234, 69532250, 69532266, 69532282, 69532298, 69532314, 69532330,
69532346, 69532362, 69532378, 69532394, 69532410, 69532426, 69532442,
69532458, 69532474, 69532490, 69532506, 69532522, 69532538, 69532554,
69532569, 69532584, 69532599, 69532614, 69532629, 69532644, 69532659,
69532674, 69532689, 69532704, 69532719, 69532734, 69532749, 69532764,
69532779, 69532794, 69532809, 69532824, 69532839, 69532854, 69532869,
69532884, 69532899, 69532914, 69532929, 69532944, 69532959, 69532974,
69532989, 69533004, 69533019, 69533034, 69533049, 69533064, 69533079,
69533094, 69533109, 69533124, 69533139, 69533154, 69533169, 69533184,
69533199, 69533214, 69533229, 69533244, 69533259, 69533274, 69533289,
69533304, 69533319, 69533334, 69533349, 69533364, 69533379, 69533394,
69533409, 69533424, 69533439, 69533454, 69533469, 69533484, 69533499,
69533514, 69533529, 69533544, 69533559, 69533574, 69533589, 69533604,
69533619, 69533634, 69533649, 69533664, 69533679, 69533694, 69533709,
69533724, 69533739, 69533754, 69533769, 69533784, 69533799, 69533814,
69533829, 69533844, 69533859, 69533874, 69533889, 69533904, 69533919,
69533934, 69533949, 69533964, 69533979, 69533994, 69534009, 69534024,
69534039, 69534054, 69534069, 69534084, 69534099, 69534114, 69534129,
69534144, 69534159, 69534174, 69534189, 69534204, 69534219, 69534233,
69534247, 69534261, 69534275, 69534289, 69534303, 69534317, 69534331,
69534345, 69534359, 69534373, 69534387, 69534401, 69534415, 69534429,
69534443, 69534457, 69534471, 69534485, 69534499, 69534513, 69534527,
69534541, 69534555, 69534569, 69534583, 69534597, 69534611, 69534625,
69534639, 69534653, 69534667, 69534681, 69534695, 69534709, 69534723,
69534737, 69534751, 69534765, 69534779, 69534793, 69534807, 69534821,
69534835, 69534849, 69534863, 69534877, 69534891, 69534905, 69534919,
69534933, 69534947, 69534961, 69534975, 69534989, 69535003, 69535017,
69535031, 69535045, 69535059, 69535073, 69535087, 69535101, 69535115,
69535129, 69535143, 69535157, 69535171, 69535185, 69535199, 69535213,
69535227, 69535241, 69535255, 69535269, 69535283, 69535297, 69535311,
69535325, 69535339, 69535353, 69535367, 69535381, 69535395, 69535409,
69535423, 69535437, 69535451, 69535465, 69535479, 69535493, 69535507,
69535521, 69535535, 69535549, 69535563, 69535577, 69535591, 69535605,
69535619, 69535633, 69535647, 69535661, 69535675, 69535689, 69535703,
69535717, 69535731, 69535744, 69535757, 69535770, 69535783, 69535796,
69535809, 69535822, 69535835, 69535848, 69535861, 69535874, 69535887,
69535900, 69535913, 69535926, 69535939, 69535952, 69535965, 69535978,
69535991, 69536004, 69536017, 69536030, 69536043, 69536056, 69536069,
69536082, 69536095, 69536108, 69536121, 69536134, 69536147, 69536160,
69536173, 69536186, 69536199, 69536212, 69536225, 69536238, 69536251,
69536264, 69536277, 69536290, 69536303, 69536316, 69536329, 69536342,
69536355, 69536368, 69536381, 69536394, 69536407, 69536420, 69536433,
69536446, 69536459, 69536472, 69536485, 69536498, 69536511, 69536524,
69536537, 69536550, 69536563, 69536576, 69536589, 69536602, 69536615,
69536628, 69536641, 69536654, 69536667, 69536680, 69536693, 69536706,
69536719, 69536732, 69536745, 69536758, 69536771, 69536784, 69536797,
69536810, 69536823, 69536836, 69536849, 69536862, 69536875, 69536888,
69536901, 69536914, 69536927, 69536940, 69536953, 69536966, 69536979,
69536992, 69537005, 69537018, 69537031, 69537044, 69537057, 69537070,
69537083, 69537096, 69537109, 69537122, 69537135, 69537148, 69537161,
69537174, 69537187, 69537200, 69537213, 69537226, 69537239, 69537252,
69537265, 69537278, 69537291, 69537304, 69537317, 69537330, 69537343,
69537356, 69537369, 69537381, 69537393, 69537405, 69537417, 69537429,
69537441, 69537453, 69537465, 69537477, 69537489, 69537501, 69537513,
69537525, 69537537, 69537549, 69537561, 69537573, 69537585, 69537597,
69537609, 69537621, 69537633, 69537645, 69537657, 69537669, 69537681,
69537693, 69537705, 69537717, 69537729, 69537741, 69537753, 69537765,
69537777, 69537789, 69537801, 69537813, 69537825, 69537837, 69537849,
69537861, 69537873, 69537885, 69537897, 69537909, 69537921, 69537933,
69537945, 69537957, 69537969, 69537981, 69537993, 69538005, 69538017,
69538029, 69538041, 69538053, 69538065, 69538077, 69538089, 69538101,
69538113, 69538125, 69538137, 69538149, 69538161, 69538173, 69538185,
69538197, 69538209, 69538221, 69538233, 69538245, 69538257, 69538269,
69538281, 69538293, 69538305, 69538317, 69538329, 69538341, 69538353,
69538365, 69538377, 69538389, 69538401, 69538413, 69538425, 69538437,
69538449, 69538461, 69538473, 69538485, 69538497, 69538509, 69538521,
69538533, 69538545, 69538557, 69538569, 69538581, 69538593, 69538605,
69538617, 69538629, 69538641, 69538653, 69538665, 69538677, 69538689,
69538701, 69538713, 69538725, 69538737, 69538749, 69538761, 69538773,
69538785, 69538797, 69538809, 69538821, 69538833, 69538845, 69538857,
69538869, 69538881, 69538893, 69538904, 69538915, 69538926, 69538937,
69538948, 69538959, 69538970, 69538981, 69538992, 69539003, 69539014,
69539025, 69539036, 69539047, 69539058, 69539069, 69539080, 69539091,
69539102, 69539113, 69539124, 69539135, 69539146, 69539157, 69539168,
69539179, 69539190, 69539201, 69539212, 69539223, 69539234, 69539245,
69539256, 69539267, 69539278, 69539289, 69539300, 69539311, 69539322,
69539333, 69539344, 69539355, 69539366, 69539377, 69539388, 69539399,
69539410, 69539421, 69539432, 69539443, 69539454, 69539465, 69539476,
69539487, 69539498, 69539509, 69539520, 69539531, 69539542, 69539553,
69539564, 69539575, 69539586, 69539597, 69539608, 69539619, 69539630,
69539641, 69539652, 69539663, 69539674, 69539685, 69539696, 69539707,
69539718, 69539729, 69539740, 69539751, 69539762, 69539773, 69539784,
69539795, 69539806, 69539817, 69539828, 69539839, 69539850, 69539861,
69539872, 69539883, 69539894, 69539905, 69539916, 69539927, 69539938,
69539949, 69539960, 69539971, 69539982, 69539993, 69540004, 69540015,
69540026, 69540037, 69540048, 69540059, 69540070, 69540081, 69540092,
69540103, 69540114, 69540125, 69540136, 69540147, 69540158, 69540169,
69540180, 69540191, 69540202, 69540213, 69540224, 69540235, 69540246,
69540257, 69540268, 69540279, 69540290, 69540301, 69540312, 69540323,
69540334, 69540345, 69540356, 69540367, 69540378, 69540389, 69540400,
69540411, 69540422, 69540433, 69540444, 69540455, 69540466, 69540477,
69540488, 69540499, 69540510, 69540521, 69540532, 69540543, 69540554,
69540565, 69540576, 69540587, 69540598, 69540609, 69540620, 69540631,
69540642, 69540653, 69540664, 69540675, 69540686, 69540697, 69540698,
69540699, 69540700, 69540701, 69540702, 69540703, 69540704, 69540705,
69540706, 69540707, 69540708, 69540709, 69540710, 69540711, 69540712,
69540713, 69540714, 69540715, 69540716, 69540717, 69540718, 69540719,
69540720, 69540721, 69540722, 69540723, 69540724, 69540725, 69540726,
69540727, 69540728, 69540729, 69540730, 69540731, 69540732, 69540733,
69540734, 69540735, 69540736, 69540737, 69540738, 69540739, 69540740,
69540741, 69540742, 69540743, 69540744, 69540745, 69540746, 69540747,
69540748, 69540749, 69540750, 69540751, 69540752, 69540753, 69540754,
69540755, 69540756, 69540757, 69540758, 69540759, 69540760, 69540761,
69540762, 69540763, 69540764, 69540765, 69540766, 69540767, 69540768,
69540769, 69540770, 69540771, 69540772, 69540773, 69540774, 69540775,
69540776, 69540777, 69540778, 69540779, 69540780, 69540781, 69540782,
69540783, 69540784, 69540785, 69540786, 69540787, 69540788, 69540789,
69540790, 69540791, 69540792, 69540793, 69540794, 69540795, 69540796,
69540797, 69540798, 69540799, 69540800, 69540801, 69540802, 69540803,
69540804, 69540805, 69540806, 69540807, 69540808, 69540809, 69540810,
69540811, 69540812, 69540813, 69540814, 69540815, 69540816, 69540817,
69540818, 69540819, 69540820, 69540821, 69540822, 69540823, 69540824,
69540825, 69540826, 69540827, 69540828, 69540829, 69540830, 69540831,
69540832, 69540833, 69540834, 69540835, 69540836, 69540837, 69540838,
69540839, 69540840, 69540841, 69540842, 69540843, 69540844, 69540845,
69540846, 69540847, 69540848, 69540849, 69540850, 69540851, 69540852,
69540853, 69540854, 69540855, 69540856, 69540857, 69540858, 69540859,
69540860, 69540861, 69540862, 69540863, 69540864, 69540865, 69540866,
69540867, 69540868, 69540869, 69540870, 69540871, 69540872, 69540873,
69540874, 69540875, 69540876, 69540877, 69540878, 69540879, 69540880,
69540881, 69540882, 69540891, 69540900, 69540909, 69540918, 69540927,
69540936, 69540945, 69540954, 69540963, 69540972, 69540981, 69540990,
69540999, 69541008, 69541017, 69541026, 69541035, 69541044, 69541053,
69541062, 69541071, 69541080, 69541089, 69541098, 69541107, 69541116,
69541125, 69541134, 69541143, 69541152, 69541161, 69541170, 69541179,
69541188, 69541197, 69541206, 69541215, 69541224, 69541233, 69541242,
69541251, 69541260, 69541269, 69541278, 69541287, 69541296, 69541305,
69541314, 69541323, 69541332, 69541341, 69541350, 69541359, 69541368,
69541377, 69541386, 69541395, 69541404, 69541413, 69541422, 69541431,
69541440, 69541449, 69541458, 69541467, 69541476, 69541485, 69541494,
69541503, 69541512, 69541521, 69541530, 69541539, 69541548, 69541557,
69541566, 69541575, 69541584, 69541593, 69541602, 69541611, 69541620,
69541629, 69541638, 69541647, 69541656, 69541665, 69541674, 69541683,
69541692, 69541701, 69541710, 69541719, 69541728, 69541737, 69541746,
69541755, 69541764, 69541773, 69541782, 69541791, 69541800, 69541809,
69541818, 69541827, 69541836, 69541845, 69541854, 69541863, 69541872,
69541881, 69541890, 69541899, 69541908, 69541917, 69541926, 69541935,
69541944, 69541953, 69541962, 69541971, 69541980, 69541989, 69541998,
69542007, 69542016, 69542025, 69542034, 69542043, 69542052, 69542061,
69542070, 69542079, 69542088, 69542097, 69542106, 69542115, 69542124,
69542133, 69542142, 69542151, 69542160, 69542169, 69542178, 69542187,
69542196, 69542205, 69542214, 69542223, 69542232, 69542241, 69542250,
69542259, 69542268, 69542277, 69542286, 69542295, 69542304, 69542313,
69542322, 69542331, 69542340, 69542349, 69542358, 69542367, 69542376,
69542385, 69542394, 69542403, 69542412, 69542421, 69542430, 69542439,
69542448, 69542457, 69542466, 69542475, 69542484, 69542493, 69542502,
69542511, 69542520, 69542529, 69542538, 69542547, 69542556, 69542565,
69542574, 69542583, 69542592, 69542601, 69542610, 69542619, 69542628,
69542637, 69542646, 69542655, 69542664, 69542673, 69542682, 69542691,
69542700, 69542709, 69542718, 69542727, 69542736, 69542745, 69542753,
69542761, 69542769, 69542777, 69542785, 69542793, 69542801, 69542809,
69542817, 69542825, 69542833, 69542841, 69542849, 69542857, 69542865,
69542873, 69542881, 69542889, 69542897, 69542905, 69542913, 69542921,
69542929, 69542937, 69542945, 69542953, 69542961, 69542969, 69542977,
69542985, 69542993, 69543001, 69543009, 69543017, 69543025, 69543033,
69543041, 69543049, 69543057, 69543065, 69543073, 69543081, 69543089,
69543097, 69543105, 69543113, 69543121, 69543129, 69543137, 69543145,
69543153, 69543161, 69543169, 69543177, 69543185, 69543193, 69543201,
69543209, 69543217, 69543225, 69543233, 69543241, 69543249, 69543257,
69543265, 69543273, 69543281, 69543289, 69543297, 69543305, 69543313,
69543321, 69543329, 69543337, 69543345, 69543353, 69543361, 69543369,
69543377, 69543385, 69543393, 69543401, 69543409, 69543417, 69543425,
69543433, 69543441, 69543449, 69543457, 69543465, 69543473, 69543481,
69543489, 69543497, 69543505, 69543513, 69543521, 69543529, 69543537,
69543545, 69543553, 69543561, 69543569, 69543577, 69543585, 69543593,
69543601, 69543609, 69543617, 69543625, 69543633, 69543641, 69543649,
69543657, 69543665, 69543673, 69543681, 69543689, 69543697, 69543705,
69543713, 69543721, 69543729, 69543737, 69543745, 69543753, 69543761,
69543769, 69543777, 69543785, 69543793, 69543801, 69543809, 69543817,
69543825, 69543833, 69543841, 69543849, 69543857, 69543865, 69543873,
69543881, 69543889, 69543897, 69543905, 69543913, 69543921, 69543929,
69543937, 69543945, 69543953, 69543961, 69543969, 69543977, 69543985,
69543993, 69544001, 69544009, 69544017, 69544025, 69544033, 69544041,
69544049, 69544057, 69544065, 69544073, 69544081, 69544089, 69544097,
69544105, 69544113, 69544121, 69544129, 69544137, 69544145, 69544153,
69544161, 69544169, 69544177, 69544185, 69544193, 69544201, 69544209,
69544217, 69544225, 69544233, 69544241, 69544249, 69544257, 69544265,
69544273, 69544281, 69544289, 69544297, 69544305, 69544313, 69544321,
69544329, 69544337, 69544345, 69544353, 69544361, 69544369, 69544377,
69544385, 69544393, 69544401, 69544409, 69544417, 69544425, 69544433,
69544441, 69544449, 69544457, 69544465, 69544473, 69544481, 69544489,
69544497, 69544505, 69544513, 69544521, 69544529, 69544537, 69544545,
69544553, 69544561, 69544569, 69544577, 69544585, 69544593, 69544601,
69544609, 69544617, 69544625, 69544633, 69544641, 69544649, 69544657,
69544665, 69544673, 69544681, 69544689, 69544697, 69544705, 69544713,
69544721, 69544729, 69544737, 69544745, 69544753, 69544761, 69544769,
69544777, 69544785, 69544793, 69544800, 69544807, 69544814, 69544821,
69544828, 69544835, 69544842, 69544849, 69544856, 69544863, 69544870,
69544877, 69544884, 69544891, 69544898, 69544905, 69544912, 69544919,
69544926, 69544933, 69544940, 69544947, 69544954, 69544961, 69544968,
69544975, 69544982, 69544989, 69544996, 69545003, 69545010, 69545017,
69545024, 69545031, 69545038, 69545045, 69545052, 69545059, 69545066,
69545073, 69545080, 69545087, 69545094, 69545101, 69545108, 69545115,
69545122, 69545129, 69545136, 69545143, 69545150, 69545157, 69545164,
69545171, 69545178, 69545185, 69545192, 69545199, 69545206, 69545213,
69545220, 69545227, 69545234, 69545241, 69545248, 69545255, 69545262,
69545269, 69545276, 69545283, 69545290, 69545297, 69545304, 69545311,
69545318, 69545325, 69545332, 69545339, 69545346, 69545353, 69545360,
69545367, 69545374, 69545381, 69545388, 69545395, 69545402, 69545409,
69545416, 69545423, 69545430, 69545437, 69545444, 69545451, 69545458,
69545465, 69545472, 69545479, 69545486, 69545493, 69545500, 69545507,
69545514, 69545521, 69545528, 69545535, 69545542, 69545549, 69545556,
69545563, 69545570, 69545577, 69545584, 69545591, 69545598, 69545605,
69545612, 69545619, 69545626, 69545633, 69545640, 69545647, 69545654,
69545661, 69545668, 69545675, 69545682, 69545689, 69545696, 69545703,
69545710, 69545717, 69545724, 69545731, 69545738, 69545745, 69545752,
69545759, 69545766, 69545773, 69545780, 69545787, 69545794, 69545801,
69545808, 69545815, 69545822, 69545829, 69545836, 69545843, 69545850,
69545857, 69545864, 69545871, 69545878, 69545885, 69545892, 69545899,
69545906, 69545913, 69545920, 69545927, 69545934, 69545941, 69545948,
69545955, 69545962, 69545969, 69545976, 69545983, 69545990, 69545997,
69546004, 69546011, 69546018, 69546025, 69546032, 69546039, 69546046,
69546053, 69546060, 69546067, 69546074, 69546081, 69546088, 69546095,
69546102, 69546109, 69546116, 69546123, 69546130, 69546137, 69546144,
69546151, 69546158, 69546165, 69546172, 69546179, 69546186, 69546193,
69546200, 69546207, 69546214, 69546221, 69546228, 69546235, 69546242,
69546249, 69546256, 69546263, 69546270, 69546277, 69546284, 69546291,
69546298, 69546305, 69546312, 69546319, 69546326, 69546333, 69546340,
69546347, 69546354, 69546361, 69546368, 69546375, 69546382, 69546389,
69546396, 69546403, 69546410, 69546417, 69546424, 69546431, 69546438,
69546445, 69546452, 69546459, 69546466, 69546473, 69546480, 69546487,
69546494, 69546501, 69546508, 69546515, 69546522, 69546529, 69546536,
69546543, 69546550, 69546557, 69546564, 69546571, 69546578, 69546585,
69546592, 69546599, 69546605, 69546611, 69546617, 69546623, 69546629,
69546635, 69546641, 69546647, 69546653, 69546659, 69546665, 69546671,
69546677, 69546683, 69546689, 69546695, 69546701, 69546707, 69546713,
69546719, 69546725, 69546731, 69546737, 69546743, 69546749, 69546755,
69546761, 69546767, 69546773, 69546779, 69546785, 69546791, 69546797,
69546803, 69546809, 69546815, 69546821, 69546827, 69546833, 69546839,
69546845, 69546851, 69546857, 69546863, 69546869, 69546875, 69546881,
69546887, 69546893, 69546899, 69546905, 69546911, 69546917, 69546923,
69546929, 69546935, 69546941, 69546947, 69546953, 69546959, 69546965,
69546971, 69546977, 69546983, 69546989, 69546995, 69547001, 69547007,
69547013, 69547019, 69547025, 69547031, 69547037, 69547043, 69547049,
69547055, 69547061, 69547067, 69547073, 69547079, 69547085, 69547091,
69547097, 69547103, 69547109, 69547115, 69547121, 69547127, 69547133,
69547139, 69547145, 69547151, 69547157, 69547163, 69547169, 69547175,
69547181, 69547187, 69547193, 69547199, 69547205, 69547211, 69547217,
69547223, 69547229, 69547235, 69547241, 69547247, 69547253, 69547259,
69547265, 69547271, 69547277, 69547283, 69547289, 69547295, 69547301,
69547307, 69547313, 69547319, 69547325, 69547331, 69547337, 69547343,
69547349, 69547355, 69547361, 69547367, 69547373, 69547379, 69547385,
69547391, 69547397, 69547403, 69547409, 69547415, 69547421, 69547427,
69547433, 69547439, 69547445, 69547451, 69547457, 69547463, 69547469,
69547475, 69547481, 69547487, 69547493, 69547499, 69547505, 69547511,
69547517, 69547523, 69547529, 69547535, 69547541, 69547547, 69547553,
69547559, 69547565, 69547571, 69547577, 69547583, 69547589, 69547595,
69547601, 69547607, 69547613, 69547619, 69547625, 69547631, 69547637,
69547643, 69547649, 69547655, 69547661, 69547667, 69547673, 69547679,
69547685, 69547691, 69547697, 69547703, 69547709, 69547715, 69547721,
69547727, 69547733, 69547739, 69547745, 69547751, 69547757, 69547763,
69547769, 69547775, 69547781, 69547787, 69547793, 69547799, 69547805,
69547811, 69547817, 69547823, 69547829, 69547835, 69547841, 69547847,
69547853, 69547859, 69547865, 69547871, 69547877, 69547883, 69547889,
69547895, 69547901, 69547907, 69547913, 69547919, 69547925, 69547931,
69547937, 69547943, 69547949, 69547955, 69547961, 69547967, 69547973,
69547979, 69547985, 69547991, 69547997, 69548003, 69548009, 69548015,
69548021, 69548027, 69548033, 69548039, 69548045, 69548051, 69548057,
69548063, 69548069, 69548075, 69548081, 69548087, 69548093, 69548099,
69548105, 69548111, 69548117, 69548123, 69548129, 69548135, 69548141,
69548147, 69548153, 69548159, 69548165, 69548171, 69548177, 69548183,
69548189, 69548195, 69548201, 69548207, 69548213, 69548219, 69548225,
69548231, 69548237, 69548243, 69548249, 69548255, 69548261, 69548267,
69548273, 69548279, 69548285, 69548291, 69548297, 69548303, 69548309,
69548315, 69548321, 69548327, 69548333, 69548339, 69548345, 69548351,
69548357, 69548363, 69548369, 69548375, 69548381, 69548387, 69548393,
69548399, 69548405, 69548411, 69548416, 69548421, 69548426, 69548431,
69548436, 69548441, 69548446, 69548451, 69548456, 69548461, 69548466,
69548471, 69548476, 69548481, 69548486, 69548491, 69548496, 69548501,
69548506, 69548511, 69548516, 69548521, 69548526, 69548531, 69548536,
69548541, 69548546, 69548551, 69548556, 69548561, 69548566, 69548571,
69548576, 69548581, 69548586, 69548591, 69548596, 69548601, 69548606,
69548611, 69548616, 69548621, 69548626, 69548631, 69548636, 69548641,
69548646, 69548651, 69548656, 69548661, 69548666, 69548671, 69548676,
69548681, 69548686, 69548691, 69548696, 69548701, 69548706, 69548711,
69548716, 69548721, 69548726, 69548731, 69548736, 69548741, 69548746,
69548751, 69548756, 69548761, 69548766, 69548771, 69548776, 69548781,
69548786, 69548791, 69548796, 69548801, 69548806, 69548811, 69548816,
69548821, 69548826, 69548831, 69548836, 69548841, 69548846, 69548851,
69548856, 69548861, 69548866, 69548871, 69548876, 69548881, 69548886,
69548891, 69548896, 69548901, 69548906, 69548911, 69548916, 69548921,
69548926, 69548931, 69548936, 69548941, 69548946, 69548951, 69548956,
69548961, 69548966, 69548971, 69548976, 69548981, 69548986, 69548991,
69548996, 69549001, 69549006, 69549011, 69549016, 69549021, 69549026,
69549031, 69549036, 69549041, 69549046, 69549051, 69549056, 69549061,
69549066, 69549071, 69549076, 69549081, 69549086, 69549091, 69549096,
69549101, 69549106, 69549111, 69549116, 69549121, 69549126, 69549131,
69549136, 69549141, 69549146, 69549151, 69549156, 69549161, 69549166,
69549171, 69549176, 69549181, 69549186, 69549191, 69549196, 69549201,
69549206, 69549211, 69549216, 69549221, 69549226, 69549231, 69549236,
69549241, 69549246, 69549251, 69549256, 69549261, 69549266, 69549271,
69549276, 69549281, 69549286, 69549291, 69549296, 69549301, 69549306,
69549311, 69549316, 69549321, 69549326, 69549331, 69549336, 69549341,
69549346, 69549351, 69549356, 69549361, 69549366, 69549371, 69549376,
69549381, 69549386, 69549391, 69549396, 69549401, 69549406, 69549411,
69549416, 69549421, 69549426, 69549431, 69549436, 69549441, 69549446,
69549451, 69549456, 69549461, 69549466, 69549471, 69549476, 69549481,
69549486, 69549491, 69549496, 69549501, 69549506, 69549511, 69549516,
69549521, 69549526, 69549531, 69549536, 69549541, 69549546, 69549551,
69549556, 69549561, 69549566, 69549571, 69549576, 69549581, 69549586,
69549591, 69549596, 69549601, 69549606, 69549611, 69549616, 69549621,
69549626, 69549631, 69549636, 69549641, 69549646, 69549651, 69549656,
69549661, 69549666, 69549671, 69549676, 69549681, 69549686, 69549691,
69549696, 69549701, 69549706, 69549711, 69549716, 69549721, 69549726,
69549731, 69549736, 69549741, 69549746, 69549751, 69549756, 69549761,
69549766, 69549771, 69549776, 69549781, 69549786, 69549791, 69549796,
69549801, 69549806, 69549811, 69549816, 69549821, 69549826, 69549831,
69549836, 69549841, 69549846, 69549851, 69549856, 69549861, 69549866,
69549871, 69549876, 69549881, 69549886, 69549891, 69549896, 69549901,
69549906, 69549911, 69549916, 69549921, 69549926, 69549931, 69549936,
69549941, 69549946, 69549951, 69549956, 69549961, 69549966, 69549971,
69549976, 69549981, 69549986, 69549991, 69549996, 69550001, 69550006,
69550011, 69550016, 69550021, 69550026, 69550031, 69550036, 69550041,
69550046, 69550051, 69550056, 69550061, 69550066, 69550071, 69550076,
69550081, 69550086, 69550091, 69550096, 69550101, 69550106, 69550111,
69550116, 69550121, 69550126, 69550131, 69550136, 69550141, 69550146,
69550151, 69550156, 69550161, 69550166, 69550171, 69550176, 69550181,
69550186, 69550191, 69550196, 69550201, 69550206, 69550211, 69550216,
69550221, 69550226, 69550231, 69550236, 69550241, 69550246, 69550251,
69550256, 69550261, 69550266, 69550271, 69550276, 69550281, 69550286,
69550291, 69550296, 69550301, 69550306, 69550311, 69550316, 69550321,
69550326, 69550331, 69550336, 69550341, 69550346, 69550351, 69550356,
69550361, 69550366, 69550371, 69550376, 69550381, 69550386, 69550390,
69550394, 69550398, 69550402, 69550406, 69550410, 69550414, 69550418,
69550422, 69550426, 69550430, 69550434, 69550438, 69550442, 69550446,
69550450, 69550454, 69550458, 69550462, 69550466, 69550470, 69550474,
69550478, 69550482, 69550486, 69550490, 69550494, 69550498, 69550502,
69550506, 69550510, 69550514, 69550518, 69550522, 69550526, 69550530,
69550534, 69550538, 69550542, 69550546, 69550550, 69550554, 69550558,
69550562, 69550566, 69550570, 69550574, 69550578, 69550582, 69550586,
69550590, 69550594, 69550598, 69550602, 69550606, 69550610, 69550614,
69550618, 69550622, 69550626, 69550630, 69550634, 69550638, 69550642,
69550646, 69550650, 69550654, 69550658, 69550662, 69550666, 69550670,
69550674, 69550678, 69550682, 69550686, 69550690, 69550694, 69550698,
69550702, 69550706, 69550710, 69550714, 69550718, 69550722, 69550726,
69550730, 69550734, 69550738, 69550742, 69550746, 69550750, 69550754,
69550758, 69550762, 69550766, 69550770, 69550774, 69550778, 69550782,
69550786, 69550790, 69550794, 69550798, 69550802, 69550806, 69550810,
69550814, 69550818, 69550822, 69550826, 69550830, 69550834, 69550838,
69550842, 69550846, 69550850, 69550854, 69550858, 69550862, 69550866,
69550870, 69550874, 69550878, 69550882, 69550886, 69550890, 69550894,
69550898, 69550902, 69550906, 69550910, 69550914, 69550918, 69550922,
69550926, 69550930, 69550934, 69550938, 69550942, 69550946, 69550950,
69550954, 69550958, 69550962, 69550966, 69550970, 69550974, 69550978,
69550982, 69550986, 69550990, 69550994, 69550998, 69551002, 69551006,
69551010, 69551014, 69551018, 69551022, 69551026, 69551030, 69551034,
69551038, 69551042, 69551046, 69551050, 69551054, 69551058, 69551062,
69551066, 69551070, 69551074, 69551078, 69551082, 69551086, 69551090,
69551094, 69551098, 69551102, 69551106, 69551110, 69551114, 69551118,
69551122, 69551126, 69551130, 69551134, 69551138, 69551142, 69551146,
69551150, 69551154, 69551158, 69551162, 69551166, 69551170, 69551174,
69551178, 69551182, 69551186, 69551190, 69551194, 69551198, 69551202,
69551206, 69551210, 69551214, 69551218, 69551222, 69551226, 69551230,
69551234, 69551238, 69551242, 69551246, 69551250, 69551254, 69551258,
69551262, 69551266, 69551270, 69551274, 69551278, 69551282, 69551286,
69551290, 69551294, 69551298, 69551302, 69551306, 69551310, 69551314,
69551318, 69551322, 69551326, 69551330, 69551334, 69551338, 69551342,
69551346, 69551350, 69551354, 69551358, 69551362, 69551366, 69551370,
69551374, 69551378, 69551382, 69551386, 69551390, 69551394, 69551398,
69551402, 69551406, 69551410, 69551414, 69551418, 69551422, 69551426,
69551430, 69551434, 69551438, 69551442, 69551446, 69551450, 69551454,
69551458, 69551462, 69551466, 69551470, 69551474, 69551478, 69551482,
69551486, 69551490, 69551494, 69551498, 69551502, 69551506, 69551510,
69551514, 69551518, 69551522, 69551526, 69551530, 69551534, 69551538,
69551542, 69551546, 69551550, 69551554, 69551558, 69551562, 69551566,
69551570, 69551574, 69551578, 69551582, 69551586, 69551590, 69551594,
69551598, 69551602, 69551606, 69551610, 69551614, 69551618, 69551622,
69551626, 69551630, 69551634, 69551638, 69551642, 69551646, 69551650,
69551654, 69551658, 69551662, 69551666, 69551670, 69551674, 69551678,
69551682, 69551686, 69551690, 69551694, 69551698, 69551702, 69551706,
69551710, 69551714, 69551718, 69551722, 69551726, 69551730, 69551734,
69551738, 69551742, 69551746, 69551750, 69551754, 69551758, 69551762,
69551766, 69551770, 69551774, 69551778, 69551782, 69551786, 69551790,
69551794, 69551798, 69551802, 69551806, 69551810, 69551814, 69551818,
69551822, 69551826, 69551830, 69551834, 69551838, 69551842, 69551846,
69551850, 69551854, 69551858, 69551862, 69551866, 69551870, 69551874,
69551878, 69551882, 69551886, 69551890, 69551894, 69551898, 69551902,
69551906, 69551910, 69551914, 69551918, 69551922, 69551926, 69551930,
69551934, 69551938, 69551942, 69551946, 69551950, 69551954, 69551958,
69551962, 69551966, 69551970, 69551974, 69551978, 69551982, 69551986,
69551990, 69551994, 69551998, 69552002, 69552006, 69552010, 69552014,
69552018, 69552022, 69552026, 69552030, 69552034, 69552038, 69552042,
69552046, 69552050, 69552054, 69552058, 69552062, 69552066, 69552070,
69552074, 69552078, 69552082, 69552086, 69552090, 69552094, 69552098,
69552102, 69552106, 69552110, 69552114, 69552118, 69552122, 69552126,
69552130, 69552134, 69552138, 69552142, 69552146, 69552150, 69552154,
69552158, 69552162, 69552166, 69552170, 69552174, 69552178, 69552182,
69552186, 69552190, 69552194, 69552198, 69552202, 69552206, 69552210,
69552214, 69552218};
System.arraycopy(temp, 0, prob, prob.length - temp.length, temp.length);
}
private static int[] chars;
private static void populateChars1() {
chars = new int[10002];
int[] temp = new int[] {32, 9, 10, 101, 97, 13, 105, 111,
110, 116, 114, 115, 108, 100, 99, 117, 109, 104, 112, 103, 48, 46,
98, 49, 160, 102, 50, 118, 121, 107, 44, 119, 45, 58, 51, 53, 52,
57, 56, 106, 54, 122, 55, 47, 41, 40, 124, 120, 1103, 1072, 1086,
113, 1080, 1575, 1077, 1085, 1090, 12540, 1088, 12398, 95, 1089, 39,
1604, 33, 233, 12290, 30340, 1083, 1074, 12289, 12531, 1082, 12356,
34, 3634, 91, 93, 63, 62, 1076, 225, 1605, 1084, 3609, 1610, 12395,
12375, 1585, 1087, 1608, 12391, 12488, 3619, 1091, 12390, 243, 12377,
1606, 61, 3629, 12473, 1578, 12427, 42, 12394, 12452, 12483, 12383,
12539, 3656, 12392, 3648, 12434, 3585, 12414, 12399, 237, 38, 19968,
12523, 1075, 20154, 12463, 252, 3617, 305, 3657, 3591, 59, 12364,
1073, 1583, 1099, 1079, 1576, 20013, 224, 3633, 12363, 26085, 1607,
43, 228, 12522, 12435, 12521, 12426, 12387, 22823, 3623, 24180, 231,
12450, 3621, 3618, 26377, 1100, 3604, 1081, 1587, 1593, 29992, 3637,
12425, 37, 246, 26032, 3588, 19981, 3626, 12373, 12418, 26159, 12371,
60, 21697, 22312, 26376, 3607, 12464, 3636, 3610, 1095, 12471, 12525,
2366, 19978, 12362, 126, 12358, 187, 12503, 227, 12479, 12428, 1577,
3627, 1093, 25105, 12524, 12367, 3605, 945, 20998, 20250, 12489, 26412,
12501, 183, 23398, 12467, 22269, 29983, 1601, 273, 3021, 8220, 8221,
20316, 1602, 1603, 35, 25991, 12472, 20102, 12513, 64, 3632, 12354,
12502, 12365, 22320, 20986, 34892, 23376, 32593, 51060, 21457, 12459,
21517, 8230, 2381, 19979, 1497, 12384, 2352, 1493, 36, 1078, 12486,
1740, 12510, 23567, 8226, 32773, 1600, 1588, 234, 26041, 959, 26368,
3611, 26102, 12496, 12469, 1094, 23478, 1581, 3405, 20837, 3614, 3649,
250, 22238, 964, 20010, 24773, 20844, 24066, 20197, 29702, 953, 1609,
1110, 21512, 949, 34920, 12461, 351, 20840, 21069, 35201, 20107, 33258,
12424, 1580, 232, 1101, 20214, 12481, 12300, 3652, 26009, 3586, 25163,
12301, 3592, 21644, 21487, 33021, 12304, 12451, 21830, 8211, 322,
1096, 2325, 12305, 22825, 25104, 12369, 39640, 21152, 12512, 3660,
12385, 241, 20026, 3639, 20869, 23450, 20449, 1092, 4304, 22909, 25968,
37329, 22810, 12458, 26469, 3640, 30005, 21040, 27861, 24037, 19994,
957, 4312, 12381, 3641, 26426, 30475, 37096, 26178, 2375, 24515, 169,
12491, 92, 3594, 32654, 31532, 12388, 24615, 12517, 28857, 12454,
21306, 2344, 36890, 12415, 65533, 12379, 244, 1492, 1377, 12499, 963,
2367, 28961, 20027, 26399, 32034, 45796, 35770, 255, 432, 12487, 12456,
22899, 20182, 25152, 29289, 12519, 44592, 3277, 1102, 12515, 1582,
226, 1589, 20307, 1586, 30011, 2360, 31995, 353, 29256, 229, 12393,
20851, 21160, 36947, 38388, 1571, 1500, 20110, 8212, 39029, 961, 26126,
12417, 27700, 12360, 2965, 3650, 30456, 36825, 12497, 3651, 26684,
28023, 3149, 1512, 31038, 24230, 24215, 20870, 22577, 1514, 12475,
22270, 12420, 30331, 12511, 30446, 94, 12372, 38754, 26381, 30693,
12431, 25945, 21518, 22806, 26356, 954, 21451, 23665, 35211, 2340,
27880, 21205, 3007, 960, 2350, 21270, 23433, 1591, 2368, 29305, 20301,
20320, 12490, 39064, 32463, 21147, 31034, 51648, 20135, 21033, 23601,
24687, 38382, 19977, 37117, 24335, 44032, 951, 4308, 2354, 21153,
3655, 21516, 12509, 269, 21271, 7841, 8364, 9733, 25237, 31449, 12480,
20204, 2980, 38291, 20445, 1502, 21496, 51032, 3009, 49828, 20803,
36164, 281, 2351, 45716, 12506, 20140, 24403, 36865, 21495, 20043,
20351, 38598, 235, 12474, 7871, 23545, 49324, 24847, 27425, 236, 20195,
24471, 956, 26908, 347, 1488, 31185, 47196, 261, 2346, 1489, 12441,
24320, 171, 20385, 32447, 54616, 35352, 380, 38480, 125, 27963, 50640,
287, 23458, 3635, 1097, 7879, 123, 3263, 22120, 12484, 7843, 601,
955, 19982, 12527, 31561, 39318, 12493, 36710, 31649, 20215, 30495,
20132, 35828, 22914, 27491, 12408, 1398, 21407, 22580, 1590, 25552,
35328, 44256, 21046, 962, 2357, 27671, 2379, 35199, 965, 3248, 257,
20108, 49884, 382, 20063, 36807, 20040, 1513, 51064, 24863, 35780,
23481, 47532, 12455, 26524, 51088, 25216, 2306, 245, 29616, 24314,
35013, 21335, 21462, 29255, 26597, 31572, 37325, 19987, 33394, 54620,
1705, 12465, 21578, 4320, 25151, 35299, 38899, 20170, 21475, 12495,
24179, 31243, 31354, 25253, 21839, 12500, 31934, 30528, 2361, 26989,
35270, 20854, 37324, 27969, 23383, 12514, 12376, 28216, 25910, 24433,
30476, 4153, 3262, 35774, 19975, 2986, 1408, 32852, 22411, 12477,
48372, 22797, 21450, 12419, 23454, 36827, 39135, 9632, 253, 9658,
4321, 259, 25628, 36335, 12460, 240, 2990, 45768, 20687, 32771, 3391,
37327, 21326, 21488, 12507, 248, 223, 24605, 38651, 96, 20855, 12429,
12397, 35745, 3349, 31435, 24819, 49436, 2992, 24191, 24341, 3120,
22522, 51012, 21592, 1400, 50500, 25509, 24212, 12505, 38271, 24405,
7897, 26080, 24030, 24120, 33457, 20809, 22478, 12298, 20876, 27714,
1504, 20184, 7899, 35831, 12299, 3612, 20309, 32423, 3134, 20048,
27665, 36733, 20379, 19990, 28040, 26481, 1574, 3606, 26360, 3135,
23453, 30000, 26415, 7845, 3006, 28982, 24744, 21435, 176, 2750, 1501,
36215, 31070, 30330, 27604, 25512, 36824, 22330, 19996, 30007, 230,
38306, 27231, 51221, 1381, 27005, 2975, 22363, 4317, 21482, 20808,
25345, 35777, 3137, 36523, 32946, 36554, 36817, 21307, 31867, 38376,
51068, 25918, 26143, 947, 3265, 25143, 23637, 26435, 7889, 242, 50612,
12468, 33521, 38498, 26631, 943, 31295, 12400, 35239, 12449, 2342,
24086, 1506, 3368, 21338, 12504, 37682, 20070, 21313, 249, 23569,
25351, 35805, 27809, 30740, 29233, 25903, 49688, 1491, 7901, 7853,
46020, 26408, 24067, 1573, 20171, 37197, 2369, 1594, 2327, 263, 26465,
45824, 25171, 25919, 3603, 28909, 32780, 31456, 28304, 948, 7873,
24460, 26495, 3376, 51204, 37027, 30333, 26696, 3240, 38283, 24456,
12508, 940, 51228, 20877, 30334, 39057, 3624, 4315, 3390, 49345, 238,
36153, 30721, 24029, 9734, 32622, 20225, 20849, 21463, 53944, 22235,
21161, 21543, 36796, 26657, 51008, 25110, 30028, 2332, 27492, 21608,
34255, 20889, 2997, 3221, 21521, 4314, 12494, 30001, 24555, 27004,
27743, 21476, 22770, 30452, 2494, 417, 1495, 969, 46972, 24050, 1569,
3112, 1579, 28779, 1508, 2994, 12409, 2985, 31119, 20219, 21333, 12457,
26053, 165, 44536, 32004, 2348, 35760, 22791, 36899, 3595, 23558,
22240, 9830, 35373, 3615, 31181, 20160, 1511, 35441, 12466, 36141,
3223, 3122, 22763, 1584, 38263, 32769, 12470, 7911, 29579, 4305, 22303,
1199, 21442, 50896, 51452, 20462, 28165, 20256, 35821, 45208, 20813,
24418, 972, 32479, 26448, 39118, 35413, 1387, 3270, 21021, 21015,
46300, 23436, 3608, 3238, 31350, 36895, 1570, 24072, 7875, 35813,
3074, 22768, 1499, 21002, 21253, 1548, 34987, 37326, 4316, 1662, 20303,
3393, 26679, 7847, 4152, 35797, 50836, 38750, 26395, 36896, 21508,
26131, 35835, 3236, 35486, 2335, 24517, 21035, 21029, 44172, 21453,
29699, 12378, 44396, 30149, 39321, 3638, 46041, 7883, 1711, 29694,
12423, 3364, 4140, 32032, 3616, 8222, 3250, 27835, 59179, 36229, 3093,
23627, 25506, 7907, 27468, 54868, 22836, 941, 8594, 22826, 23550,
20491, 23460, 30707, 3256, 27454, 32467, 9679, 20581, 27668, 20415,
31246, 33391, 25165, 26410, 20116, 36873, 3654, 36816, 1410, 12442,
36074, 49457, 38500, 1505, 21019, 25307, 36716, 2480, 21619, 54644,
3625, 24049, 25490, 30701, 47484, 2330, 3016, 2736, 191, 21729, 1257,
1098, 30041, 49548, 25103, 48708, 20570, 31080, 21151, 37202, 31169,
20174, 27169, 49888, 20123, 51109, 25454, 32929, 35215, 4309, 32080,
25972, 25913, 180, 2970, 50689, 38738, 20294, 12302, 2991, 21345,
20104, 32218, 35443, 12403, 23455, 215, 20999, 23548, 31215, 32473,
30058, 30465, 23384, 48512, 28145, 12303, 4307, 47928, 24859, 26519,
2995, 33410, 50857, 24535, 12516, 39564, 32452, 36148, 942, 20004,
27096, 3370, 38988, 36617, 38405, 26149, 28436, 29366, 23798, 38450,
36984, 24635, 21360, 35336, 8250, 966, 24110, 32048, 36820, 2509,
24247, 36861, 3253, 3378, 174, 163, 186, 26449, 36719, 12416, 254,
51080, 36009, 23616, 47560, 1396, 32454, 29031, 31639, 29575, 3597,
3246, 33853, 38395, 2503, 36136, 54924, 35265, 24182, 2622, 24352,
23621, 48120, 2358, 22987, 7885, 44277, 36039, 31505, 3202, 50668,
24425, 4145, 20987, 35268, 952, 25773, 251, 967, 3128, 12411, 7909,
283, 23494, 47564, 32476, 33616, 3851, 2728, 30010, 20799, 33829,
49464, 3375, 24378, 44397, 4323, 4322, 22788, 1749, 2337, 3359, 36023,
9834, 299, 1496, 24590, 31859, 25522, 38144, 7891, 26354, 12462, 36798,
20080, 47924, 26045, 275, 7903, 337, 1391, 22253, 12498, 1490, 32844,
44060, 38656, 21464, 22905, 35843, 7921, 7913, 8251, 2309, 8218, 35758,
20540, 51004, 35753, 50724, 32534, 21209, 38451, 21363, 4096, 44284,
324, 46308, 20139, 239, 20302, 2495, 22495, 22793, 2765, 2759, 8224,
45236, 35069, 3114, 21150, 31616, 3125, 36275, 345, 1112, 44221, 29987,
3247, 33267, 23130, 3384, 21315, 161, 7855, 31163, 40644, 27494, 30424,
36234, 28201, 21806, 22242, 20363, 39532, 3330, 4311, 35501, 25214,
29260, 25226, 2993, 28207, 35748, 3381, 36208, 27599, 20856, 4121,
50976, 24102, 40857, 26223, 35814, 31216, 25928, 35759, 8482, 51312,
35266, 3242, 35937, 24459, 44544, 21448, 3108, 2752, 27833, 25112,
2472, 27770, 23646, 20248, 51652, 27979, 29609, 20934, 30524, 4143,
24195, 2370, 35782, 24453, 4141, 3374, 1735, 50672, 2608, 2984, 32418,
1592, 36942, 12370, 39033, 1510, 4112, 24540, 1397, 54252, 34880,
38463, 27426, 30003, 26413, 8203, 27827, 50864, 36135, 20915, 26222,
36830, 25252, 9670, 31687, 30906, 35272, 3118, 1407, 167, 44288, 12518,
20843, 3377, 33647, 7919, 20845, 39365, 4100, 8249, 53552, 35810,
27515, 26666, 20811, 31665, 25353, 8722, 23500, 35469, 1503, 31574,
4306, 26144, 51077, 21322, 21916, 47784, 22336, 21490, 47732, 29577,
38918, 38469, 24231, 26031, 26089, 7917, 1111, 24503, 12406, 12368,
22659, 946, 24220, 27773, 28858, 23572, 21629, 26681, 32232, 3762,
12402, 33322, 27573, 40657, 26512, 26174, 279, 20891, 31278, 48169,
24577, 26371, 39764, 23427, 33402, 21452, 24211, 12374, 34915, 3110,
1179, 35789, 26494, 35542, 9472, 29615, 27982, 26029, 1614, 9474,
30332, 21834, 50504, 33041, 22812, 2734, 35874, 7893, 23041, 12293,
39080, 9500, 50868, 21548, 27874, 32068, 21382, 3737, 21334, 24052,
20122, 50948, 20241, 25511, 22855, 36939, 36130, 32500, 50556, 22686,
33879, 30382, 3103, 20061, 26446, 20505, 177, 3119, 973, 24065, 31614,
32066, 28246, 25289, 32856, 32154, 20064, 25215, 21547, 28608, 54617,
9660, 33268, 2339, 22833, 181, 26680, 31227, 39044, 32676, 2349, 48148,
37319, 339, 1114, 164, 27597, 36948, 36578, 32887, 27490, 54840, 8225,
32076, 39030, 38134, 23713, 20960, 20030, 47308, 4117, 35282, 20181,
2343, 53356, 21513, 25293, 170, 35519, 19969, 20117, 2709, 50629,
178, 3095, 36092, 24076, 36814, 44368, 38190, 2453, 1405, 21527, 53440,
26063, 1108, 25442, 36131, 35895, 51201, 2616, 20805, 54408, 2376,
51473, 51020, 24613, 39006, 25126, 26397, 22871, 49373, 3257, 33324,
38065, 20892, 24565, 20221, 3379, 54532, 46356, 2319, 23578, 37038,
27493, 49440, 49845, 1406, 12422, 22259, 47588, 27983, 23448, 22827,
30830, 1105, 27611, 3244, 22290, 24235, 36755, 26816, 35768, 22799,
2310, 34899, 30053, 2741, 3251, 21312, 26500, 20778, 21507, 9829,
35746, 32862, 4313, 20859, 31036, 24494, 3231, 38142, 12401, 39208,
31881, 20037, 23487, 2631, 1494, 8240, 22343, 35910, 22283, 1670,
371, 39046, 25925, 1392, 32057, 38431, 3233, 24178, 34903, 28459,
38272, 51076, 3398, 33590, 182, 47112, 19971, 22530, 2476, 32178,
24046, 2763, 27531, 3143, 27915, 3147, 35273, 12366, 2359, 36739,
2724, 21319, 51116, 44228, 2690, 36753, 49892, 25658, 20113, 45380,
20114, 52380, 2326, 52824, 24207, 47749, 1116, 35500, 24111, 21738,
6098, 21942, 22996, 38590, 32207, 1388, 29486, 33756, 21387, 2488,
33487, 48516, 2623, 24375, 30103, 2479, 7863, 46321, 9675, 36949,
44144, 1118, 38609, 49885, 20041, 52852, 23626, 28010, 39134, 54028,
3658, 23416, 36793, 28082, 7915, 49328, 25209, 3015, 21017, 3105,
47785, 45936, 52404, 28168, 29275, 22521, 23475, 30772, 363, 23425,
53664, 1567, 50900, 33865, 51089, 21048, 54633, 33539, 172, 2624,
4334, 45432, 22856, 23395, 4123, 52628, 44036, 21095, 24213, 3098,
31471, 27941, 21378, 1744, 30410, 29677, 21177, 29420, 28120, 4116,
39280, 47084, 25240, 23401, 974, 27721, 50752, 38555, 1107, 28385,
23470, 33310, 38442, 402, 47932, 36187, 36027, 38957, 2744, 20917,
20633, 23429, 27801, 27010, 3271, 21542, 26379, 24651, 39340, 38477,
33609, 3403, 12476, 21355, 36914, 26234, 21336, 35703, 4328, 35838,
25915, 27849, 27704, 38543, 26044, 25321, 25563, 2341, 26497, 35430,
28155, 20284, 21010, 32905, 9473, 23822, 27927, 54032, 31508, 45800,
38169, 35531, 36938, 12532, 21320, 3784, 39443, 184, 22885, 31192,
4126, 47197, 38597, 38745, 3354, 20339, 24198, 20358, 44163, 4129,
33509, 36259, 24107, 2751, 2482, 36913, 162, 31168, 3142, 31105, 1115,
54665, 20029, 20381, 12520, 4124, 35686, 31179, 21028, 24038, 2313,
20852, 44552, 2598, 3785, 3136, 35757, 2979, 2581, 2478, 33719, 31461,
2311, 25805, 19988, 21491, 35222, 21704, 35785, 20146, 20853, 50696,
34276, 51200, 1119, 12353, 20105, 36866, 21439, 27966, 19997, 32422,
2730, 38634, 38505, 32493, 39636, 48156, 2600, 20083, 36828, 24237,
23554, 39000, 20919, 3014, 9492, 1385, 22870, 6070, 21892, 47700,
7887, 21709, 38632, 24202, 26862, 2949, 24373, 36848, 8213, 2738,
188, 47000, 24441, 36889, 38889, 34701, 21454, 46104, 53685, 44053,
12405, 23089, 33464, 35775, 1379, 45224, 27431, 36864, 38081, 45348,
24800, 24184, 36125, 34955, 37504, 35848, 3713, 27178, 49353, 2347,
35468, 31361, 32461, 31199, 54000, 20848, 25285, 9633, 32972, 25588,
2404, 26522, 23618, 27602, 22920, 4154, 44148, 54624, 44160, 38556,
4101, 26434, 22830, 52572, 1409, 38468, 24448, 20551, 33775, 35752,
1729, 20418, 39302, 25147, 2474, 35802, 22323, 32599, 48264, 35527,
49444, 7877, 168, 36731, 20142, 38795, 2951, 48376, 36319, 30828,
38472, 30171, 21602, 45908, 3363, 52264, 27083, 21215, 21183, 20826,
3228, 2468, 4318, 23612, 1380, 1113, 27744, 48176, 8206, 21327, 32508,
30151, 25144, 20247, 21364, 1384, 8658, 20234, 38917, 36794, 28288,
23432, 26641, 3593, 36766, 30002, 23556, 45684, 21560, 21016, 38913,
3116, 7881, 36855, 65279, 25668, 20943, 29190, 1106, 30431, 23519,
3399, 54168, 8195, 48152, 32102, 175, 26800, 32440, 1746, 25391, 9650,
23186, 355, 21628, 21047, 25705, 40635, 20313, 52636, 189, 1616, 32426,
30097, 32026, 32435, 37240, 166, 45817, 26230, 27508, 54788, 21051,
24907, 2996, 35251, 27954, 1611, 22359, 26723, 48660, 33145, 20020,
27719, 26202, 32455, 31309, 37070, 38596, 30274, 2613, 9482, 54588,
32722, 2735, 3732, 50669, 28789, 21672, 2596, 3275, 26411, 30417,
20253, 20196, 7849, 27850, 36884, 20165, 38050, 22260, 1412, 26550,
25480, 27841, 25173, 20260, 21213, 31777, 27497, 38663, 26367, 28783,
48277, 35834, 35841, 54980, 958, 23492, 39184, 3353, 2610, 24449,
52397, 20572, 38706, 44608, 35696, 50630, 3757, 23681, 22266, 27161,
6042, 38647, 3776, 38522, 26790, 20185, 32456, 33287, 3019, 37444,
2617, 23707, 23459, 2753, 8595, 20516, 25239, 48260, 27211, 32477,
38761, 20498, 32933, 25955, 32763, 24187, 3613, 29399, 21531, 53076,
24149, 35388, 34917, 36196, 367, 35762, 27663, 3266, 50577, 21344,
29105, 361, 4330, 30427, 31569, 47476, 27036, 38215, 25551, 40658,
44048, 22992, 37239, 12619, 12382, 36969, 51649, 29238, 772, 22294,
3351, 4325, 2969, 2602, 3226, 21483, 36149, 38989, 35342, 24481, 24536,
4156, 47140, 26432, 3100, 23553, 27810, 24746, 36008, 34013, 36935,
31186, 4097, 4324, 38626, 3366, 3719, 33510, 38364, 20304, 48124,
4151, 3264, 36152, 24322, 7867, 29483, 47568, 9608, 23614, 39154,
23452, 33655, 38470, 27177, 29664, 27507, 3630, 21367, 190, 34382,
2463, 29872, 26579, 51665, 32511, 22971, 26619, 39592, 21103, 2635,
23613, 21478, 27442, 54540, 20202, 36611, 27996, 38381, 28310, 28286,
32113, 32321, 25976, 20493, 3394, 179, 32097, 12412, 3761, 44620,
950, 38138, 25343, 45784, 40670, 36879, 20912, 1394, 26893, 23653,
2606, 28988, 21733, 25937, 47141, 21106, 1617, 21018, 44208, 51333,
21477, 357, 2497, 36127, 23431, 247, 33050, 25774, 33303, 2492, 24444,
2716, 1378, 51216, 3138, 1726, 3751, 22721, 31821, 48149, 24188, 22969,
8593, 25246, 3018, 6035, 29790, 38914, 20006, 49569, 38386, 29087,
24040, 1402, 40060, 1241, 1615, 49549, 35498, 36175, 54364, 2312,
7851, 44428, 2604, 35242, 30343, 1187, 25176, 54664, 27888, 2672,
28814, 53468, 26152, 24930, 378, 32932, 21381, 38544, 2364, 23566,
25033, 22243, 38047, 31069, 20908, 27138, 26292, 22280, 32681, 34507,
32819, 1171, 23721, 28151, 20016, 27993, 23381, 12389, 3745, 31383,
33337, 48652, 24133, 3235, 2562, 21494, 34220, 39035, 2726, 32013,
20419, 21809, 48320, 20816, 31359, 21220, 3942, 23457, 28526, 25324,
20914, 32025, 21862, 30064, 20055, 3254, 44305, 21361, 26757, 35672,
732, 26366, 36339, 185, 29066, 20005, 23546, 3372, 24109, 38627, 35611,
51656, 54632, 3760, 4155, 710, 20276, 31680, 38236, 20497, 2336, 2588,
24466, 3738, 20839, 46108, 1572, 2745, 3205, 53412, 32147, 50557,
35946, 2958, 3077, 3765, 36001, 24693, 53580, 1618, 26576, 33073,
50872, 38996, 21050, 4310, 4157, 27598, 31958, 21551, 23631, 23064,
24310, 24039, 38646, 32858, 24656, 50808, 26087, 6036, 22025, 24618,
20896, 35377, 20315, 26472, 23565, 49900, 303, 22815, 32451, 4332,
50632, 1498, 20081, 12380, 36062, 4146, 26007, 50508, 20065, 20874,
36996, 35442, 33016, 24739, 22919, 35338, 28006, 20992, 20474, 2620,
30342, 32487, 6016, 2719, 54805, 37089, 24196, 29378, 24489, 21402,
7865, 32039, 46160, 48373, 3530, 36317, 6040, 21066, 20652, 54872,
25484, 20729, 25505, 39740, 36024, 20966, 31689, 20024, 297, 47336,
39034, 31526, 32908, 29359, 40092, 2711, 32043, 2732, 23560, 24112,
2507, 39278, 36032, 39069, 6047, 45733, 20861, 36000, 39038, 50528,
25191, 2470, 32117, 51592, 25554, 27402, 52488, 25346, 35823, 12541,
27798, 24576, 25645, 21024, 24351, 26263, 35613, 4122, 31481, 2331,
26477, 21332, 26332, 3600, 48324, 44201, 4106, 38867, 22902, 3356,
4142, 1734, 26725, 39304, 3749, 28020, 36129, 36842, 33180, 7895,
33635, 25630, 36991, 44033, 32000, 33026, 44540, 36012, 55176, 35302,
3906, 22679, 23544, 25463, 25311, 24093, 20159, 23447, 26463, 48520,
47728, 3392, 38281, 52293, 21776, 7869, 34394, 28895, 3255, 9671,
35036, 52376, 46412, 26997, 45804, 22995, 49496, 29273, 295, 36718,
12534, 28966, 26479, 20511, 40575, 27873, 21109, 22256, 29976, 22352,
3129, 32701, 32431, 30784, 8801, 33014, 12316, 2673, 333, 27605, 47536,
8470, 326, 1404, 3659, 32993, 29356, 22918, 24059, 21073, 30070, 1389,
44553, 3954, 26124, 20025, 36028, 25935, 24778, 45572, 3008, 2455,
22609, 12492, 32260, 24464, 51613, 369, 4326, 2742, 2439, 3010, 30563,
23506, 2460, 23792, 50892, 30142, 12478, 8730, 26262, 7857, 30436,
39131, 3333, 32842, 36605, 39749, 36035, 3144, 32570, 3274, 37073,
24895, 49465, 26588, 25276, 39178, 12413, 46988, 21058, 48143, 31085,
36305, 40664, 33080, 22307, 36805, 50506, 46993, 21171, 26071, 32784,
22818, 50728, 26082, 32884, 1709, 53804, 49696, 2625, 35914, 30561,
23485, 21127, 29986, 27784, 23615, 54856, 40165, 38452, 28204, 23551,
54217, 3538, 28771, 318, 3754, 32988, 23467, 3921, 3771, 31454, 25361,
9678, 32618, 35506, 7929, 24377, 45812, 21311, 28187, 35799, 20465,
20596, 45320, 34399, 3964, 9516, 30423, 26242, 21621, 54637, 39068,
33288, 38520, 35387, 12421, 38024, 33150, 46021, 34429, 35504, 21191,
26716, 34180, 26691, 54876, 52964, 24115, 35370, 35379, 29123, 28193,
24402, 3505, 25688, 26480, 36213, 1383, 25481, 26639, 23547, 45216,
9618, 52768, 28369, 32990, 22635, 28287, 26106, 38534, 47492, 38752,
48155, 54200, 36882, 45813, 3385, 8592, 20210, 38542, 52286, 23526,
37636, 49352, 23439, 33945, 50977, 27905, 47549, 1399, 52712, 45212,
6031, 20489, 36960, 21414, 20180, 4139, 24537, 3735, 32118, 36664,
21218, 35023, 25265, 3245, 51339, 24369, 36557, 27973, 44400, 20001,
27794, 27193, 38538, 49437, 25244, 35793, 28595, 30719, 48177, 4150,
20046, 21917, 24694, 20161, 1390, 21556, 38525, 4102, 23736, 34101,
50732, 39277, 28070, 21561, 22362, 29482, 49692, 51456, 3361, 3127,
29645, 52285, 32020, 53364, 52292, 39746, 47448, 36870, 27503, 2953,
3239, 2721, 2371, 25439, 12359, 20961, 20129, 38911, 40481, 48288,
47144, 22612, 31283, 45843, 20860, 21934, 32650, 39770, 53469, 24681,
3383, 32244, 8734, 37030, 34411, 3590, 20804, 54596, 35079, 25317,
3382, 22258, 28798, 40845, 53945, 2566, 4327, 23562, 50416, 50501,
20598, 27427, 48513, 24748, 8804, 28872, 22338, 1722, 9507, 31455,
3926, 38075, 39537, 1739, 54869, 20057, 30913, 26195, 3725, 2489,
25187, 19976, 21063, 37266, 40784, 23456, 25201, 25731, 32210, 24597,
44057, 46976, 24291, 1742, 26580, 30418, 22863, 6020, 1736, 40614,
31478, 54256, 28784, 35226, 4144, 12407, 32553, 40736, 20648, 40065,
20882, 12396, 45376, 47672, 23039, 23380, 20262, 21169, 21807, 22937,
316, 28129, 36786, 30435, 36151, 31563, 50676, 33740, 35009, 20928,
22841, 20255, 24785, 2447, 47548, 27578, 50616, 35044, 45912, 3777,
39151, 32005, 35422, 47480, 24935, 36650, 24452, 20249, 28072, 54056,
4118, 22278, 33437, 2328, 20405, 32536, 25138, 20439, 36067, 22351,
20384, 26157, 2338, 2583, 23517, 3000, 2438, 3342, 25277, 9488, 28903,
1382, 29392, 23559, 35465, 20173, 49332, 29978, 23142, 36020, 28014,
52828, 22622, 23156, 6043, 63243, 26792, 3755, 20964, 3126, 968, 1958,
28271, 24525, 32925, 23385, 23486, 40763, 9642, 1201, 12453, 8805,
8776, 9478, 47566, 3620, 28363, 26564, 24499, 9553, 12307, 32047,
38321, 22681, 31062, 3661, 37322, 39550, 8745, 44152, 38145, 26700,
35786, 20559, 36763, 25196, 26417, 38548, 47200, 21734, 25569, 23610,
26286, 26970, 29748, 27683, 22311, 2486, 34966, 2305, 20280, 24658,
1403, 21162, 27818, 33109, 26834, 1688, 36973, 30952, 9617, 8231,
49468, 2465, 37109, 1507, 8208, 28079, 35386, 25964, 38920, 52280,
21092, 32879, 32489, 21416, 33136, 3938, 22805, 54744, 52840, 22524,
33298, 35206, 49660, 49849, 20685, 3207, 55148, 25250, 26228, 28418,
30422, 33459, 51208, 3520, 36681, 36134, 38972, 20272, 9576, 26364,
38772, 48128, 52629, 20659, 46304, 35712, 26118, 2626, 2694, 29287,
2714, 2565, 30496, 54693, 31077, 32094, 23244, 27785, 48036, 2693,
40599, 23435, 9600, 36867, 27530, 33891, 46608, 2725, 54021, 26333,
2586, 47088, 9578, 29572, 27931, 24754, 33033, 34907, 33104, 26753,
9524, 23563, 3272, 21746, 9619, 33778, 28716, 3400, 26391, 2950, 25581,
22696, 45720, 3631, 24598, 32724, 24080, 22346, 3764, 23043, 3733,
38378, 36741, 49340, 20426, 3739, 23110, 25235, 1401, 25499, 6086,
28508, 38936, 9552, 31890, 36190, 52992, 29980, 29942, 29240, 21009,
32173, 30284, 27839, 3923, 3482, 52980, 21331, 21568, 38915, 21484,
28392, 20599, 44600, 2377, 26611, 2380, 33495, 33151, 58853, 36829,
36133, 38182, 3206, 25313, 32791, 36951, 38454, 31558, 38712, 30246,
2591, 22727, 12685, 63688, 3908, 40636, 1109, 8704, 2355, 47581, 36186,
24321, 24509, 32340, 33618, 24544, 46384, 1169, 48624, 4222, 40723,
33707, 4171, 3512, 3111, 36963, 24745, 2496, 44061, 35037, 23652,
3602, 9496, 27901, 30690, 2723, 2727, 31245, 48337, 38518, 32937,
3535, 54140, 3514, 8811, 63242, 26059, 25954, 32943, 33832, 36341,
3714, 1968, 33406, 25340, 3716, 2458, 12404, 25269, 20206, 50472,
25140, 20693, 3214, 4331, 21172, 9604, 24594, 32854, 2632, 2595, 28009,
28041, 9532, 6071, 22068, 6033, 33395, 27934, 32302, 35889, 12355,
47792, 32974, 3767, 4244, 20975, 24125, 54889, 3515, 38083, 6038,
27171, 25193, 3117, 28431, 20663, 33713, 26690, 25613, 6041, 20391,
47004, 28139, 44200, 6091, 30722, 33261, 38459, 50644, 29141, 3628,
35330, 22900, 30059, 22865, 37347, 328, 2333, 20035, 37101, 36797,
29436, 51217, 30805, 4113, 47100, 34913, 3501, 35029, 20271, 45367,
40479, 36575, 33673, 44192, 3742, 36880, 24382, 20134, 3146, 31348,
50620, 28096, 37341, 3079, 27687, 2324, 26086, 38322, 35064, 3956,
49552, 20094, 38453, 2972, 27748, 711, 28342, 3599, 33694, 27735,
51676, 3371, 39854, 23703, 3373, 46973, 30908, 27807, 3380, 23696,
25973, 30123, 32441, 44760, 8207, 20989, 8236, 35477, 22618, 8451,
39039, 33489, 38155, 26460, 3367, 36104, 3936, 4329, 34588, 50756,
20841, 3115, 3402, 9572, 22934, 28809, 33455, 34425, 29827, 25514,
9312, 44508, 40836, 24518, 37492, 29554, 52509, 34214, 28818, 27946,
6021, 31206, 30130, 28511, 8319, 39166, 13217, 46028, 20223, 2582,
2733, 23019, 20940, 33126, 26694, 2459, 29028, 3335, 26781, 23233,
36857, 26575, 36745, 33836, 28404, 20044, 38642, 32966, 9565, 25106,
36300, 33804, 38428, 27583, 54609, 28034, 27877, 2477, 32963, 9571,
3358, 32209, 30636, 26538, 31908, 34385, 3722, 28748, 44204, 33576,
35731, 29618, 51096, 26216, 3209, 25299, 2703, 38108, 6072, 3789,
9313, 23068, 27396, 35264, 3078, 25429, 4239, 55092, 32442, 9557,
27542, 24324, 29245, 47561, 25381, 9563, 38360, 32531, 26441, 2434,
26628, 20056, 37857, 9564, 3665, 25331, 4017, 34389, 12297, 20957,
25298, 52384, 47553, 25943, 3523, 36367, 48276, 21097, 29916, 32626,
3598, 22633, 25308, 3540, 28176, 31807, 28845, 25026, 52649, 33747,
51313, 47049, 28248, 3334, 21330, 3769, 36843, 1962, 38485, 47803,
1657, 26194, 3962, 36742, 26172, 23588, 30127, 38177, 36214, 32959,
32882, 20982, 36992, 40802, 20179, 27424, 20018, 28450, 25932, 24674,
27745, 9475, 20740, 29627, 48292, 33146, 3928, 32764, 36941, 1927,
32318, 26421, 35722, 35010, 3939, 21193, 44264, 26525, 22296, 3107,
39569, 39658, 2637, 22615, 19992, 28171, 37034, 31684, 39575, 2454,
26609, 26825, 24736, 9559, 6081, 32317, 33529, 20126, 24223, 21365,
31726, 50880, 25130, 21247, 35041, 33293, 22868, 25975, 24422, 38929,
8242, 24500, 32439, 4120, 2715, 34218, 32291, 28330, 27298, 3720,
25671, 1509, 36933, 38928, 12296, 4757, 37291, 26132, 51105, 289,
37228, 24062, 32420, 3302, 25233, 50520, 35261, 9569, 6076, 27713,
21943, 27155, 35033, 37428, 8976, 24163, 12530, 25142, 26049, 12306,
9580, 24069, 36194, 24467, 32958, 54861, 54952, 23531, 45712, 22369,
21368, 49325, 291, 26092, 9654, 25286, 27284, 32645, 8706, 32224,
21170, 36981, 36965, 39376, 24189, 9508, 7923, 24140, 2710, 30416,
26705, 20420, 37969, 4160, 53216, 33777, 47161, 35657, 32153, 25014,
26119, 28860, 25424, 36986, 30244, 2334, 9568, 3780, 28378, 1613,
26001, 24478, 9562, 8729, 4114, 28902, 2696, 23542, 38149, 21654,
9495, 31049, 49836, 51600, 34678, 31895, 27489, 30086, 21696, 54844,
49800, 9567, 21682, 30473, 9661, 50688, 27627, 23396, 9561, 21427,
21443, 3601, 21570, 48380, 29943, 29467, 54728, 27475, 36321, 34349,
3779, 27891, 31896, 48736, 31281, 8194, 3237, 1960, 22218, 27882,
24323, 34183, 33538, 40654, 2451, 6075, 27875, 36724, 32928, 30862,
30555, 3853, 36393, 44275, 36235, 33900, 21576, 36771, 2329, 24742,
33108, 22374, 21514, 29595, 25402, 9574, 38684, 28797, 20937, 23476,
38515, 36801, 32433, 26165, 3123, 32472, 28580, 33256, 50613, 39511,
51316, 29038, 24490, 34269, 12308, 1964, 30899, 24796, 24033, 9577,
29239, 36180, 12361, 20818, 25644, 24708, 23507, 23529, 45576, 3517,
775, 12309, 12640, 21741, 26361, 44480, 23731, 22985, 24551, 36291,
29926, 2323, 23576, 8359, 23449, 25720, 8718, 50529, 28611, 20237,
30196, 2475, 6082, 44257, 22922, 2731, 35258, 22982, 23389, 23195,
21857, 9555, 36776, 36328, 25136, 20141, 2754, 37057, 9484, 25670,
34081, 34923, 28781, 32736, 38517, 24815, 8992, 22475, 2437, 24713,
26885, 53080, 1922, 24344, 50980, 30879, 35859, 49844, 30021, 47592,
39048, 35825, 47101, 31570, 6044, 30865, 23574, 36192, 2603, 33714,
33976, 9558, 2962, 36920, 24904, 8993, 51460, 3086, 20387, 2471, 1683,
33075, 9575, 20239, 9566, 22766, 21223, 48393, 36777, 8721, 3503,
34746, 33738, 9651, 23490, 35492, 3243, 26093, 30887, 7905, 4147,
20538, 9825, 25200, 2441, 23305, 7927, 24573, 29157, 26187, 38519,
23888, 22443, 20607, 47016, 26612, 6050, 9570, 29017, 9612, 36132,
36182, 25195, 9616, 9556, 47533, 21202, 267, 37707, 47582, 32954,
24118, 27836, 9579, 21520, 33251, 51901, 27987, 24190, 2567, 30140,
21098, 35480, 2307, 3508, 6026, 26088, 24735, 2593, 9573, 27867, 36655,
38971, 38613, 32918, 54801, 8978, 26020, 1393, 26827, 24185, 29923,
12357, 39336, 31379, 53588, 28422, 37749, 22661, 26012, 1203, 25369,
35351, 39514, 31911, 21305, 731, 3081, 20124, 1672, 22402, 20820,
4335, 26627, 2406, 28856, 24259, 51256, 44537, 20296, 3758, 35488,
8747, 32416, 40643, 30408, 53596, 51061, 38160, 12622, 8233, 8810,
29454, 8710, 32899, 22859, 44068, 23035, 28059, 32257, 51328, 30406,
25830, 22519, 37002, 46112, 22675, 29747, 32202, 39063, 8201, 22857,
32938, 45436, 47673, 34503, 50773, 47800, 25198, 39536, 2487, 25159,
35980, 48268, 29468, 36784, 37111, 20542, 54060, 21966, 53448, 23611,
1386, 24609, 39128, 25366, 2739, 49905, 2568, 39542, 52880, 3778,
9560, 47017, 25475, 12444, 23815, 21908, 3222, 25806, 20096, 729,
33328, 28388, 36774, 34562, 24171, 37628, 31389, 50420, 39023, 25302,
36394, 1415, 22730, 21931, 1411, 28092, 38599, 7859, 33883, 31282,
50920, 32716, 35832, 38686, 24910, 48296, 54253, 38640, 33311, 8214,
6039, 33039, 22378, 47116, 54812, 21083, 49912, 35806, 38560, 31946,
3267, 31957, 9314, 32768, 52268, 54925, 8202, 26842, 24265, 49492,
8561, 46377, 35433, 1413, 20801, 20625, 49910, 8235, 32982, 24357,
36154, 35576, 26799, 30462, 53441, 271, 26438, 24443, 9554, 32822,
25080, 52272, 45453, 6084, 39438, 54045, 35380, 22528, 311, 21767,
36637, 38109, 2743, 22654, 25300, 32437, 34928, 25169, 20047, 35856,
30990, 4725, 38506, 2469, 20973, 50628, 37257, 21544, 40527, 24724,
30742, 24070, 25496, 24330, 32893, 46121, 21566, 25758, 38592, 29151,
25259, 22771, 26247, 36713, 728, 36093, 8712, 6023, 34909, 38901,
36712, 28415, 20208, 22958, 6017, 29611, 3304, 40511, 31232, 37679,
38400, 33289, 1748, 54413, 35426, 31292, 26647, 51025, 4245, 21351,
6030, 20932, 28504, 45944, 52395, 24950, 39015, 47001, 31918, 2534,
53584, 22561, 2407, 23004, 20976, 32602, 26894, 29246, 38152, 25958,
49689, 26447, 37666, 3768, 2408, 33889, 27133, 47676, 45328, 32874,
33167, 31661, 53444, 1777, 31048, 50883, 36493, 38512, 28900, 33633,
1632, 24505, 21861, 23725, 23229, 27738, 22403, 30165, 47111, 12643,
40718, 28846, 38401, 51340, 22334, 3337, 27893, 2605, 25166, 47579,
44040, 37995, 38393, 40372, 39364, 27972, 63731, 24524, 50937, 51697,
37011, 21350, 50837, 21091, 26607, 51137, 32483, 21563, 31452, 28085,
30896, 53433, 3545, 26257, 3773, 22993, 1563, 54984, 27450, 50526,
31609, 33452, 27852, 34174, 25206, 29808, 28687, 23047, 33294, 40483,
20661, 34972, 23528, 32396, 20658, 22842, 33678, 1769, 24942, 28938,
20667, 20523, 49901, 38617, 23777, 28107, 36891, 52265, 23624, 21449,
54504, 50743, 23849, 3524, 23527, 44867, 35851, 29788, 33292, 23072,
21780, 1717, 51596, 35930, 2707, 3924, 24266, 26704, 24840, 20817,
21674, 32541, 25320, 31298, 4127, 28866, 35440, 27233, 3495, 27974,
22043, 49772, 25539, 23159, 33796, 33988, 24288, 24680, 20918, 25312,
23002, 8743, 3647, 24193, 27779, 30290, 32186, 44596, 4170, 4018,
32466, 40831, 20329, 35676, 1959, 27844, 12310, 23660, 23581, 51424,
22534, 35347, 38577, 24358, 40634, 31258, 20806, 24944, 45149, 47540,
3395, 52968, 1633, 22616, 34989, 4223, 32469, 24685, 27185, 28382,
39547, 51104, 12311, 35868, 25562, 26517, 20052, 27589, 12410, 8764,
39366, 52432, 26224, 33831, 63246, 33469, 20736, 3546, 29422, 19985,
3663, 3094, 3763, 37051, 21195, 25040, 24931, 32922, 36924, 29376,
36898, 37559, 38563, 31150, 34253, 32445, 28113, 36628, 26685, 33485,
28843, 36785, 36143, 20399, 21574, 20002, 1929, 24808, 2467, 25799,
6078, 32190, 1395, 38739, 3218, 29401, 21460, 38666, 50516, 8229,
36212, 27965, 30526, 23273, 38568, 25885, 23391, 32490, 28192, 36808,
1612, 33922, 28357, 6018, 20341, 32501, 733, 6032, 32023, 23608, 36831,
4637, 2569, 50984, 23330, 21208, 33805, 9835, 20175, 26742, 45336,
52860, 3484, 51453, 23884, 9792, 9794, 31351, 39759, 22435, 24676,
40169, 31992, 1923, 3666, 45769, 28024, 24432, 27465, 25220, 1707,
25802, 33178, 30044, 970, 22915, 24917, 44404, 45815, 44984, 47029,
20011, 27511, 36139, 4653, 36156, 24429, 28142, 3664, 45440, 30168,
26689, 34109, 52769, 25764, 38499, 54756, 36629, 34945, 40180, 22570,
35997, 29425, 2695, 33274, 29301, 29421, 33446, 53011, 48716, 34092,
33683, 38307, 34030, 38654, 9674, 28057, 22079, 26801, 44049, 21897,
30861, 24339, 45909, 39292, 29081, 38570, 26097, 29417, 22467, 9426,
25448, 21890, 53360, 46319, 21346, 34900, 28393, 50725, 40560, 28331,
29518, 25342, 3740, 53560, 50772, 50521, 24367, 20767, 1685, 34430,
21340, 36424, 52789, 35698, 36744, 20941, 26197, 38035, 6025, 39164,
2999, 8727, 29237, 25996, 36893, 54400, 21385, 32156, 23067, 63728,
32294, 54260, 32368, 24801, 32434, 33993, 20911, 44417, 20285, 36362,
34277, 8719, 32705, 36649, 2536, 4661, 22882, 29756, 21525, 24616,
27472, 21155, 37255, 24677, 28516, 34924, 48388, 54016, 2535, 29228,
45458, 28548, 25273, 36974, 29539, 39554, 37941, 30827, 51704, 55141,
35947, 20597, 20534, 25135, 3536, 27585, 22739, 4098, 33931, 45180,
25377, 39062, 24085, 20923, 37782, 21280, 34384, 20613, 25243, 52392};
System.arraycopy(temp, 0, chars, 0, temp.length);
}
private static void populateChars2() {
int[] temp = new int[] {
49472, 54732, 38391, 51669, 49556, 20266, 46024, 32617, 21898, 36930,
36600, 25746, 24858, 38620, 36015, 9668, 33550, 23518, 26528, 36562,
50685, 30871, 24311, 32789, 55192, 4148, 4840, 45772, 2652, 47168,
25407, 1926, 50780, 49380, 4621, 35880, 35582, 36066, 21246, 54392,
31844, 1690, 3109, 4224, 29408, 9315, 22916, 47215, 54536, 20670,
3365, 22287, 23014, 32592, 30789, 64257, 27922, 22888, 37528, 37066,
30079, 32191, 4632, 25818, 30033, 29738, 38728, 46989, 24034, 53952,
1784, 63743, 36203, 2974, 27703, 47456, 29544, 23617, 30095, 46301,
25197, 26820, 54036, 33144, 24764, 25242, 1928, 26280, 27675, 1660,
50536, 26539, 730, 28639, 33541, 4768, 34311, 19993, 28316, 37912,
36172, 50648, 37237, 3001, 1211, 27688, 25776, 30683, 50024, 28448,
45392, 32518, 4813, 2959, 21497, 45803, 22904, 46244, 34886, 32564,
34809, 27506, 27754, 3276, 52236, 4704, 50684, 3350, 33970, 28525,
8260, 26352, 28381, 1414, 20995, 53084, 24841, 23947, 48712, 53948,
26114, 53461, 26898, 2599, 33382, 48317, 3346, 50040, 35803, 29281,
54841, 8800, 39540, 1634, 25042, 21472, 27631, 25856, 29282, 29226,
1665, 21187, 3303, 21163, 21796, 20786, 25304, 3232, 25745, 8243,
20513, 12542, 28180, 25582, 4616, 21703, 28322, 32465, 50952, 9758,
21400, 38125, 32930, 50997, 349, 2697, 4333, 54785, 34560, 38797,
46307, 24343, 20390, 36171, 54589, 50517, 39578, 12291, 38397, 4773,
32085, 38742, 20984, 1934, 36002, 29004, 37238, 26420, 52896, 30591,
1673, 3746, 40493, 24055, 36910, 33218, 24825, 36161, 39588, 6034,
52972, 21371, 24088, 26543, 38290, 24043, 19995, 20054, 38062, 37670,
21034, 47589, 50532, 29369, 48279, 49832, 21681, 44512, 33030, 30067,
33433, 38669, 21273, 25384, 20111, 36158, 33821, 20467, 51608, 22894,
6048, 23194, 32330, 21535, 9827, 21693, 38136, 29492, 26179, 34676,
21676, 39442, 29642, 26039, 24688, 6087, 28655, 8234, 25260, 4845,
48744, 37198, 45264, 27832, 26127, 49244, 31056, 28500, 4119, 38464,
37129, 2373, 31067, 45459, 21078, 28189, 39729, 30137, 20305, 54047,
21683, 12295, 30450, 3734, 33235, 51069, 36007, 47605, 8756, 26635,
28044, 22372, 31579, 38041, 51276, 28169, 63729, 3539, 47788, 63730,
33351, 25836, 23403, 32670, 25417, 2717, 49397, 52237, 8739, 21123,
23828, 24217, 21388, 32960, 32737, 29128, 46496, 47160, 24789, 32011,
40863, 35961, 25010, 49512, 3510, 25380, 26151, 20240, 27733, 32160,
24604, 20167, 20605, 24700, 20677, 32114, 265, 29508, 27819, 3937,
47353, 33624, 39282, 24161, 33152, 48400, 32568, 3986, 34542, 46523,
24417, 49604, 26643, 21688, 3461, 20365, 28514, 36874, 4709, 21523,
31966, 48731, 38420, 3669, 1776, 45285, 3139, 37122, 21129, 29229,
7861, 27498, 2791, 24868, 28147, 25447, 37549, 23071, 39041, 36752,
20136, 45789, 36795, 53416, 38886, 30643, 44260, 54057, 30399, 22963,
35850, 3208, 2575, 33909, 33980, 38203, 3215, 33192, 38665, 22949,
37806, 20553, 4149, 22353, 45797, 36138, 285, 33540, 26729, 39281,
20282, 30697, 35186, 25153, 50865, 20711, 24501, 28417, 36059, 22533,
3087, 54792, 32923, 31515, 21049, 38614, 3930, 50656, 33181, 33519,
21093, 8560, 46500, 25088, 21912, 36887, 4133, 28911, 1779, 3905,
25292, 3080, 33086, 37233, 25788, 22942, 32499, 21481, 30385, 1758,
25335, 33290, 36735, 1932, 47952, 6096, 12615, 2314, 35987, 8362,
25793, 36011, 52825, 24833, 47113, 29312, 24962, 31096, 20698, 22602,
54224, 31109, 28792, 35207, 27695, 33426, 45000, 31520, 21855, 22132,
40548, 33606, 37204, 44844, 36758, 22816, 33034, 22285, 27224, 31528,
4720, 48157, 27054, 53581, 46096, 22890, 51320, 31291, 22941, 39378,
22952, 52492, 35475, 32566, 53328, 35598, 3904, 26954, 26217, 21248,
28921, 32752, 29006, 30897, 51092, 25998, 39567, 22774, 25970, 22040,
4232, 30460, 64258, 23541, 23477, 28810, 2960, 27225, 33995, 35776,
21555, 44845, 31909, 36923, 22586, 33032, 48164, 8467, 45397, 32709,
4752, 30776, 32380, 9664, 31712, 21705, 20028, 1635, 24908, 10146,
30770, 4125, 23451, 1931, 3934, 23020, 30967, 22368, 3782, 33018,
27249, 24307, 3224, 50641, 33139, 44648, 21410, 3804, 28907, 35772,
3662, 8711, 53556, 47680, 4843, 32233, 36330, 1920, 3910, 28879, 35920,
3148, 25096, 24807, 40607, 21038, 22122, 35998, 12641, 37772, 36530,
1778, 53748, 38695, 27815, 3667, 54848, 52632, 40441, 49789, 28183,
39173, 28291, 30162, 33721, 35408, 21895, 20022, 40517, 40335, 2412,
45433, 32331, 22581, 28212, 20857, 26976, 21534, 22075, 28317, 38553,
40667, 25674, 30959, 34442, 22564, 37045, 46076, 27778, 33098, 25309,
38053, 31363, 4755, 21999, 4103, 35784, 33905, 45347, 2712, 12445,
36031, 32363, 53456, 31209, 2790, 47551, 47805, 25797, 54784, 53224,
34028, 36016, 24428, 3548, 35885, 33131, 33392, 20137, 28976, 20457,
1961, 54268, 20007, 38748, 46392, 4336, 20985, 32961, 39165, 44054,
23466, 47148, 36720, 2498, 54172, 1936, 26531, 9316, 6077, 20828,
26775, 47704, 33419, 33453, 48064, 6080, 38476, 33334, 37231, 38208,
25513, 12446, 33733, 45927, 8562, 22839, 40509, 3772, 47751, 30703,
27387, 32027, 22317, 38639, 22365, 22247, 52832, 31302, 24245, 28170,
21321, 33031, 29814, 34593, 34468, 1686, 25172, 32610, 36386, 21860,
2464, 37259, 20521, 28577, 51396, 21710, 53020, 38025, 20725, 21329,
54001, 9672, 48165, 20754, 365, 49104, 38156, 51677, 54645, 27760,
30733, 25334, 2963, 36877, 21467, 1641, 52845, 38343, 24392, 29298,
32544, 47217, 29138, 38593, 3347, 34299, 2409, 4161, 8857, 33564,
37041, 37509, 38383, 10084, 23219, 39662, 30174, 40232, 24035, 36126,
1637, 44050, 22291, 39449, 50741, 3343, 36538, 33769, 40179, 22082,
31548, 30185, 26847, 9763, 28460, 37320, 20392, 39556, 24222, 22925,
26623, 30522, 31237, 20901, 24248, 30922, 25436, 38085, 47204, 24717,
23609, 2411, 21375, 38057, 23016, 46888, 24218, 30433, 25615, 23515,
25379, 8629, 49704, 35878, 33216, 35463, 12599, 28251, 36852, 45225,
44340, 25022, 20098, 50473, 21843, 53372, 2584, 54648, 46168, 25684,
29791, 28641, 9702, 29705, 25114, 2415, 25238, 32177, 20062, 25079,
1933, 30126, 2720, 36195, 34203, 1669, 33579, 12443, 33735, 21650,
3747, 48197, 30928, 23472, 30294, 31805, 63736, 32110, 1681, 54764,
31967, 23663, 34432, 2878, 21754, 3352, 25594, 36042, 25993, 26000,
47352, 29993, 47021, 22196, 46504, 33795, 39894, 21465, 8806, 1640,
25545, 4319, 23648, 29563, 23534, 48729, 31929, 28493, 29503, 38587,
37489, 37340, 8210, 34583, 49452, 28103, 37474, 20632, 4848, 50885,
1373, 39047, 2636, 35738, 22777, 28799, 30849, 22887, 34217, 21679,
33203, 20254, 21557, 21295, 33147, 22092, 52524, 3653, 51593, 33184,
38902, 25812, 27146, 50631, 53457, 4162, 1636, 32624, 31623, 1706,
47691, 48709, 4635, 28100, 912, 31165, 25387, 36556, 45228, 48537,
33225, 31364, 8807, 59115, 26028, 52981, 31883, 39635, 29242, 1741,
27682, 26646, 32283, 31469, 27792, 27572, 1930, 37664, 53097, 22756,
34893, 22217, 32016, 25423, 51232, 25001, 24278, 32829, 12636, 33593,
26283, 34957, 20872, 38392, 37218, 47280, 21643, 22840, 55120, 47085,
21397, 21254, 45929, 59017, 1639, 45240, 2607, 22549, 49453, 21947,
24799, 6085, 24359, 2597, 22846, 50633, 24999, 25654, 54008, 40486,
39686, 9080, 31293, 6037, 35140, 4853, 25199, 4877, 48150, 37048,
32903, 26771, 21214, 48757, 54635, 30813, 36452, 20431, 31487, 23596,
2543, 3766, 30571, 2321, 25405, 30008, 25605, 35695, 21000, 25161,
32462, 40665, 2755, 28195, 1638, 45209, 32597, 39192, 28528, 51667,
55064, 4619, 4872, 26586, 6083, 26829, 37230, 21149, 32896, 53092,
10003, 20945, 48121, 27331, 52377, 29432, 2410, 48420, 46907, 37507,
314, 1924, 3668, 37467, 40629, 34521, 36804, 53916, 3227, 45828, 32051,
8834, 1043333, 28572, 35845, 4186, 24041, 38662, 981, 22434, 27575,
47576, 52644, 22484, 39171, 32299, 37676, 23633, 49500, 4776, 38275,
33102, 29863, 26021, 34523, 29734, 25778, 4175, 45230, 51081, 21485,
22869, 44161, 23830, 24427, 34223, 30036, 4134, 20979, 38622, 3984,
37323, 36926, 46832, 38931, 8209, 2952, 29640, 27899, 4733, 3415,
33899, 3305, 31204, 6089, 34509, 20322, 48127, 30050, 49368, 26837,
40680, 39472, 3805, 28073, 1305, 32227, 25325, 32827, 27679, 39295,
38991, 44732, 33436, 3216, 34935, 54592, 27985, 22576, 35065, 35948,
3920, 27085, 30338, 1417, 44052, 52489, 38048, 24426, 44628, 54144,
22750, 28790, 20864, 26869, 23604, 2537, 51229, 37165, 23094, 39072,
51468, 3925, 21769, 3499, 28888, 34433, 23493, 25666, 29076, 24809,
27900, 39286, 2539, 54017, 25472, 1468, 26310, 49341, 28136, 39129,
34196, 20621, 34315, 40637, 28487, 38054, 35854, 35449, 23561, 35875,
37039, 36106, 20314, 39551, 12533, 33948, 30447, 32673, 31391, 12386,
4723, 37723, 38829, 26365, 4019, 30535, 27131, 3219, 51079, 1921,
20177, 26198, 20323, 27694, 45257, 9824, 341, 38567, 36051, 54156,
25296, 12482, 359, 40594, 2499, 35617, 21564, 32781, 26803, 63250,
4648, 51236, 33806, 26025, 36084, 8600, 31177, 34395, 36225, 4651,
34074, 53668, 46405, 23113, 21756, 23532, 52252, 50432, 23234, 2864,
4656, 29279, 37247, 26122, 29477, 27463, 35853, 9487, 32180, 36176,
31108, 49399, 21486, 51564, 27766, 33008, 23835, 30631, 20900, 49334,
46272, 31166, 22604, 20522, 40613, 21290, 8901, 49240, 20955, 37284,
37049, 27197, 25995, 26388, 34067, 45196, 49933, 26632, 51664, 32058,
21059, 33465, 2760, 27667, 21927, 26805, 26530, 47931, 30164, 37026,
27308, 20360, 27495, 31373, 28954, 20446, 55121, 38982, 2457, 12963,
4808, 29241, 21647, 34121, 35088, 3090, 30358, 37112, 47213, 20977,
22030, 65104, 52983, 33492, 4707, 24936, 21633, 2538, 39423, 31783,
20050, 33841, 2794, 44272, 21914, 24051, 28389, 21764, 26278, 33545,
28905, 26454, 2413, 53420, 31072, 2795, 29802, 36276, 26943, 33833,
28068, 32902, 32239, 35558, 29033, 37009, 33029, 8741, 36767, 30889,
26329, 49100, 38389, 45448, 4781, 21936, 12430, 1207, 29509, 3458,
27838, 37085, 45924, 30270, 44852, 33296, 27512, 38582, 36137, 61984,
21980, 50619, 52856, 21577, 38533, 45132, 54804, 22013, 22931, 33729,
1042487, 24420, 22047, 29840, 1185, 22781, 34249, 38055, 39076, 2462,
32428, 12849, 34802, 38604, 2433, 35320, 2837, 32333, 39745, 36145,
3935, 9742, 10047, 34584, 52393, 26311, 3490, 32362, 27726, 26797,
2792, 30116, 21133, 47708, 9499, 24208, 29632, 34453, 39348, 26708,
31545, 1785, 29100, 33674, 3307, 21281, 33589, 4613, 38678, 35223,
21930, 29022, 9317, 45128, 31735, 28467, 33639, 25386, 3096, 39037,
23622, 12596, 40655, 48180, 30031, 2414, 24282, 37832, 30917, 25749,
38043, 2893, 29995, 40778, 22986, 36481, 27741, 22645, 33046, 25318,
30355, 3497, 33631, 4238, 29560, 55137, 47329, 22496, 8744, 3336,
28844, 45516, 2320, 37686, 33067, 30494, 49483, 55124, 39717, 26963,
28689, 51247, 51480, 31397, 36168, 29781, 28657, 28891, 3999, 47092,
34164, 6073, 1463, 52270, 2589, 1464, 21880, 3913, 34722, 2579, 39791,
45140, 53665, 8746, 38619, 23784, 25597, 35584, 27728, 23521, 37221,
33659, 1374, 46980, 45256, 27060, 21505, 29956, 2542, 30702, 28760,
21237, 1524, 20238, 2796, 539, 23706, 36064, 2691, 38180, 27896, 24661,
2510, 21673, 20506, 38997, 31353, 25327, 25438, 3473, 25375, 22350,
22862, 40660, 19998, 26592, 31446, 1251, 36711, 23803, 28796, 1177,
35586, 25487, 36953, 44316, 37304, 30192, 31377, 3909, 35122, 53681,
8660, 39748, 21727, 35090, 34638, 21515, 27264, 45349, 4234, 10065,
25874, 27526, 30699, 21610, 2353, 48764, 20008, 47609, 8758, 27012,
20183, 33307, 50670, 22234, 28179, 24871, 38146, 9491, 9699, 54004,
21585, 1781, 45210, 36983, 38930, 36159, 9698, 37145, 48141, 31398,
35028, 31491, 40077, 9644, 1460, 27712, 21380, 29071, 4240, 28949,
31161, 20051, 20871, 8757, 38449, 1966, 33620, 27975, 33398, 9480,
31581, 39056, 46497, 36420, 4111, 40801, 3306, 21250, 3671, 35359,
30860, 31407, 29306, 44636, 45124, 29792, 38583, 22366, 35609, 9582,
32495, 24794, 21742, 25329, 19984, 36101, 28507, 47337, 35829, 2954,
3670, 31319, 20166, 46385, 34224, 3642, 3525, 22880, 1043296, 34281,
30072, 31459, 29787, 3672, 29053, 21589, 9788, 8786, 46120, 28629,
27014, 34398, 59009, 33125, 32728, 31337, 46181, 331, 47896, 27204,
39180, 51021, 22151, 36245, 33329, 20846, 31869, 21137, 40251, 26999,
9483, 38175, 1041703, 29042, 50584, 2540, 25765, 26023, 26848, 30520,
20336, 1782, 1780, 48145, 27803, 31229, 3452, 38416, 54204, 28210,
55184, 32478, 47019, 28372, 31095, 50424, 34126, 31601, 30219, 2887,
36838, 24758, 30529, 9786, 30505, 23241, 3521, 27777, 26791, 6090,
21815, 29380, 25844, 59114, 21888, 32986, 23081, 6088, 24290, 31964,
33368, 37336, 40858, 28472, 38753, 23649, 48316, 20518, 45916, 31378,
27813, 35070, 48960, 31402, 36090, 28263, 38887, 38501, 23994, 48533,
1456, 28919, 24101, 51536, 4677, 37275, 36468, 22066, 21653, 9547,
25950, 22769, 2879, 23682, 30221, 20398, 39042, 44618, 32438, 31903,
55036, 33099, 30113, 32512, 37210, 47131, 34219, 27953, 38262, 31162,
12828, 26928, 29831, 22107, 33286, 24608, 3308, 37413, 28466, 34850,
9700, 45940, 28065, 2405, 9477, 15142, 9836, 309, 37232, 50476, 45324,
2587, 2541, 21700, 31914, 38446, 30606, 57348, 22404, 28552, 1523,
25504, 21185, 36466, 50812, 3344, 20463, 2456, 45776, 35766, 3088,
4779, 40595, 38082, 22687, 12485, 36077, 31925, 37756, 29712, 61472,
28346, 3673, 22593, 6092, 34157, 26274, 30596, 59131, 40568, 31840,
537, 55180, 3309, 48261, 39381, 33276, 25414, 4115, 23045, 23044,
30691, 38209, 25032, 36249, 26279, 29211, 53300, 35424, 30651, 25170,
29786, 38660, 35363, 37226, 38907, 2592, 29590, 52884, 32865, 1700,
36198, 1965, 20355, 9318, 47156, 31143, 28149, 46609, 34434, 4941,
38230, 33559, 39274, 27579, 38046, 32070, 31296, 47157, 34633, 46164,
28478, 3234, 4196, 28003, 4771, 33009, 3091, 3858, 32920, 21325, 29746,
25771, 26464, 22114, 29254, 24103, 3549, 4225, 23591, 21736, 54760,
30590, 4226, 4829, 21899, 3454, 32504, 38078, 21737, 21992, 12609,
6112, 25441, 1042486, 28558, 31339, 30637, 3106, 38191, 35059, 8563,
36783, 2764, 1940, 27837, 47716, 32680, 28122, 22124, 35269, 45580,
28851, 39881, 34107, 30585, 9581, 3504, 1783, 33592, 2856, 23087,
52897, 33445, 24977, 29614, 22065, 30129, 3587, 28373, 53489, 8736,
5222, 36958, 21104, 33530, 21128, 3940, 4672, 21596, 23077, 30251,
25234, 20045, 3919, 46263, 50694, 21713, 4634, 32735, 30710, 38713,
46629, 30634, 26629, 39539, 35535, 35167, 2570, 6024, 63735, 47693,
28822, 23776, 25622, 48656, 24974, 45229, 20904, 38289, 22383, 8735,
36255, 12553, 21941, 47925, 21235, 3404, 48391, 32831, 23421, 21987,
4004, 37613, 46992, 32907, 26289, 39822, 38605, 24162, 38067, 45734,
29634, 26342, 25074, 65103, 32548, 28435, 24013, 59066, 36988, 31811,
29750, 20887, 33760, 39558, 30307, 36527, 33670, 28953, 29730, 24465,
32517, 8232, 12613, 59100, 44285, 31672, 26577, 22367, 29733, 58566,
38013, 26313, 4901, 20332, 21584, 24867, 30566, 24730, 23679, 26429,
21932, 30802, 59162, 59130, 23344, 28414, 1939, 21359, 3596, 54196,
45588, 26207, 33802, 50967, 3675, 9701, 51222, 38221, 2860, 5509,
6022, 4221, 33643, 44176, 33285, 39045, 38181, 8759, 40104, 9787,
6093, 9655, 28937, 27167, 31499, 49899, 47956, 24246, 55128, 47212,
24803, 38539, 2793, 20502, 25619, 48044, 22057, 59120, 31637, 12529,
3589, 4158, 30414, 45252, 23267, 26133, 9584, 33012, 2946, 27986,
24853, 47120, 3310, 6103, 31716, 1041647, 53132, 9685, 9602, 4851,
35060, 48848, 35607, 32838, 40158, 27048, 49916, 27788, 48389, 38379,
50912, 24315, 45937, 31636, 31809, 32509, 28670, 1808, 38746, 1041734,
38588, 32251, 12294, 53272, 32834, 37108, 29749, 32532, 50136, 37321,
24328, 34656, 32121, 44220, 30115, 21891, 28925, 30300, 50715, 51684,
3872, 36757, 57344, 31961, 65109, 53188, 32474, 46027, 29649, 37351,
4659, 44145, 25703, 35809, 34321, 32453, 38394, 21822, 27029, 35674,
44988, 3230, 39899, 28698, 20448, 2872, 312, 24005, 31406, 20873,
29522, 39269, 35566, 30741, 20130, 34444, 21766, 51260, 38968, 35513,
7952, 28181, 2852, 51082, 21777, 29309, 27814, 27544, 28186, 20308,
32948, 25305, 51117, 31047, 31040, 36286, 49920, 38471, 30544, 2504,
30207, 53812, 25578, 32406, 49632, 34122, 22418, 8054, 4163, 33308,
1043286, 39548, 50745, 25203, 26840, 28359, 44992, 24976, 8835, 7936,
44788, 45244, 38475, 28218, 26462, 53413, 12593, 47585, 40132, 23394,
51687, 24646, 33300, 35565, 21348, 4623, 36764, 2576, 40434, 25850,
23630, 24319, 30732, 4609, 33043, 4936, 29060, 59161, 25098, 45787,
36142, 39493, 8228, 22930, 23724, 1013, 26241, 21242, 44415, 4811,
49847, 9319, 21632, 23013, 34649, 58979, 21076, 31041, 22697, 24623,
900, 30428, 31401, 38414, 34662, 47736, 49455, 52040, 29234, 2880,
3453, 52452, 8481, 26214, 30094, 25947, 39608, 13213, 30977, 22204,
1937, 46524, 8599, 24409, 48140, 36454, 38536, 20814, 50505, 28153,
59091, 25443, 22179, 39290, 27516, 28865, 2551, 26355, 23386, 52196,
53808, 32494, 27088, 4896, 38064, 9756, 2862, 35641, 24275, 49744,
36144, 37758, 25031, 9320, 33302, 29822, 27243, 38225, 29481, 4169,
23913, 57474, 32687, 33275, 22022, 23388, 35715, 30610, 3743, 50560,
59098, 30315, 1925, 21957, 25524, 31264, 46364, 44263, 36264, 24287,
24653, 38255, 31311, 28234, 45331, 46161, 9737, 22039, 25884, 26786,
6027, 26874, 20133, 35438, 37196, 34875, 3311, 32203, 25287, 31001,
20939, 35773, 32608, 54736, 21519, 770, 36174, 28609, 2873, 9635,
9122, 32033, 462, 4250, 8361, 25458, 3463, 39912, 2722, 48596, 35876,
32957, 52740, 22778, 36943, 27774, 29471, 32880, 2947, 4168, 971,
20432, 29557, 22438, 30420, 21971, 51094, 28037, 34914, 52656, 3522,
4824, 25722, 4962, 10070, 20885, 51086, 4617, 47105, 32629, 4650,
59011, 31607, 24458, 22764, 45805, 27194, 9605, 40140, 29277, 8765,
61623, 30439, 51210, 33499, 21474, 51075, 23697, 24439, 3465, 24347,
38816, 23495, 36060, 51788, 49714, 3793, 46944, 39533, 36676, 27945,
32349, 45544, 27603, 35837, 35808, 49356, 31983, 36845, 32371, 25854,
27099, 24472, 28335, 28205, 26191, 3929, 44624, 1724, 52888, 34103,
38774, 27584, 26880, 4165, 26806, 30519, 6113, 27696, 2797, 28196,
33040, 50928, 30872, 29200, 24264, 28654, 36111, 29785, 32098, 12601,
32359, 27513, 22666, 38491, 21256, 25370, 31496, 8200, 9479, 29494,
50740, 32314, 36726, 20278, 47497, 37292, 25410, 22953, 39620, 30133,
36244, 31893, 39052, 23413, 25314, 54049, 38124, 38115, 37586, 27978,
50549, 54663, 1942, 38308, 49707, 33527, 40860, 44216, 5123, 29764,
36010, 3542, 38675, 21480, 31014, 63724, 27580, 22103, 30970, 28154,
3931, 32533, 20451, 37706, 36703, 20406, 45377, 6028, 50519, 40100,
25735, 25794, 30068, 36140, 28051, 477, 1043254, 31482, 28828, 4875,
39050, 32745, 45130, 8855, 26604, 28825, 27147, 36781, 31568, 9504,
21671, 36869, 30504, 39347, 1042479, 24691, 30178, 50734, 35178, 22684,
26865, 55193, 22852, 30208, 21719, 65102, 33515, 23308, 37276, 9585,
6114, 61607, 63732, 2799, 21866, 25602, 28889, 31975, 47344, 22446,
25341, 36049, 24336, 47449, 24971, 33333, 40573, 29701, 35114, 32824,
36994, 50028, 47452, 33688, 22108, 22275, 38643, 25601, 32010, 25358,
39031, 23786, 32538, 38342, 52308, 27527, 4614, 31098, 54660, 38607,
1042482, 50545, 33162, 36995, 21702, 26103, 20440, 21489, 33134, 61550,
3488, 21627, 20031, 22974, 23092, 1041718, 37193, 33463, 29020, 33400,
4173, 8056, 53888, 36929, 24396, 38192, 21874, 609, 26974, 46036,
33706, 769, 4722, 25139, 26485, 23629, 3873, 4167, 53672, 2858, 26726,
33743, 37168, 48977, 29696, 46316, 59106, 4164, 59116, 28780, 27103,
51469, 39607, 26505, 24832, 4763, 8238, 33213, 5251, 25134, 6049,
44081, 36635, 22956, 26866, 22732, 39719, 39314, 24709, 30415, 54943,
3451, 27902, 57347, 45785, 50544, 35905, 23125, 30511, 34003, 32521,
3462, 30361, 26406, 23673, 4001, 34532, 54729, 35435, 20461, 1042478,
48976, 53680, 45143, 3360, 24684, 28053, 35709, 44188, 4961, 24092,
25942, 63348, 23791, 21652, 32843, 38130, 25376, 21827, 8223, 21571,
39285, 34241, 47569, 4726, 32399, 34581, 36070, 8869, 25282, 31310,
21283, 38635, 4209, 9607, 28904, 2798, 27863, 28437, 30403, 2508,
25078, 38808, 33187, 20642, 39301, 37389, 53304, 28465, 8166, 26099,
8853, 25892, 12432, 48184, 2818, 3874, 39387, 35516, 26552, 39464,
1465, 2594, 33491, 2866, 6055, 31388, 34837, 39654, 29344, 36746,
37799, 36447, 59016, 54176, 25810, 26326, 8596, 34690, 57361, 23167,
27762, 32806, 25769, 36978, 1263, 27278, 39612, 5125, 65105, 32697,
44413, 6100, 39059, 55136, 33828, 29835, 6079, 34631, 49480, 45806,
39243, 8239, 35763, 27609, 27859, 22821, 52244, 61548, 24816, 54169,
39108, 28586, 21234, 2761, 21949, 29864, 29001, 35970, 4009, 26161,
46748, 46763, 491, 37619, 37159, 28173, 4850, 23100, 34261, 44191,
39156, 8564, 29096, 821, 20731, 39187, 49709, 1963, 12610, 40779,
52841, 5314, 22767, 33105, 21816, 32666, 59111, 26707, 39621, 33304,
55152, 40786, 40687, 3507, 4197, 13212, 30202, 38990, 5198, 3741,
59109, 22121, 25530, 37675, 59101, 39853, 32485, 12570, 26751, 1941,
44151, 32554, 25467, 3467, 48521, 1042480, 24407, 20369, 30187, 21032,
28711, 31330, 28751, 38788, 1967, 37274, 44180, 9321, 23536, 31820,
40201, 4770, 9523, 5130, 20760, 30757, 39848, 32526, 46360, 21421,
29158, 715, 24199, 45573, 21978, 29824, 25000, 26238, 4826, 20993,
40557, 23254, 1821, 4251, 28699, 31167, 3220, 27022, 62047, 40120,
20490, 57477, 4622, 30179, 22831, 4728, 49481, 8750, 32187, 34065,
6074, 46416, 63685, 47577, 1648, 53472, 21658, 33247, 24119, 4925,
38056, 34153, 46317, 46749, 1175, 4629, 28132, 47960, 44292, 28198,
28340, 39562, 21413, 38179, 25662, 4023, 22999, 4814, 37195, 25294,
33011, 32999, 24958, 21441, 24811, 29796, 38197, 28861, 25102, 21536,
34093, 31267, 23480, 31382, 22016, 1043331, 54800, 50564, 12583, 28416,
28293, 59125, 21617, 63248, 31686, 33725, 47020, 12575, 32341, 33253,
1043212, 699, 24398, 53301, 34137, 32386, 59037, 25087, 36993, 20319,
2891, 7925, 33503, 30201, 1042485, 24571, 4721, 32671, 31252, 21884,
33722, 9837, 52041, 4654, 34691, 32996, 39519, 26578, 23162, 36461,
34811, 466, 47495, 31933, 38170, 24361, 28479, 27018, 30633, 4193,
40442, 9688, 9603, 32503, 21648, 22707, 26570, 20689, 32639, 26541,
36184, 26946, 8048, 35126, 34115, 29626, 3099, 32305, 29801, 37638,
31117, 34071, 3020, 39559, 55016, 25225, 12616, 47104, 61656, 3476,
29184, 36799, 38112, 22021, 25179, 44273, 48173, 20458, 36524, 63234,
57360, 35781, 27292, 48727, 37569, 23522, 4899, 13115, 27607, 47688,
54988, 31513, 37610, 1462, 40367, 37445, 32350, 3338, 31998, 658,
38956, 10006, 52412, 25527, 31713, 9839, 34152, 49296, 23525, 48282,
10048, 34310, 33479, 28156, 818, 45356, 3911, 1816, 22829, 23625,
40633, 32718, 35032, 35538, 24130, 20504, 28644, 25100, 4675, 25248,
55113, 40485, 59020, 31171, 4772, 33454, 31751, 28160, 6063, 2854,
31368, 33580, 26925, 9606, 49939, 32458, 38045, 21553, 4819, 33418,
23143, 36671, 44403, 9501, 20291, 47340, 54029, 25600, 35692, 2863,
8255, 21591, 50969, 5335, 9583, 54184, 33005, 30105, 38497, 28640,
44861, 25319, 29440, 23729, 40284, 4810, 4166, 13095, 30328, 3944,
59113, 8016, 30048, 20970, 12317, 23769, 773, 33502, 24421, 2466,
801, 24760, 50956, 53040, 31627, 27769, 30347, 21526, 48192, 33240,
20120, 54077, 30239, 31174, 34619, 24920, 53428, 59184, 40515, 40023,
3794, 44051, 26112, 20812, 3584, 34558, 24413, 47945, 4821, 26654,
39568, 36294, 30938, 8182, 54044, 27035, 37213, 9643, 24996, 54996,
32519, 23853, 19999, 23700, 38417, 54548, 28297, 35109, 9117, 45068,
44202, 31118, 3797, 21878, 28108, 25488, 27179, 32633, 9476, 44217,
2881, 24822, 26389, 46916, 1719, 55072, 36620, 9438, 38189, 30640,
34645, 4189, 9744, 47926, 28353, 28071, 9728, 25413, 39130, 4706,
28867, 39661, 38893, 1042481, 34986, 36956, 34083, 31629, 20991, 25744,
33100, 30249, 9481, 27742, 40522, 29409, 1470, 22329, 25371, 8601,
39479, 26348, 20060, 52313, 23046, 20916, 31968, 31224, 1723, 36162,
30629, 20433, 53244, 29771, 20273, 33586, 20348, 20478, 32641, 1281,
22134, 3622, 33137, 59087, 20312, 9120, 35427, 32690, 63738, 38126,
33936, 1040426, 65117, 28063, 50784, 28626, 34396, 39535, 4649, 21638,
63727, 27964, 36381, 4638, 51500, 37530, 29605, 30153, 30233, 30910,
22241, 47364, 3511, 31659, 54945, 46388, 59054, 33399, 32496, 21426,
23445, 30717, 45188, 22199, 1041584, 59107, 28174, 36299, 23461, 1826,
9515, 45934, 27595, 4846, 3788, 30090, 28102, 38671, 30746, 47493,
40499, 34367, 4194, 44555, 1041705, 10063, 20356, 23996, 25571, 63723,
1663, 23568, 1461, 1731, 15104, 4618, 617, 28074, 29723, 31146, 21537,
37261, 48981, 27189, 26665, 48195, 12631, 9116, 51692, 46769, 33575,
9119, 27084, 29313, 26185, 23146, 29922, 21646, 53553, 45740, 3203,
2461, 45012, 25653, 40300, 12318, 29469, 63725, 20525, 10004, 46896,
21937, 30778, 21828, 44637, 38086, 27586, 44860, 25212, 28847, 25004,
37150, 6120, 32024, 61647, 31560, 23157, 48374, 33585, 28458, 46280,
33255, 30186, 511, 34506, 63734, 39237, 3210, 9115, 21422, 37397,
50659, 29662, 39545, 8838, 27648, 1042484, 34870, 30844, 47610, 714,
8815, 4213, 21657, 33940, 44557, 24951, 25898, 46357, 4220, 37264,
22718, 45713, 27553, 9531, 59097, 53485, 54072, 33179, 4219, 48852,
39138, 30933, 51900, 39563, 21990, 8814, 34769, 33603, 3104, 36989,
21792, 28540, 26624, 49456, 9539, 21533, 47464, 53431, 44611, 1840,
49256, 4658, 38859, 30180, 12595, 27280, 8150, 53000, 2435, 464, 32104,
4669, 9689, 30518, 38346, 12584, 20500, 5229, 28197, 48307, 40285,
31584, 2844, 27739, 3991, 65118, 29935, 47502, 5456, 28544, 36894,
59104, 33640, 39311, 20472, 29243, 24488, 8052, 20565, 21714, 31899,
21501, 3082, 25824, 27323, 40495, 21269, 9118, 54411, 4003, 3474,
30106, 991, 1042483, 35728, 27028, 28046, 441, 22036, 44865, 32427,
38173, 5319, 12336, 33215, 38133, 20191, 31729, 26727, 53476, 25421,
34905, 27453, 34670, 3355, 28651, 21545, 25944, 34388, 25912, 31384,
59112, 12433, 45235, 38111, 25119, 61501, 28463, 59021, 27053, 38892,
23805, 36944, 21550, 24091, 33660, 26613, 34943, 48904, 12618, 8569,
35892, 24561, 3795, 12579, 31207, 33421, 50277, 35203, 23218, 34851,
46037, 712, 23919, 24596, 592, 31260, 23158, 31806, 335, 34201, 3073,
20149, 31074, 1043330, 2839, 4765, 32286, 65106, 301, 36732, 37532,
22070, 35815, 30655, 37021, 47701, 5200, 38309, 35867, 59108, 61485,
5333, 44225, 31692, 31414, 51132, 22391, 3852, 21473, 63687, 20106,
27529, 39110, 32129, 4135, 25754, 7823, 30923, 12555, 28977, 4627,
54607, 771, 33862, 27016, 21985, 21599, 36487, 30545, 37624, 30154,
9641, 20147, 34383, 32660, 27822, 32482, 25531, 44751, 8565, 31565,
1825, 33750, 5507, 27994, 20034, 45700, 46433, 35819, 34427, 45227,
12623, 38504, 30597, 38171, 33071, 20834, 3792, 29280, 53220, 20127,
8134, 34597, 29854, 52507, 57503, 44900, 39307, 30109, 8254, 59110,
12526, 51796, 23831, 38253, 31725, 30609, 38076, 30352, 28078, 26248,
4231, 25803, 34527, 22948, 33450, 20898, 65110, 1661, 38039, 27067,
27320, 21606, 40550, 561, 20653, 4753, 9601, 49564, 25880, 59126,
36779, 32792, 1041701, 21595, 25891, 15360, 34993, 9332, 30318, 34579,
21342, 32361, 1824, 48531, 50052, 1811, 34407, 34770, 29989, 26855,
21799, 24817, 2384, 52996, 40569, 29165, 40840, 25520, 4708, 34543,
28327, 35331, 25303, 9831, 35183, 38935, 1371, 4108, 31381, 44405,
1041586, 2315, 38425, 35916, 59140, 24698, 36837, 38771, 1041721,
59185, 50489, 29722, 36405, 700, 44749, 24469, 4756, 29599, 1843,
3537, 21119, 46176, 8494, 38107, 32652, 29990, 24812, 24331, 4657,
29898, 596, 22775, 20396, 21582, 22165, 25315, 277, 21894, 47469,
38210, 59025, 39201, 31921, 51219, 23579, 8733, 26212, 40480, 37300,
1041634, 21417, 34829, 24473, 39851, 27795, 23011, 30136, 23138, 40521,
63237, 24257, 53077, 31721, 23018, 20469, 32714, 36418, 36841, 48724,
9711, 38000, 22754, 38924, 3988, 36324, 21173, 1813, 34996, 46516,
34191, 34085, 1043234, 1954, 373, 14592, 3993, 22007, 23059, 25420,
45460, 50924, 29403, 23437, 1949, 7984, 4705, 21670, 47128, 25291,
293, 63238, 49438, 36802, 20164, 34885, 4827, 23270, 30169, 35791,
35881, 13214, 28712, 35884, 34814, 4620, 29088, 28402, 36426, 35866,
50687, 63281, 36761, 30822, 1836, 21310, 26964, 24682, 54148, 31087,
23860, 4873, 46400, 39003, 3502, 50493, 38722, 4777, 32631, 23462,
39995, 4841, 24061, 54161, 55129, 22158, 35098, 50025, 21675, 25431,
3348, 1834, 23408, 30232, 35830, 3881, 24340, 44613, 28805, 9832,
49788, 40107, 35039, 36068, 48139, 23869, 32491, 9760, 53459, 4864,
53960, 38094, 28457, 20608, 31153, 30768, 8050, 4963, 23620, 35559,
9333, 51144, 23789, 29336, 62018, 32997, 35563, 4869, 27462, 1659,
4633, 15872, 33081, 6019, 45139, 50143, 38026, 31824, 4939, 27617,
25344, 23997, 1043188, 28126, 32557, 27781, 1770, 1245, 28167, 49913,
50893, 29641, 27263, 38128, 39253, 28222, 9662, 1789, 4243, 1473,
1679, 45184, 30241, 20800, 28140, 31061, 34015, 4214, 49396, 9130,
28672, 1041707, 4782, 25494, 34568, 31042, 5205, 25558, 29996, 46892,
25326, 1042451, 4758, 4611, 5316, 48730, 50044, 593, 1676, 36955,
33222, 25466, 39342, 8709, 1042391, 21698, 21668, 22244, 32044, 35131,
23628, 1790, 51329, 40063, 38331, 36036, 24813, 29113, 53237, 53568,
37406, 36968, 50760, 48159, 831, 36368, 39089, 63631, 23075, 3092,
33983, 30758, 23504, 31308, 1620, 4192, 24447, 37510, 5285, 39333,
54187, 23781, 57345, 30183, 59094, 37007, 2698, 4608, 25549, 37742,
33193, 22002, 3229, 1946, 33784, 3796, 26686, 35548, 1728, 28407,
5503, 52868, 28625, 9681, 35635, 44641, 4849, 27825, 58999, 21708,
9680, 34758, 26551, 3674, 603, 39087, 29145, 4006, 7747, 33636, 36460,
5290, 22160, 4828, 20769, 38541, 25062, 29179, 65532, 37043, 13199,
31668, 34068, 39600, 20295, 12556, 30394, 1938, 30305, 1195, 24726,
29619, 9586, 51789, 865, 1771, 37555, 45823, 63686, 35057, 26728,
52152, 22809, 28088, 54396, 33600, 24826, 40702, 40848, 47129, 1644,
32703, 22137, 51334, 28227, 24756, 34451, 58980, 4624, 8902, 1041617,
713, 21913, 29462, 22874, 26891, 1658, 63309, 31567, 38358, 44079,
28753, 21863, 6115, 49344, 31071, 515, 53217, 375, 45798, 28228, 31858,
52180, 21277, 1956, 9352, 9125, 3362, 27355, 21655, 21872, 47607,
39825, 52899, 33094, 1209, 25772, 9613, 808, 59038, 21522, 58865,
24980, 45253, 58636, 57346, 23810, 22427, 33449, 50491, 24913, 633,
34417, 38894, 21994, 30402, 38552, 53484, 1945, 24527, 22257, 10877,
48072, 9828, 468, 21057, 32609, 44452, 57812, 8215, 29461, 25711,
37648, 2544, 35988, 21405, 22178, 33323, 26015, 26584, 32753, 62139,
3102, 28000, 33583, 25084, 1041200, 1042433, 3943, 39361, 31434, 720,
9512, 35820, 26487, 35616, 28425, 33107, 24792, 21240, 49808, 22221,
26164, 2849, 2870, 33096, 36040, 20807, 23882, 28538, 33210, 39711,
53825, 1643, 49108, 33615, 59403, 61626, 49928, 2757, 33355, 22139,
4203, 51428, 33205, 28356, 27673, 23005, 33477, 44866, 35924, 53597,
38323, 26003, 34946, 20367, 34022, 38466, 37709, 27153, 59095, 29384,
32761, 34282, 27523, 32381, 9774, 12571, 34314, 26851, 2718, 4132,
28532, 22136, 34728, 33669, 25034, 4673, 35764, 36490, 28950, 37502,
20643, 45231, 27904, 11520, 23090, 26199, 59390, 36343, 30684, 25077,
34784, 8198, 30568, 34044, 29134, 39123, 38150, 30775, 59057, 22163,
37393, 8001, 4645, 49677, 37200, 54747, 33686, 39553, 37219, 25721,
45957, 44361, 320, 37434, 38589, 27821, 5359, 1041223, 34847, 26107,
57759, 21939, 29852, 34612, 34360, 22159, 36409, 618, 39627, 50771,
32475, 4172, 32412, 37001, 15616, 52843, 61483, 26503, 29355, 59023,
31255, 38068, 31103, 28510, 36022, 34948, 63719, 21294, 61372, 61664,
40150, 36163, 12617, 50753, 30820, 1810, 33007, 8566, 28325, 33129,
24186, 59119, 48333, 1041648, 23057, 9745, 12850, 35973, 24124, 21804,
29502, 33074, 48281, 24581, 25642, 51673, 29674, 39850, 35543, 34949,
32181, 26244, 25115, 20112, 4652, 34615, 26017, 33338, 48737, 25620,
26196, 59138, 63333, 23825, 21317, 26839, 45600, 35578, 3075, 9998,
31142, 4710, 6066, 22349, 26719, 44169, 4874, 31428, 59175, 45321,
38096, 58971, 34479, 35754, 39509, 19989, 49567, 21970, 32774, 40157,
2847, 647, 34739, 34496, 40766, 38012, 4809, 1689, 2822, 39993, 8771,
39221, 33894, 9428, 20515, 36347, 4130, 49520, 28497, 50276, 52258,
36759, 31959, 21117, 26965, 2842, 1041702, 977, 58552, 814, 63681,
6116, 24012, 1127, 24337, 49679, 25523, 38649, 34541, 22744, 27311,
30562, 65111, 51923, 31104, 30442, 34647, 28951, 6095, 31786, 10026,
1042476, 29678, 40605, 653, 7956, 61558, 34502, 21707, 24949, 49093,
10061, 25474, 38670, 27075, 34578, 4667, 28593, 36834, 21757, 34553,
307, 21636, 34635, 48528, 38069, 25616, 3801, 2888, 20456, 34222,
21243, 29030, 4731, 507, 21005, 343, 4678, 3799, 4636, 27988, 4938,
36155, 33914, 4965, 25160, 30821, 9334, 5328, 61614, 49360, 58773,
35014, 34563, 59157, 13568, 52405, 23346, 38148, 63683, 4008, 33390,
1041720, 21988, 1649, 32353, 2580, 31418, 40639, 21867, 20762, 52853,
2821, 8568, 32901, 31658, 36961, 26249, 27315, 37036, 4216, 37476,
59032, 3544, 35174, 38051, 4241, 29855, 47943, 31923, 12620, 63233,
21499, 4923, 39589, 27647, 513, 39634, 21541, 22702, 25306, 34623,
1043235, 4013, 35074, 51792, 52600, 38718, 9322, 26722, 25462, 1832,
12319, 766, 20375, 4920, 44621, 23896, 35855, 30874, 30759, 29351,
32942, 57350, 20850, 21500, 26407, 65125, 24751, 1042460, 6121, 22063,
58637, 39214, 36667, 31063, 49573, 63684, 65123, 32679, 40133, 32365,
3489, 39255, 38335, 24380, 12032, 3800, 62719, 38256, 38765, 47159,
21972, 39631, 1041202, 8960, 28396, 26917, 24258, 63682, 38938, 30242,
39405, 30883, 26188, 21471, 21902, 29690, 27001, 32046, 8598, 4230,
49961, 2560, 21085, 59096, 38034, 4754, 29934, 7969, 3798, 32029,
36425, 45845, 1815, 30679, 44609, 24900, 27192, 33830, 63329, 27079,
21558, 38178, 10066, 21510, 22313, 23265, 29744, 63739, 31494, 33065,
40617, 26991, 63337, 22209, 63737, 33907, 28451, 21691, 8895, 53095,
46895, 50032, 35826, 31800, 1040824, 39250, 32184, 501, 20558, 4878,
28821, 26166, 27421, 2025, 4797, 22003, 59191, 23833, 27166, 39557,
63726, 30091, 33630, 59036, 37350, 3879, 54973, 30780, 25288, 3487,
20822, 39582, 25332, 12551, 23539, 20389, 5234, 30818, 27872, 1123,
57720, 39122, 23105, 36495, 30604, 23782, 32236, 995, 26638, 1835,
58942, 35594, 5206, 40843, 34193, 13076, 33335, 30817, 1846, 23418,
944, 39675, 40141, 26688, 59117, 21833, 1715, 39079, 36346, 34978,
8707, 25082, 29647, 48856, 61692, 30071, 37728, 5418, 34552, 35461,
37891, 63280, 3121, 36427, 40510, 26171, 22741, 30777, 44740, 29394,
20721, 12594, 34952, 39585, 47028, 50739, 29317, 52645, 26296, 33848,
28095, 30045, 3916, 45480, 20547, 22462, 38217, 37970, 51674, 25373,
1041680, 3880, 47719, 35628, 58841, 29322, 9519, 24675, 329, 12621,
1043241, 29736, 1104, 44808, 50567, 28270, 36856, 58991, 20486, 36076,
2365, 36479, 9493, 57480, 28635, 21669, 34199, 46375, 21087, 61627,
29029, 23723, 35084, 34108, 37312, 25899, 6102, 58998, 1645, 26060,
25035, 2861, 37225, 9587, 29807, 22592, 53104, 21068, 1043185, 23735,
3787, 40482, 39319, 29136, 30306, 11056, 34849, 824, 8366, 63282,
26137, 49668, 29999, 40748, 36382, 33682, 30652, 29484, 28152, 36740,
49343, 24806, 36118, 4242, 35912, 34162, 28386, 30738, 32377, 23301,
51609, 4917, 8614, 26075, 8748, 34510, 28390, 31546, 33588, 28583,
35357, 28734, 50137, 24814, 50144, 1042399, 36489, 2876, 1763, 28408,
4099, 29130, 31059, 31657, 52240, 5354, 20956, 29166, 25661, 38747,
35281, 30857, 26978, 32895, 21886, 45072, 45352, 47103, 4907, 51908,
8680, 21549, 30350, 22024, 54749, 31631, 62017, 4674, 4612, 39053,
45656, 37396, 38737, 32619, 37032, 31709, 33985, 33393, 37716, 9527,
28399, 50433, 1858, 613, 26717, 37169, 27710, 63289, 27628, 14848,
32552, 33476, 33003, 37000, 22575, 4854, 28061, 46904, 9335, 9424,
46616, 35811, 3875, 58974, 27386, 48289, 52908, 29977, 38967, 59178,
39699, 20594, 26979, 36706, 1042404, 24779, 1042468, 7717, 1458, 9743,
24530, 30663, 35749, 38601, 61669, 21343, 34306, 59201, 27537, 34001,
27887, 776, 30472, 24774, 29585, 20925, 25540, 9615, 39309, 28693,
23049, 28598, 4904, 45339, 30855, 30087, 28766, 49941, 2704, 59018,
28610, 6060, 8725, 38408, 21604, 24575, 32537, 8567, 27929, 30344,
45825, 13312, 1181, 1040826, 34047, 36019, 38860, 37826, 22376, 58661,
32945, 36146, 32171, 58732, 30782, 7779, 12559, 26697, 31287, 37561,
38356, 22138, 39757, 25736, 38224, 38514, 25503, 37711, 25775, 3328,
37928, 1596, 49816, 24665, 33537, 38398, 38328, 52320, 35575, 21981};
System.arraycopy(temp, 0, chars, chars.length - temp.length, temp.length);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.caliper.Benchmark;
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
/**
* Simple benchmark: create, start, read. This does not currently report the
* most useful result because it's ambiguous to what extent the stopwatch
* benchmark is being affected by GC.
*
* @author Kevin Bourrillion
*/
public class StopwatchBenchmark {
@Benchmark long stopwatch(int reps) {
long total = 0;
for (int i = 0; i < reps; i++) {
Stopwatch s = Stopwatch.createStarted();
// here is where you would do something
total += s.elapsed(TimeUnit.NANOSECONDS);
}
return total;
}
@Benchmark long manual(int reps) {
long total = 0;
for (int i = 0; i < reps; i++) {
long start = System.nanoTime();
// here is where you would do something
total += (System.nanoTime() - start);
}
return total;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
/**
* Some microbenchmarks for the {@link Objects.ToStringHelper} class.
*
* @author Osvaldo Doederlein
*/
public class ToStringHelperBenchmark {
@Param({"0", "2", "5", "10"}) int dataSize;
private static final String NAME = "abcdefgh";
private static final String NAME3 = Strings.repeat(NAME, 3);
private static void addEntries(Objects.ToStringHelper helper) {
helper
.add(NAME, 10)
.addValue(10L)
.add(NAME, 3.14f)
.addValue(3.14d)
.add(NAME3, false)
.add(NAME3, NAME3)
.add(NAME3, 'x');
}
@Benchmark int toString(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
Objects.ToStringHelper helper = Objects.toStringHelper("klass").omitNullValues();
for (int j = 0; j < dataSize; ++j) {
addEntries(helper);
}
dummy ^= helper
.toString().hashCode();
}
return dummy;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.base.Ascii;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Random;
/**
* Benchmarks for the ASCII class.
*
* @author Kevin Bourrillion
*/
public class AsciiBenchmark {
private static String ALPHA =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static String NONALPHA =
"0123456789`~-_=+[]{}|;:',.<>/?!@#$%^&*()\"\\";
@Param({"20", "2000"}) int size;
@Param({"2", "20"}) int nonAlphaRatio; // one non-alpha char per this many chars
@Param boolean noWorkToDo;
Random random;
String testString;
@BeforeExperiment void setUp() {
random = new Random();
int nonAlpha = size / nonAlphaRatio;
int alpha = size - nonAlpha;
List<Character> chars = Lists.newArrayListWithCapacity(size);
for (int i = 0; i < alpha; i++) {
chars.add(randomAlpha());
}
for (int i = 0; i < nonAlpha; i++) {
chars.add(randomNonAlpha());
}
Collections.shuffle(chars, random);
char[] array = Chars.toArray(chars);
this.testString = new String(array);
}
private char randomAlpha() {
return ALPHA.charAt(random.nextInt(ALPHA.length()));
}
private char randomNonAlpha() {
return NONALPHA.charAt(random.nextInt(NONALPHA.length()));
}
@Benchmark int asciiToUpperCase(int reps) {
String string = noWorkToDo
? Ascii.toUpperCase(testString)
: testString;
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Ascii.toUpperCase(string).length();
}
return dummy;
}
@Benchmark int stringToUpperCase1(int reps) {
String string = noWorkToDo
? testString.toUpperCase()
: testString;
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += string.toUpperCase().length();
}
return dummy;
}
@Benchmark int stringToUpperCase2(int reps) {
String string = noWorkToDo
? testString.toUpperCase(Locale.US)
: testString;
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += string.toUpperCase(Locale.US).length();
}
return dummy;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.Arrays;
import java.util.Iterator;
/**
* Benchmarks {@link Joiner} against some common implementations of delimiter-based
* string joining.
*
* @author Adomas Paltanavicius
*/
public class JoinerBenchmark {
private static final String DELIMITER_STRING = ",";
private static final char DELIMITER_CHARACTER = ',';
private static final Joiner JOINER_ON_STRING = Joiner.on(DELIMITER_STRING);
private static final Joiner JOINER_ON_CHARACTER = Joiner.on(DELIMITER_CHARACTER);
@Param({"3", "30", "300"}) int count;
@Param({"0", "1", "16", "32", "100"}) int componentLength;
private Iterable<String> components;
@BeforeExperiment
void setUp() {
String component = Strings.repeat("a", componentLength);
String[] raw = new String[count];
Arrays.fill(raw, component);
components = Arrays.asList(raw);
}
/**
* {@link Joiner} with a string delimiter.
*/
@Benchmark int joinerWithStringDelimiter(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy ^= JOINER_ON_STRING.join(components).length();
}
return dummy;
}
/**
* {@link Joiner} with a character delimiter.
*/
@Benchmark int joinerWithCharacterDelimiter(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy ^= JOINER_ON_CHARACTER.join(components).length();
}
return dummy;
}
/**
* Mimics what the {@link Joiner} class does internally when no extra options like
* ignoring {@code null} values are used.
*/
@Benchmark int joinerInlined(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
StringBuilder sb = new StringBuilder();
Iterator<String> iterator = components.iterator();
if (iterator.hasNext()) {
sb.append(iterator.next().toString());
while (iterator.hasNext()) {
sb.append(DELIMITER_STRING);
sb.append(iterator.next());
}
}
dummy ^= sb.toString().length();
}
return dummy;
}
/**
* Only appends delimiter if the accumulated string is non-empty.
* Note: this isn't a candidate implementation for Joiner since it fails on leading
* empty components.
*/
@Benchmark int stringBuilderIsEmpty(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
StringBuilder sb = new StringBuilder();
for (String comp : components) {
if (sb.length() > 0) {
sb.append(DELIMITER_STRING);
}
sb.append(comp);
}
dummy ^= sb.toString().length();
}
return dummy;
}
/**
* Similar to the above, but keeps a boolean flag rather than checking for the string
* accumulated so far being empty. As a result, it does not have the above-mentioned bug.
*/
@Benchmark int booleanIfFirst(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
StringBuilder sb = new StringBuilder();
boolean append = false;
for (String comp : components) {
if (append) {
sb.append(DELIMITER_STRING);
}
sb.append(comp);
append = true;
}
dummy ^= sb.toString().length();
}
return dummy;
}
/**
* Starts with an empty delimiter and changes to the desired value at the end of the
* iteration.
*/
@Benchmark int assignDelimiter(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
StringBuilder sb = new StringBuilder();
String delim = "";
for (String comp : components) {
sb.append(delim);
sb.append(comp);
delim = DELIMITER_STRING;
}
dummy ^= sb.toString().length();
}
return dummy;
}
/**
* Always append the delimiter after the component, and in the very end shortens the buffer
* to get rid of the extra trailing delimiter.
*/
@Benchmark int alwaysAppendThenBackUp(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
StringBuilder sb = new StringBuilder();
for (String comp : components) {
sb.append(comp);
sb.append(DELIMITER_STRING);
}
if (sb.length() > 0) {
sb.setLength(sb.length() - DELIMITER_STRING.length());
}
dummy ^= sb.toString().length();
}
return dummy;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.collect.Iterables;
/**
* Microbenchmark for {@link Splitter#on} with char vs String with length == 1.
*
* @author Paul Lindner
*/
public class SplitterBenchmark {
// overall size of string
@Param({"1", "10", "100", "1000"}) int length;
// Number of matching strings
@Param({"xxxx", "xxXx", "xXxX", "XXXX"}) String text;
private String input;
private static final Splitter CHAR_SPLITTER = Splitter.on('X');
private static final Splitter STRING_SPLITTER = Splitter.on("X");
@BeforeExperiment void setUp() {
input = Strings.repeat(text, length);
}
@Benchmark void charSplitter(int reps) {
int total = 0;
for (int i = 0; i < reps; i++) {
total += Iterables.size(CHAR_SPLITTER.split(input));
}
}
@Benchmark void stringSplitter(int reps) {
int total = 0;
for (int i = 0; i < reps; i++) {
total += Iterables.size(STRING_SPLITTER.split(input));
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.base.Strings;
/**
* Microbenchmark for {@link Strings#repeat}
*
* @author Mike Cripps
*/
public class StringsRepeatBenchmark {
@Param({"1", "5", "25", "125"}) int count;
@Param({"1", "10"}) int length;
private String originalString;
@BeforeExperiment void setUp() {
originalString = Strings.repeat("x", length);
}
@Benchmark void oldRepeat(int reps) {
for (int i = 0; i < reps; i++) {
String x = oldRepeat(originalString, count);
if (x.length() != (originalString.length() * count)) {
throw new RuntimeException("Wrong length: "+x);
}
}
}
@Benchmark void mikeRepeat(int reps) {
for (int i = 0; i < reps; i++) {
String x = mikeRepeat(originalString, count);
if (x.length() != (originalString.length() * count)) {
throw new RuntimeException("Wrong length: "+x);
}
}
}
@Benchmark void martinRepeat(int reps) {
for (int i = 0; i < reps; i++) {
String x = martinRepeat(originalString, count);
if (x.length() != (originalString.length() * count)) {
throw new RuntimeException("Wrong length: "+x);
}
}
}
private static String mikeRepeat(String string, int count) {
final int len = string.length();
char[] strCopy = new char[len * Integer.highestOneBit(count)];
string.getChars(0, len, strCopy, 0);
char[] array = new char[len * count];
int strCopyLen = len;
int pos = 0;
while (count != 0) {
if ((count & 1) != 0) {
System.arraycopy(strCopy, 0, array, pos,strCopyLen);
pos += strCopyLen;
}
count >>= 1;
if (count != 0) {
System.arraycopy(strCopy, 0, strCopy, strCopyLen, strCopyLen);
strCopyLen <<= 1;
}
}
return new String(array);
}
private static String oldRepeat(String string, int count) {
// If this multiplication overflows, a NegativeArraySizeException or
// OutOfMemoryError is not far behind
final int len = string.length();
final int size = len * count;
char[] array = new char[size];
for (int i = 0; i < size; i+=len) {
string.getChars(0, len, array, i);
}
return new String(array);
}
private static String martinRepeat(String string, int count) {
final int len = string.length();
final int size = len * count;
final char[] array = new char[size];
string.getChars(0, len, array, 0);
int n;
for (n = len; n < size - n; n <<= 1) {
System.arraycopy(array, 0, array, n, n);
}
System.arraycopy(array, 0, array, n, size - n);
return new String(array);
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.caliper.Benchmark;
import com.google.common.base.Objects;
/**
* Some microbenchmarks for the {@link Objects} class.
*
* @author Ben L. Titzer
*/
public class ObjectsBenchmark {
private static final Integer I0 = -45;
private static final Integer I1 = -1;
private static final Integer I2 = 3;
private static final String S0 = "3";
private static final String S1 = "Ninety five";
private static final String S2 = "44 one million";
private static final String S3 = "Lowly laundry lefties";
private static final String S4 = "89273487U#*&#";
private static final Double D0 = 9.234d;
private static final Double D1 = -1.2e55;
@Benchmark int hashString_2(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(S0, S1);
}
return dummy;
}
@Benchmark int hashString_3(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(S0, S1, S2);
}
return dummy;
}
@Benchmark int hashString_4(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(S0, S1, S2, S3);
}
return dummy;
}
@Benchmark int hashString_5(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(S0, S1, S2, S3, S4);
}
return dummy;
}
@Benchmark int hashMixed_5(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(I2, S1, D1, S2, I0);
dummy += Objects.hashCode(D0, I1, S3, I2, S0);
}
return dummy;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.primitives;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import java.util.Random;
/**
* Benchmarks for certain methods of {@code UnsignedLongs}.
*
* @author Eamonn McManus
*/
public class UnsignedLongsBenchmark {
private static final int ARRAY_SIZE = 0x10000;
private static final int ARRAY_MASK = 0x0ffff;
private static final Random RANDOM_SOURCE = new Random(314159265358979L);
private static final long[] longs = new long[ARRAY_SIZE];
private static final long[] divisors = new long[ARRAY_SIZE];
private static final String[] decimalStrings = new String[ARRAY_SIZE];
private static final String[] binaryStrings = new String[ARRAY_SIZE];
private static final String[] hexStrings = new String[ARRAY_SIZE];
private static final String[] prefixedHexStrings = new String[ARRAY_SIZE];
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
longs[i] = random();
divisors[i] = randomDivisor(longs[i]);
decimalStrings[i] = UnsignedLongs.toString(longs[i]);
binaryStrings[i] = UnsignedLongs.toString(longs[i], 2);
hexStrings[i] = UnsignedLongs.toString(longs[i], 16);
prefixedHexStrings[i] = "0x" + hexStrings[i];
}
}
@Benchmark long divide(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.divide(longs[j], divisors[j]);
}
return tmp;
}
@Benchmark long remainder(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.remainder(longs[j], divisors[j]);
}
return tmp;
}
@Benchmark long parseUnsignedLong(int reps) {
long tmp = 0;
// Given that we make three calls per pass, we scale reps down in order
// to do a comparable amount of work to other measurements.
int scaledReps = reps / 3 + 1;
for (int i = 0; i < scaledReps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.parseUnsignedLong(decimalStrings[j]);
tmp += UnsignedLongs.parseUnsignedLong(hexStrings[j], 16);
tmp += UnsignedLongs.parseUnsignedLong(binaryStrings[j], 2);
}
return tmp;
}
@Benchmark long parseDecode10(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.decode(decimalStrings[j]);
}
return tmp;
}
@Benchmark long parseDecode16(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.decode(prefixedHexStrings[j]);
}
return tmp;
}
@Benchmark int toString(int reps) {
int tmp = 0;
// Given that we make three calls per pass, we scale reps down in order
// to do a comparable amount of work to other measurements.
int scaledReps = reps / 3 + 1;
for (int i = 0; i < scaledReps; i++) {
int j = i & ARRAY_MASK;
long x = longs[j];
tmp += UnsignedLongs.toString(x).length();
tmp += UnsignedLongs.toString(x, 16).length();
tmp += UnsignedLongs.toString(x, 2).length();
}
return tmp;
}
private static long random() {
return RANDOM_SOURCE.nextLong();
}
// A random value that cannot be 0 and that is unsigned-less-than or equal
// to the given dividend, so that we don't have half of our divisions being
// trivial because the divisor is bigger than the dividend.
// Using remainder here does not give us a uniform distribution but it should
// not have a big impact on the measurement.
private static long randomDivisor(long dividend) {
long r = RANDOM_SOURCE.nextLong();
if (dividend == -1) {
return r;
} else {
return UnsignedLongs.remainder(r, dividend + 1);
}
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.primitives;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
/**
* Microbenchmark for {@link UnsignedBytes}.
*
* @author Hiroshi Yamauchi
*/
public class UnsignedBytesBenchmark {
private byte[] ba1;
private byte[] ba2;
private byte[] ba3;
private byte[] ba4;
private Comparator<byte[]> javaImpl;
private Comparator<byte[]> unsafeImpl;
// 4, 8, 64, 1K, 1M, 1M (unaligned), 64M, 64M (unaligned)
//@Param({"4", "8", "64", "1024", "1048576", "1048577", "6710884", "6710883"})
@Param({"4", "8", "64", "1024" })
private int length;
@BeforeExperiment
void setUp() throws Exception {
Random r = new Random();
ba1 = new byte[length];
r.nextBytes(ba1);
ba2 = Arrays.copyOf(ba1, ba1.length);
// Differ at the last element
ba3 = Arrays.copyOf(ba1, ba1.length);
ba4 = Arrays.copyOf(ba1, ba1.length);
ba3[ba1.length - 1] = (byte) 43;
ba4[ba1.length - 1] = (byte) 42;
javaImpl = UnsignedBytes.lexicographicalComparatorJavaImpl();
unsafeImpl =
UnsignedBytes.LexicographicalComparatorHolder.UnsafeComparator.INSTANCE;
}
@Benchmark void longEqualJava(int reps) {
for (int i = 0; i < reps; ++i) {
if (javaImpl.compare(ba1, ba2) != 0) {
throw new Error(); // deoptimization
}
}
}
@Benchmark void longEqualUnsafe(int reps) {
for (int i = 0; i < reps; ++i) {
if (unsafeImpl.compare(ba1, ba2) != 0) {
throw new Error(); // deoptimization
}
}
}
@Benchmark void diffLastJava(int reps) {
for (int i = 0; i < reps; ++i) {
if (javaImpl.compare(ba3, ba4) == 0) {
throw new Error(); // deoptimization
}
}
}
@Benchmark void diffLastUnsafe(int reps) {
for (int i = 0; i < reps; ++i) {
if (unsafeImpl.compare(ba3, ba4) == 0) {
throw new Error(); // deoptimization
}
}
}
/*
try {
UnsignedBytesBenchmark bench = new UnsignedBytesBenchmark();
bench.length = 1024;
bench.setUp();
bench.timeUnsafe(100000);
} catch (Exception e) {
}*/
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.randomDouble;
import static com.google.common.math.MathBenchmarking.randomPositiveDouble;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.math.DoubleMath;
import java.math.RoundingMode;
/**
* Benchmarks for the rounding methods of {@code DoubleMath}.
*
* @author Louis Wasserman
*/
public class DoubleMathRoundingBenchmark {
private static final double[] doubleInIntRange = new double[ARRAY_SIZE];
private static final double[] doubleInLongRange = new double[ARRAY_SIZE];
private static final double[] positiveDoubles = new double[ARRAY_SIZE];
@Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
RoundingMode mode;
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
doubleInIntRange[i] = randomDouble(Integer.SIZE - 2);
doubleInLongRange[i] = randomDouble(Long.SIZE - 2);
positiveDoubles[i] = randomPositiveDouble();
}
}
@Benchmark int roundToInt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += DoubleMath.roundToInt(doubleInIntRange[j], mode);
}
return tmp;
}
@Benchmark long roundToLong(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += DoubleMath.roundToLong(doubleInLongRange[j], mode);
}
return tmp;
}
@Benchmark int roundToBigInteger(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += DoubleMath.roundToBigInteger(positiveDoubles[j], mode).intValue();
}
return tmp;
}
@Benchmark int log2Round(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += DoubleMath.log2(positiveDoubles[j], mode);
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomExponent;
import static com.google.common.math.MathBenchmarking.randomNonNegativeBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.common.math.LongMath;
/**
* Benchmarks for the non-rounding methods of {@code LongMath}.
*
* @author Louis Wasserman
*/
public class LongMathBenchmark {
private static final int[] exponents = new int[ARRAY_SIZE];
private static final int[] factorialArguments = new int[ARRAY_SIZE];
private static final int[][] binomialArguments = new int[ARRAY_SIZE][2];
private static final long[] positive = new long[ARRAY_SIZE];
private static final long[] nonnegative = new long[ARRAY_SIZE];
private static final long[] longs = new long[ARRAY_SIZE];
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
exponents[i] = randomExponent();
positive[i] = randomPositiveBigInteger(Long.SIZE - 2).longValue();
nonnegative[i] = randomNonNegativeBigInteger(Long.SIZE - 2).longValue();
longs[i] = RANDOM_SOURCE.nextLong();
factorialArguments[i] = RANDOM_SOURCE.nextInt(30);
binomialArguments[i][1] = RANDOM_SOURCE.nextInt(MathBenchmarking.biggestBinomials.length);
int k = binomialArguments[i][1];
binomialArguments[i][0] =
RANDOM_SOURCE.nextInt(MathBenchmarking.biggestBinomials[k] - k) + k;
}
}
@Benchmark int pow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.pow(positive[j], exponents[j]);
}
return tmp;
}
@Benchmark int mod(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.mod(longs[j], positive[j]);
}
return tmp;
}
@Benchmark int gCD(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.mod(nonnegative[j], positive[j]);
}
return tmp;
}
@Benchmark int factorial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.factorial(factorialArguments[j]);
}
return tmp;
}
@Benchmark int binomial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.binomial(binomialArguments[j][0], binomialArguments[j][1]);
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.caliper.api.SkipThisScenarioException;
import com.google.common.primitives.Doubles;
import java.util.Random;
/**
* Benchmarks for various algorithms for computing the mean and/or variance.
*
* @author Louis Wasserman
*/
public class StatsBenchmark {
enum MeanAlgorithm {
SIMPLE {
@Override
double mean(double[] values) {
double sum = 0.0;
for (double value : values) {
sum += value;
}
return sum / values.length;
}
},
KAHAN {
@Override
double mean(double[] values) {
double sum = 0.0;
double c = 0.0;
for (double value : values) {
double y = value - c;
double t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum / values.length;
}
},
KNUTH {
@Override
double mean(double[] values) {
double mean = values[0];
for (int i = 1; i < values.length; i++) {
mean = mean + (values[i] - mean) / (i + 1);
}
return mean;
}
};
abstract double mean(double[] values);
}
static class MeanAndVariance {
private final double mean;
private final double variance;
MeanAndVariance(double mean, double variance) {
this.mean = mean;
this.variance = variance;
}
@Override
public int hashCode() {
return Doubles.hashCode(mean) * 31 + Doubles.hashCode(variance);
}
}
enum VarianceAlgorithm {
DO_NOT_COMPUTE {
@Override
MeanAndVariance variance(double[] values, MeanAlgorithm meanAlgorithm) {
return new MeanAndVariance(meanAlgorithm.mean(values), 0.0);
}
},
SIMPLE {
@Override
MeanAndVariance variance(double[] values, MeanAlgorithm meanAlgorithm) {
double mean = meanAlgorithm.mean(values);
double sumOfSquaresOfDeltas = 0.0;
for (double value : values) {
double delta = value - mean;
sumOfSquaresOfDeltas += delta * delta;
}
return new MeanAndVariance(mean, sumOfSquaresOfDeltas / values.length);
}
},
KAHAN {
@Override
MeanAndVariance variance(double[] values, MeanAlgorithm meanAlgorithm) {
double mean = meanAlgorithm.mean(values);
double sumOfSquaresOfDeltas = 0.0;
double c = 0.0;
for (double value : values) {
double delta = value - mean;
double deltaSquared = delta * delta;
double y = deltaSquared - c;
double t = sumOfSquaresOfDeltas + deltaSquared;
c = (t - sumOfSquaresOfDeltas) - y;
sumOfSquaresOfDeltas = t;
}
return new MeanAndVariance(mean, sumOfSquaresOfDeltas / values.length);
}
},
KNUTH {
@Override
MeanAndVariance variance(double[] values, MeanAlgorithm meanAlgorithm) {
if (meanAlgorithm != MeanAlgorithm.KNUTH) {
throw new SkipThisScenarioException();
}
double mean = values[0];
double s = 0.0;
for (int i = 1; i < values.length; i++) {
double nextMean = mean + (values[i] - mean) / (i + 1);
s += (values[i] - mean) * (values[i] - nextMean);
mean = nextMean;
}
return new MeanAndVariance(mean, s / values.length);
}
};
abstract MeanAndVariance variance(double[] values, MeanAlgorithm meanAlgorithm);
}
@Param({"100", "10000"})
int n;
@Param
MeanAlgorithm meanAlgorithm;
@Param
VarianceAlgorithm varianceAlgorithm;
private double[][] values = new double[0x100][];
@BeforeExperiment
void setUp() {
Random rng = new Random();
for (int i = 0; i < 0x100; i++) {
values[i] = new double[n];
for (int j = 0; j < n; j++) {
values[i][j] = rng.nextDouble();
}
}
}
@Benchmark int meanAndVariance(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
tmp += varianceAlgorithm.variance(values[i & 0xFF], meanAlgorithm).hashCode();
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomDouble;
import static com.google.common.math.MathBenchmarking.randomPositiveDouble;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
/**
* Tests for the non-rounding methods of {@code DoubleMath}.
*
* @author Louis Wasserman
*/
public class DoubleMathBenchmark {
private static final double[] positiveDoubles = new double[ARRAY_SIZE];
private static final int[] factorials = new int[ARRAY_SIZE];
private static final double [] doubles = new double[ARRAY_SIZE];
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
positiveDoubles[i] = randomPositiveDouble();
doubles[i] = randomDouble(Long.SIZE);
factorials[i] = RANDOM_SOURCE.nextInt(100);
}
}
@Benchmark long log2(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += Double.doubleToRawLongBits(DoubleMath.log2(positiveDoubles[j]));
}
return tmp;
}
@Benchmark long factorial(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += Double.doubleToRawLongBits(DoubleMath.factorial(factorials[j]));
}
return tmp;
}
@Benchmark int isMathematicalInteger(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (DoubleMath.isMathematicalInteger(doubles[j])) {
tmp++;
}
}
return tmp;
}
@Benchmark int isPowerOfTwo(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (DoubleMath.isPowerOfTwo(doubles[j])) {
tmp++;
}
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static java.math.RoundingMode.CEILING;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.math.BigIntegerMath;
import com.google.common.math.IntMath;
import com.google.common.math.LongMath;
import java.math.BigInteger;
/**
* Benchmarks for the non-rounding methods of {@code BigIntegerMath}.
*
* @author Louis Wasserman
*/
public class BigIntegerMathBenchmark {
private static final int[] factorials = new int[ARRAY_SIZE];
private static final int[] slowFactorials = new int[ARRAY_SIZE];
private static final int[] binomials = new int[ARRAY_SIZE];
@Param({"50", "1000", "10000"})
int factorialBound;
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
factorials[i] = RANDOM_SOURCE.nextInt(factorialBound);
slowFactorials[i] = RANDOM_SOURCE.nextInt(factorialBound);
binomials[i] = RANDOM_SOURCE.nextInt(factorials[i] + 1);
}
}
/**
* Previous version of BigIntegerMath.factorial, kept for timing purposes.
*/
private static BigInteger oldSlowFactorial(int n) {
if (n <= 20) {
return BigInteger.valueOf(LongMath.factorial(n));
} else {
int k = 20;
return BigInteger.valueOf(LongMath.factorial(k)).multiply(oldSlowFactorial(k, n));
}
}
/**
* Returns the product of {@code n1} exclusive through {@code n2} inclusive.
*/
private static BigInteger oldSlowFactorial(int n1, int n2) {
assert n1 <= n2;
if (IntMath.log2(n2, CEILING) * (n2 - n1) < Long.SIZE - 1) {
// the result will definitely fit into a long
long result = 1;
for (int i = n1 + 1; i <= n2; i++) {
result *= i;
}
return BigInteger.valueOf(result);
}
/*
* We want each multiplication to have both sides with approximately the same number of digits.
* Currently, we just divide the range in half.
*/
int mid = (n1 + n2) >>> 1;
return oldSlowFactorial(n1, mid).multiply(oldSlowFactorial(mid, n2));
}
@Benchmark int slowFactorial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += oldSlowFactorial(slowFactorials[j]).intValue();
}
return tmp;
}
@Benchmark int factorial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.factorial(factorials[j]).intValue();
}
return tmp;
}
@Benchmark int binomial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & 0xffff;
tmp += BigIntegerMath.binomial(factorials[j], binomials[j]).intValue();
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomNonZeroBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.math.IntMath;
import java.math.RoundingMode;
/**
* Benchmarks for the rounding methods of {@code IntMath}.
*
* @author Louis Wasserman
*/
public class IntMathRoundingBenchmark {
private static final int[] positive = new int[ARRAY_SIZE];
private static final int[] nonzero = new int[ARRAY_SIZE];
private static final int[] ints = new int[ARRAY_SIZE];
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
positive[i] = randomPositiveBigInteger(Integer.SIZE - 2).intValue();
nonzero[i] = randomNonZeroBigInteger(Integer.SIZE - 2).intValue();
ints[i] = RANDOM_SOURCE.nextInt();
}
}
@Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
RoundingMode mode;
@Benchmark int log2(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.log2(positive[j], mode);
}
return tmp;
}
@Benchmark int log10(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.log10(positive[j], mode);
}
return tmp;
}
@Benchmark int sqrt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.sqrt(positive[j], mode);
}
return tmp;
}
@Benchmark int divide(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.divide(ints[j], nonzero[j], mode);
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomNonZeroBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.math.LongMath;
import java.math.RoundingMode;
/**
* Benchmarks for the rounding methods of {@code LongMath}.
*
* @author Louis Wasserman
*/
public class LongMathRoundingBenchmark {
@Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
RoundingMode mode;
private static final long[] positive = new long[ARRAY_SIZE];
private static final long[] nonzero = new long[ARRAY_SIZE];
private static final long[] longs = new long[ARRAY_SIZE];
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
positive[i] = randomPositiveBigInteger(Long.SIZE - 2).longValue();
nonzero[i] = randomNonZeroBigInteger(Long.SIZE - 2).longValue();
longs[i] = RANDOM_SOURCE.nextLong();
}
}
@Benchmark int log2(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.log2(positive[j], mode);
}
return tmp;
}
@Benchmark int log10(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.log10(positive[j], mode);
}
return tmp;
}
@Benchmark int sqrt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.sqrt(positive[j], mode);
}
return tmp;
}
@Benchmark int divide(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.divide(longs[j], nonzero[j], mode);
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomBigInteger;
import static com.google.common.math.MathBenchmarking.randomNonNegativeBigInteger;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.math.DoubleMath;
import com.google.common.math.IntMath;
import com.google.common.math.LongMath;
/**
* Benchmarks against the Apache Commons Math utilities.
*
* <p>Note: the Apache benchmarks are not open sourced to avoid the extra dependency.
*
* @author Louis Wasserman
*/
public class ApacheBenchmark {
private enum Impl {
GUAVA {
@Override
public double factorialDouble(int n) {
return DoubleMath.factorial(n);
}
@Override
public int gcdInt(int a, int b) {
return IntMath.gcd(a, b);
}
@Override
public long gcdLong(long a, long b) {
return LongMath.gcd(a, b);
}
@Override
public long binomialCoefficient(int n, int k) {
return LongMath.binomial(n, k);
}
@Override
public boolean noAddOverflow(int a, int b) {
try {
IntMath.checkedAdd(a, b);
return true;
} catch (ArithmeticException e) {
return false;
}
}
@Override
public boolean noAddOverflow(long a, long b) {
try {
LongMath.checkedAdd(a, b);
return true;
} catch (ArithmeticException e) {
return false;
}
}
@Override
public boolean noMulOverflow(int a, int b) {
try {
IntMath.checkedMultiply(a, b);
return true;
} catch (ArithmeticException e) {
return false;
}
}
@Override
public boolean noMulOverflow(long a, long b) {
try {
LongMath.checkedMultiply(a, b);
return true;
} catch (ArithmeticException e) {
return false;
}
}
};
public abstract double factorialDouble(int n);
public abstract long binomialCoefficient(int n, int k);
public abstract int gcdInt(int a, int b);
public abstract long gcdLong(long a, long b);
public abstract boolean noAddOverflow(int a, int b);
public abstract boolean noAddOverflow(long a, long b);
public abstract boolean noMulOverflow(int a, int b);
public abstract boolean noMulOverflow(long a, long b);
}
private final int[] factorials = new int[ARRAY_SIZE];
private final int[][] binomials = new int[ARRAY_SIZE][2];
private final int[][] nonnegInt = new int[ARRAY_SIZE][2];
private final long[][] nonnegLong = new long[ARRAY_SIZE][2];
private final int[][] intsToAdd = new int[ARRAY_SIZE][2];
private final int[][] intsToMul = new int[ARRAY_SIZE][2];
private final long[][] longsToAdd = new long[ARRAY_SIZE][2];
private final long[][] longsToMul = new long[ARRAY_SIZE][2];
@Param({"APACHE", "GUAVA"})
Impl impl;
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
factorials[i] = RANDOM_SOURCE.nextInt(200);
for (int j = 0; j < 2; j++) {
nonnegInt[i][j] = randomNonNegativeBigInteger(Integer.SIZE - 2).intValue();
nonnegLong[i][j] = randomNonNegativeBigInteger(Long.SIZE - 2).longValue();
}
do {
for (int j = 0; j < 2; j++) {
intsToAdd[i][j] = randomBigInteger(Integer.SIZE - 2).intValue();
}
} while (!Impl.GUAVA.noAddOverflow(intsToAdd[i][0], intsToAdd[i][1]));
do {
for (int j = 0; j < 2; j++) {
longsToAdd[i][j] = randomBigInteger(Long.SIZE - 2).longValue();
}
} while (!Impl.GUAVA.noAddOverflow(longsToAdd[i][0], longsToAdd[i][1]));
do {
for (int j = 0; j < 2; j++) {
intsToMul[i][j] = randomBigInteger(Integer.SIZE - 2).intValue();
}
} while (!Impl.GUAVA.noMulOverflow(intsToMul[i][0], intsToMul[i][1]));
do {
for (int j = 0; j < 2; j++) {
longsToMul[i][j] = randomBigInteger(Long.SIZE - 2).longValue();
}
} while (!Impl.GUAVA.noMulOverflow(longsToMul[i][0], longsToMul[i][1]));
int k = binomials[i][1] = RANDOM_SOURCE.nextInt(MathBenchmarking.biggestBinomials.length);
binomials[i][0] = RANDOM_SOURCE.nextInt(MathBenchmarking.biggestBinomials[k] - k) + k;
}
}
@Benchmark long factorialDouble(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += Double.doubleToRawLongBits(impl.factorialDouble(factorials[j]));
}
return tmp;
}
@Benchmark int intGCD(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += impl.gcdInt(nonnegInt[j][0], nonnegInt[j][1]);
}
return tmp;
}
@Benchmark long longGCD(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += impl.gcdLong(nonnegLong[j][0], nonnegLong[j][1]);
}
return tmp;
}
@Benchmark long binomialCoefficient(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += impl.binomialCoefficient(binomials[j][0], binomials[j][1]);
}
return tmp;
}
@Benchmark int intAddOverflow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (impl.noAddOverflow(intsToAdd[j][0], intsToAdd[j][1])) {
tmp++;
}
}
return tmp;
}
@Benchmark int longAddOverflow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (impl.noAddOverflow(longsToAdd[j][0], longsToAdd[j][1])) {
tmp++;
}
}
return tmp;
}
@Benchmark int intMulOverflow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (impl.noMulOverflow(intsToMul[j][0], intsToMul[j][1])) {
tmp++;
}
}
return tmp;
}
@Benchmark int longMulOverflow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (impl.noMulOverflow(longsToMul[j][0], longsToMul[j][1])) {
tmp++;
}
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.randomNonZeroBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.math.BigIntegerMath;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* Benchmarks for the rounding methods of {@code BigIntegerMath}.
*
* @author Louis Wasserman
*/
public class BigIntegerMathRoundingBenchmark {
private static final BigInteger[] nonzero1 = new BigInteger[ARRAY_SIZE];
private static final BigInteger[] nonzero2 = new BigInteger[ARRAY_SIZE];
private static final BigInteger[] positive = new BigInteger[ARRAY_SIZE];
@Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
RoundingMode mode;
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
positive[i] = randomPositiveBigInteger(1024);
nonzero1[i] = randomNonZeroBigInteger(1024);
nonzero2[i] = randomNonZeroBigInteger(1024);
}
}
@Benchmark int log2(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.log2(positive[j], mode);
}
return tmp;
}
@Benchmark int log10(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.log10(positive[j], mode);
}
return tmp;
}
@Benchmark int sqrt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.sqrt(positive[j], mode).intValue();
}
return tmp;
}
@Benchmark int divide(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.divide(nonzero1[j], nonzero2[j], mode).intValue();
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomExponent;
import static com.google.common.math.MathBenchmarking.randomNonNegativeBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.common.math.IntMath;
/**
* Benchmarks for the non-rounding methods of {@code IntMath}.
*
* @author Louis Wasserman
*/
public class IntMathBenchmark {
private static int[] exponent = new int[ARRAY_SIZE];
private static int[] factorial = new int[ARRAY_SIZE];
private static int[] binomial = new int[ARRAY_SIZE];
private static final int[] positive = new int[ARRAY_SIZE];
private static final int[] nonnegative = new int[ARRAY_SIZE];
private static final int[] ints = new int[ARRAY_SIZE];
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
exponent[i] = randomExponent();
factorial[i] = RANDOM_SOURCE.nextInt(50);
binomial[i] = RANDOM_SOURCE.nextInt(factorial[i] + 1);
positive[i] = randomPositiveBigInteger(Integer.SIZE - 2).intValue();
nonnegative[i] = randomNonNegativeBigInteger(Integer.SIZE - 2).intValue();
ints[i] = RANDOM_SOURCE.nextInt();
}
}
@Benchmark int pow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.pow(positive[j], exponent[j]);
}
return tmp;
}
@Benchmark int mod(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.mod(ints[j], positive[j]);
}
return tmp;
}
@Benchmark int gCD(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.gcd(nonnegative[j], positive[j]);
}
return tmp;
}
@Benchmark int factorial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.factorial(factorial[j]);
}
return tmp;
}
@Benchmark int binomial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.binomial(factorial[j], binomial[j]);
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.Random;
/**
* Benchmarks for various ways of writing the expression {@code foo + ((bar < baz) ? 1 : 0)}.
*
* @author Louis Wasserman
*/
public class LessThanBenchmark {
static final int SAMPLE_SIZE = 0x1000;
static final int SAMPLE_MASK = 0x0FFF;
@Param("1234")
int randomSeed;
int[] xInts;
int[] yInts;
long[] xLongs;
long[] yLongs;
int[] constant;
private static final long NONNEGATIVE_LONG_MASK = 0x7FFFFFFFFFFFFFFFL;
@BeforeExperiment
void setUp() {
Random random = new Random(randomSeed);
xInts = new int[SAMPLE_SIZE];
yInts = new int[SAMPLE_SIZE];
xLongs = new long[SAMPLE_SIZE];
yLongs = new long[SAMPLE_SIZE];
constant = new int[SAMPLE_SIZE];
for (int i = 0; i < SAMPLE_SIZE; i++) {
xInts[i] = random.nextInt(Integer.MAX_VALUE);
yInts[i] = random.nextInt(Integer.MAX_VALUE);
xLongs[i] = random.nextLong() & NONNEGATIVE_LONG_MASK;
yLongs[i] = random.nextLong() & NONNEGATIVE_LONG_MASK;
constant[i] = random.nextInt();
}
}
@Benchmark int branchFreeLtIntInlined(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & SAMPLE_MASK;
int x = xInts[j];
int y = yInts[j];
int z = constant[j];
tmp += z + ((x - y) >>> (Integer.SIZE - 1));
}
return tmp;
}
@Benchmark int branchFreeLtInt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & SAMPLE_MASK;
int x = xInts[j];
int y = yInts[j];
int z = constant[j];
tmp += z + IntMath.lessThanBranchFree(x, y);
}
return tmp;
}
@Benchmark int ternaryLtIntAddOutsideTernary(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & SAMPLE_MASK;
int x = xInts[j];
int y = yInts[j];
int z = constant[j];
tmp += z + ((x < y) ? 1 : 0);
}
return tmp;
}
@Benchmark int ternaryLtIntAddInsideTernary(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & SAMPLE_MASK;
int x = xInts[j];
int y = yInts[j];
int z = constant[j];
tmp += (x < y) ? z + 1 : z;
}
return tmp;
}
@Benchmark int branchFreeLtLongInlined(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & SAMPLE_MASK;
long x = xLongs[j];
long y = yLongs[j];
int z = constant[j];
tmp += z + (int) ((x - y) >>> (Long.SIZE - 1));
}
return tmp;
}
@Benchmark int branchFreeLtLong(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & SAMPLE_MASK;
long x = xLongs[j];
long y = yLongs[j];
int z = constant[j];
tmp += z + LongMath.lessThanBranchFree(x, y);
}
return tmp;
}
@Benchmark int ternaryLtLongAddOutsideTernary(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & SAMPLE_MASK;
long x = xLongs[j];
long y = yLongs[j];
int z = constant[j];
tmp += z + ((x < y) ? 1 : 0);
}
return tmp;
}
@Benchmark int ternaryLtLongAddInsideTernary(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & SAMPLE_MASK;
long x = xLongs[j];
long y = yLongs[j];
int z = constant[j];
tmp += (x < y) ? z + 1 : z;
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.eventbus;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
/**
* Benchmark for {@link EventBus}.
*
* @author Eric Fellheimer
*/
public class EventBusBenchmark {
private EventBus eventBus;
@BeforeExperiment
void setUp() {
eventBus = new EventBus("for benchmarking purposes");
eventBus.register(this);
}
@Benchmark void postStrings(int reps) {
for (int i = 0; i < reps; i++) {
eventBus.post("hello there");
}
}
@Subscribe
public void handleStrings(String string) {
// Nothing to do here.
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.Benchmark;
/**
* Benchmarking interners.
*
* @author Dimitris Andreou
*/
public class InternersBenchmark {
@Benchmark int weakInterner(int reps) {
Interner<String> interner = Interners.newWeakInterner();
for (int i = 0; i < reps; i++) {
interner.intern(Double.toHexString(Math.random()));
}
return reps;
}
@Benchmark int strongInterner(int reps) {
Interner<String> interner = Interners.newStrongInterner();
for (int i = 0; i < reps; i++) {
interner.intern(Double.toHexString(Math.random()));
}
return reps;
}
@SuppressWarnings("ReturnValueIgnored")
@Benchmark int stringIntern(int reps) {
for (int i = 0; i < reps; i++) {
Double.toHexString(Math.random()).intern();
}
return reps;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Multisets.checkNonnegative;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.annotation.Nullable;
/**
* Benchmarks for {@link ConcurrentHashMultiset}.
*
* @author mike nonemacher
*/
public class ConcurrentHashMultisetBenchmark {
@Param({"1", "2", "4", "8"}) int threads;
@Param({"3", "30", "300"}) int size;
@Param MultisetSupplier implSupplier;
private Multiset<Integer> multiset;
private ImmutableList<Integer> keys;
private ExecutorService threadPool;
@BeforeExperiment void setUp() throws Exception {
multiset = implSupplier.get();
ImmutableList.Builder<Integer> builder = ImmutableList.builder();
for (int i = 0; i < size; i++) {
builder.add(i);
}
keys = builder.build();
threadPool =
Executors.newFixedThreadPool(threads, new ThreadFactoryBuilder().setDaemon(true).build());
}
@Benchmark long add(final int reps) throws ExecutionException, InterruptedException {
return doMultithreadedLoop(
new Callable<Long>() {
@Override public Long call() {
return runAddSingleThread(reps);
}
});
}
@Benchmark long addRemove(final int reps) throws ExecutionException, InterruptedException {
return doMultithreadedLoop(
new Callable<Long>() {
@Override public Long call() {
return runAddRemoveSingleThread(reps);
}
});
}
private long doMultithreadedLoop(Callable<Long> task)
throws InterruptedException, ExecutionException {
List<Future<Long>> futures = Lists.newArrayListWithCapacity(threads);
for (int i = 0; i < threads; i++) {
futures.add(threadPool.submit(task));
}
long total = 0;
for (Future<Long> future : futures) {
total += future.get();
}
return total;
}
private long runAddSingleThread(int reps) {
Random random = new Random();
int nKeys = keys.size();
long blah = 0;
for (int i = 0; i < reps; i++) {
Integer key = keys.get(random.nextInt(nKeys));
int delta = random.nextInt(5);
blah += delta;
multiset.add(key, delta);
}
return blah;
}
private long runAddRemoveSingleThread(int reps) {
Random random = new Random();
int nKeys = keys.size();
long blah = 0;
for (int i = 0; i < reps; i++) {
Integer key = keys.get(random.nextInt(nKeys));
// This range is [-5, 4] - slight negative bias so we often hit zero, which brings the
// auto-removal of zeroes into play.
int delta = random.nextInt(10) - 5;
blah += delta;
if (delta >= 0) {
multiset.add(key, delta);
} else {
multiset.remove(key, -delta);
}
}
return blah;
}
private enum MultisetSupplier {
CONCURRENT_HASH_MULTISET() {
@Override Multiset<Integer> get() {
return ConcurrentHashMultiset.create();
}
},
BOXED_ATOMIC_REPLACE() {
@Override Multiset<Integer> get() {
return OldConcurrentHashMultiset.create();
}
},
SYNCHRONIZED_MULTISET() {
@Override Multiset<Integer> get() {
return Synchronized.multiset(HashMultiset.<Integer>create(), null);
}
},
;
abstract Multiset<Integer> get();
}
/**
* Duplication of the old version of ConcurrentHashMultiset (with some unused stuff removed, like
* serialization code) which used a map with boxed integers for the values.
*/
private static final class OldConcurrentHashMultiset<E> extends AbstractMultiset<E> {
/** The number of occurrences of each element. */
private final transient ConcurrentMap<E, Integer> countMap;
/**
* Creates a new, empty {@code OldConcurrentHashMultiset} using the default
* initial capacity, load factor, and concurrency settings.
*/
public static <E> OldConcurrentHashMultiset<E> create() {
return new OldConcurrentHashMultiset<E>(new ConcurrentHashMap<E, Integer>());
}
@VisibleForTesting OldConcurrentHashMultiset(ConcurrentMap<E, Integer> countMap) {
checkArgument(countMap.isEmpty());
this.countMap = countMap;
}
// Query Operations
/**
* Returns the number of occurrences of {@code element} in this multiset.
*
* @param element the element to look for
* @return the nonnegative number of occurrences of the element
*/
@Override public int count(@Nullable Object element) {
try {
return unbox(countMap.get(element));
} catch (NullPointerException e) {
return 0;
} catch (ClassCastException e) {
return 0;
}
}
/**
* {@inheritDoc}
*
* <p>If the data in the multiset is modified by any other threads during this
* method, it is undefined which (if any) of these modifications will be
* reflected in the result.
*/
@Override public int size() {
long sum = 0L;
for (Integer value : countMap.values()) {
sum += value;
}
return Ints.saturatedCast(sum);
}
/*
* Note: the superclass toArray() methods assume that size() gives a correct
* answer, which ours does not.
*/
@Override public Object[] toArray() {
return snapshot().toArray();
}
@Override public <T> T[] toArray(T[] array) {
return snapshot().toArray(array);
}
/*
* We'd love to use 'new ArrayList(this)' or 'list.addAll(this)', but
* either of these would recurse back to us again!
*/
private List<E> snapshot() {
List<E> list = Lists.newArrayListWithExpectedSize(size());
for (Multiset.Entry<E> entry : entrySet()) {
E element = entry.getElement();
for (int i = entry.getCount(); i > 0; i--) {
list.add(element);
}
}
return list;
}
// Modification Operations
/**
* Adds a number of occurrences of the specified element to this multiset.
*
* @param element the element to add
* @param occurrences the number of occurrences to add
* @return the previous count of the element before the operation; possibly
* zero
* @throws IllegalArgumentException if {@code occurrences} is negative, or if
* the resulting amount would exceed {@link Integer#MAX_VALUE}
*/
@Override public int add(E element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
while (true) {
int current = count(element);
if (current == 0) {
if (countMap.putIfAbsent(element, occurrences) == null) {
return 0;
}
} else {
checkArgument(occurrences <= Integer.MAX_VALUE - current,
"Overflow adding %s occurrences to a count of %s",
occurrences, current);
int next = current + occurrences;
if (countMap.replace(element, current, next)) {
return current;
}
}
// If we're still here, there was a race, so just try again.
}
}
/**
* Removes a number of occurrences of the specified element from this
* multiset. If the multiset contains fewer than this number of occurrences to
* begin with, all occurrences will be removed.
*
* @param element the element whose occurrences should be removed
* @param occurrences the number of occurrences of the element to remove
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative
*/
@Override public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
while (true) {
int current = count(element);
if (current == 0) {
return 0;
}
if (occurrences >= current) {
if (countMap.remove(element, current)) {
return current;
}
} else {
// We know it's an "E" because it already exists in the map.
@SuppressWarnings("unchecked")
E casted = (E) element;
if (countMap.replace(casted, current, current - occurrences)) {
return current;
}
}
// If we're still here, there was a race, so just try again.
}
}
/**
* Removes <b>all</b> occurrences of the specified element from this multiset.
* This method complements {@link Multiset#remove(Object)}, which removes only
* one occurrence at a time.
*
* @param element the element whose occurrences should all be removed
* @return the number of occurrences successfully removed, possibly zero
*/
private int removeAllOccurrences(@Nullable Object element) {
try {
return unbox(countMap.remove(element));
} catch (NullPointerException e) {
return 0;
} catch (ClassCastException e) {
return 0;
}
}
/**
* Removes exactly the specified number of occurrences of {@code element}, or
* makes no change if this is not possible.
*
* <p>This method, in contrast to {@link #remove(Object, int)}, has no effect
* when the element count is smaller than {@code occurrences}.
*
* @param element the element to remove
* @param occurrences the number of occurrences of {@code element} to remove
* @return {@code true} if the removal was possible (including if {@code
* occurrences} is zero)
*/
public boolean removeExactly(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return true;
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
while (true) {
int current = count(element);
if (occurrences > current) {
return false;
}
if (occurrences == current) {
if (countMap.remove(element, occurrences)) {
return true;
}
} else {
@SuppressWarnings("unchecked") // it's in the map, must be an "E"
E casted = (E) element;
if (countMap.replace(casted, current, current - occurrences)) {
return true;
}
}
// If we're still here, there was a race, so just try again.
}
}
/**
* Adds or removes occurrences of {@code element} such that the {@link #count}
* of the element becomes {@code count}.
*
* @return the count of {@code element} in the multiset before this call
* @throws IllegalArgumentException if {@code count} is negative
*/
@Override public int setCount(E element, int count) {
checkNonnegative(count, "count");
return (count == 0)
? removeAllOccurrences(element)
: unbox(countMap.put(element, count));
}
/**
* Sets the number of occurrences of {@code element} to {@code newCount}, but
* only if the count is currently {@code oldCount}. If {@code element} does
* not appear in the multiset exactly {@code oldCount} times, no changes will
* be made.
*
* @return {@code true} if the change was successful. This usually indicates
* that the multiset has been modified, but not always: in the case that
* {@code oldCount == newCount}, the method will return {@code true} if
* the condition was met.
* @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is
* negative
*/
@Override public boolean setCount(E element, int oldCount, int newCount) {
checkNonnegative(oldCount, "oldCount");
checkNonnegative(newCount, "newCount");
if (newCount == 0) {
if (oldCount == 0) {
// No change to make, but must return true if the element is not present
return !countMap.containsKey(element);
} else {
return countMap.remove(element, oldCount);
}
}
if (oldCount == 0) {
return countMap.putIfAbsent(element, newCount) == null;
}
return countMap.replace(element, oldCount, newCount);
}
// Views
@Override Set<E> createElementSet() {
final Set<E> delegate = countMap.keySet();
return new ForwardingSet<E>() {
@Override protected Set<E> delegate() {
return delegate;
}
@Override public boolean remove(Object object) {
try {
return delegate.remove(object);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
};
}
private transient EntrySet entrySet;
@Override public Set<Multiset.Entry<E>> entrySet() {
EntrySet result = entrySet;
if (result == null) {
entrySet = result = new EntrySet();
}
return result;
}
@Override int distinctElements() {
return countMap.size();
}
@Override public boolean isEmpty() {
return countMap.isEmpty();
}
@Override Iterator<Entry<E>> entryIterator() {
final Iterator<Map.Entry<E, Integer>> backingIterator =
countMap.entrySet().iterator();
return new Iterator<Entry<E>>() {
@Override public boolean hasNext() {
return backingIterator.hasNext();
}
@Override public Multiset.Entry<E> next() {
Map.Entry<E, Integer> backingEntry = backingIterator.next();
return Multisets.immutableEntry(backingEntry.getKey(),
backingEntry.getValue());
}
@Override public void remove() {
backingIterator.remove();
}
};
}
@Override public void clear() {
countMap.clear();
}
private class EntrySet extends AbstractMultiset<E>.EntrySet {
@Override Multiset<E> multiset() {
return OldConcurrentHashMultiset.this;
}
/*
* Note: the superclass toArray() methods assume that size() gives a correct
* answer, which ours does not.
*/
@Override public Object[] toArray() {
return snapshot().toArray();
}
@Override public <T> T[] toArray(T[] array) {
return snapshot().toArray(array);
}
private List<Multiset.Entry<E>> snapshot() {
List<Multiset.Entry<E>> list = Lists.newArrayListWithExpectedSize(size());
// not Iterables.addAll(list, this), because that'll forward back here
Iterators.addAll(list, iterator());
return list;
}
@Override public boolean remove(Object object) {
if (object instanceof Multiset.Entry) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) object;
Object element = entry.getElement();
int entryCount = entry.getCount();
return countMap.remove(element, entryCount);
}
return false;
}
/**
* The hash code is the same as countMap's, though the objects aren't equal.
*/
@Override public int hashCode() {
return countMap.hashCode();
}
}
/**
* We use a special form of unboxing that treats null as zero.
*/
private static int unbox(@Nullable Integer i) {
return (i == null) ? 0 : i;
}
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.base.Preconditions;
import java.util.Random;
/**
* Tests the speed of iteration of different iteration methods for collections.
*
* @author David Richter
*/
public class MultisetIteratorBenchmark {
@Param({"0", "1", "16", "256", "4096", "65536"}) int size;
LinkedHashMultiset<Object> linkedHashMultiset;
HashMultiset<Object> hashMultiset;
// TreeMultiset requires a Comparable element.
TreeMultiset<Integer> treeMultiset;
@BeforeExperiment void setUp() {
hashMultiset = HashMultiset.create(size);
linkedHashMultiset = LinkedHashMultiset.create(size);
treeMultiset = TreeMultiset.create();
Random random = new Random();
int sizeRemaining = size;
// TODO(kevinb): generate better test contents for multisets
for (int i = 0; sizeRemaining > 0; i++) {
// The JVM will return interned values for small ints.
Integer value = random.nextInt(1000) + 128;
int count = Math.min(random.nextInt(10) + 1, sizeRemaining);
sizeRemaining -= count;
hashMultiset.add(value, count);
linkedHashMultiset.add(value, count);
treeMultiset.add(value, count);
}
//TODO(kevinb): convert to assert once benchmark tests enable asserts by default
Preconditions.checkState(hashMultiset.size() == size);
}
@Benchmark int hashMultiset(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : hashMultiset) {
sum += value.hashCode();
}
}
return sum;
}
@Benchmark int linkedHashMultiset(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : linkedHashMultiset) {
sum += value.hashCode();
}
}
return sum;
}
@Benchmark int treeMultiset(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : treeMultiset) {
sum += value.hashCode();
}
}
return sum;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.List;
/**
* Benchmark for various ways to create an {@code ImmutableList}.
*
* @author Louis Wasserman
*/
public class ImmutableListCreationBenchmark {
@Param({"10", "1000", "1000000"})
int size;
private static final Object OBJECT = new Object();
@Benchmark int builderAdd(int reps) {
int size = this.size;
int dummy = 0;
for (int rep = 0; rep < reps; rep++) {
ImmutableList.Builder<Object> builder = ImmutableList.builder();
for (int i = 0; i < size; i++) {
builder.add(OBJECT);
}
dummy += builder.build().size();
}
return dummy;
}
@Benchmark int preSizedBuilderAdd(int reps) {
int size = this.size;
int dummy = 0;
for (int rep = 0; rep < reps; rep++) {
ImmutableList.Builder<Object> builder = new ImmutableList.Builder<Object>(size);
for (int i = 0; i < size; i++) {
builder.add(OBJECT);
}
dummy += builder.build().size();
}
return dummy;
}
@Benchmark int copyArrayList(int reps) {
int size = this.size;
int dummy = 0;
for (int rep = 0; rep < reps; rep++) {
List<Object> builder = Lists.newArrayList();
for (int i = 0; i < size; i++) {
builder.add(OBJECT);
}
dummy += ImmutableList.copyOf(builder).size();
}
return dummy;
}
@Benchmark int copyPreSizedArrayList(int reps) {
int size = this.size;
int tmp = 0;
for (int rep = 0; rep < reps; rep++) {
List<Object> builder = Lists.newArrayListWithCapacity(size);
for (int i = 0; i < size; i++) {
builder.add(OBJECT);
}
tmp += ImmutableList.copyOf(builder).size();
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.collect.BenchmarkHelpers.SetImpl;
import com.google.common.collect.CollectionBenchmarkSampleData.Element;
import java.util.Set;
/**
* Test iteration speed at various size for {@link Set} instances.
*
* @author Christopher Swenson
*/
public class SetIterationBenchmark {
@Param({ "3", "6", "11", "23", "45", "91", "181", "362", "724", "1448",
"2896", "5793", "11585", "23170", "46341", "92682", "185364", "370728",
"741455", "1482910", "2965821", "5931642"})
private int size;
// "" means no fixed seed
@Param("1234")
private SpecialRandom random;
@Param({"Immutable", "Hash"})
private SetImpl impl;
// the following must be set during setUp
private Set<Element> setToTest;
@BeforeExperiment void setUp() {
CollectionBenchmarkSampleData sampleData =
new CollectionBenchmarkSampleData(true, random, 0.8, size);
setToTest = impl.create(sampleData.getValuesInSet());
}
@Benchmark int iteration(int reps) {
int x = 0;
for (int i = 0; i < reps; i++) {
for (Element y : setToTest) {
x ^= System.identityHashCode(y);
}
}
return x;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.collect.BenchmarkHelpers.SetImpl;
import com.google.common.collect.CollectionBenchmarkSampleData.Element;
import java.util.Set;
/**
* A microbenchmark that tests the performance of contains() on various Set
* implementations.
*
* @author Kevin Bourrillion
*/
public class SetContainsBenchmark {
// Start at 4.88 then multiply by 2*2^phi <evil cackle> - The goal is be uniform
// yet visit a variety of "values-relative-to-the-next-power-of-2"
@Param({"5", "30", "180", "1100", "6900", "43000", "260000"}) // "1600000", "9800000"
private int size;
// TODO(kevinb): look at exact (==) hits vs. equals() hits?
@Param({"0.2", "0.8"})
private double hitRate;
@Param("true")
private boolean isUserTypeFast;
// "" means no fixed seed
@Param("")
private SpecialRandom random;
@Param({"Hash", "Immutable"})
private SetImpl impl;
// the following must be set during setUp
private Element[] queries;
private Set<Element> setToTest;
@BeforeExperiment void setUp() {
CollectionBenchmarkSampleData sampleData =
new CollectionBenchmarkSampleData(
isUserTypeFast, random, hitRate, size);
this.setToTest = impl.create(sampleData.getValuesInSet());
this.queries = sampleData.getQueries();
}
@Benchmark boolean contains(int reps) {
// Paranoia: acting on hearsay that accessing fields might be slow
// Should write a benchmark to test that!
Set<Element> set = setToTest;
Element[] queries = this.queries;
int mask = queries.length - 1;
boolean dummy = false;
for (int i = 0; i < reps; i++) {
dummy ^= set.contains(queries[i & mask]);
}
return dummy;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.AfterExperiment;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.base.Function;
import com.google.common.collect.MapMaker;
import com.google.common.primitives.Ints;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
/**
* Simple single-threaded benchmark for a computing map with maximum size.
*
* @author Charles Fry
*/
public class MapMakerSingleThreadBenchmark {
@Param({"1000", "2000"}) int maximumSize;
@Param("5000") int distinctKeys;
@Param("4") int segments;
// 1 means uniform likelihood of keys; higher means some keys are more popular
// tweak this to control hit rate
@Param("2.5") double concentration;
Random random = new Random();
Map<Integer, Integer> cache;
int max;
static AtomicLong requests = new AtomicLong(0);
static AtomicLong misses = new AtomicLong(0);
@BeforeExperiment void setUp() {
// random integers will be generated in this range, then raised to the
// power of (1/concentration) and floor()ed
max = Ints.checkedCast((long) Math.pow(distinctKeys, concentration));
cache = new MapMaker()
.concurrencyLevel(segments)
.maximumSize(maximumSize)
.makeComputingMap(
new Function<Integer, Integer>() {
@Override public Integer apply(Integer from) {
return (int) misses.incrementAndGet();
}
});
// To start, fill up the cache.
// Each miss both increments the counter and causes the map to grow by one,
// so until evictions begin, the size of the map is the greatest return
// value seen so far
while (cache.get(nextRandomKey()) < maximumSize) {}
requests.set(0);
misses.set(0);
}
@Benchmark int time(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += cache.get(nextRandomKey());
}
requests.addAndGet(reps);
return dummy;
}
private int nextRandomKey() {
int a = random.nextInt(max);
/*
* For example, if concentration=2.0, the following takes the square root of
* the uniformly-distributed random integer, then truncates any fractional
* part, so higher integers would appear (in this case linearly) more often
* than lower ones.
*/
return (int) Math.pow(a, 1.0 / concentration);
}
@AfterExperiment void tearDown() {
double req = requests.get();
double hit = req - misses.get();
// Currently, this is going into /dev/null, but I'll fix that
System.out.println("hit rate: " + hit / req);
}
// for proper distributions later:
// import JSci.maths.statistics.ProbabilityDistribution;
// int key = (int) dist.inverse(random.nextDouble());
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Benchmark for HashMultiset.add for an already-present element.
*
* @author Louis Wasserman
*/
public class HashMultisetAddPresentBenchmark {
private static final int ARRAY_MASK = 0x0ffff;
private static final int ARRAY_SIZE = 0x10000;
List<Multiset<Integer>> multisets = new ArrayList<Multiset<Integer>>(0x10000);
int[] queries = new int[ARRAY_SIZE];
@BeforeExperiment
void setUp() {
Random random = new Random();
multisets.clear();
for (int i = 0; i < ARRAY_SIZE; i++) {
HashMultiset<Integer> multiset = HashMultiset.<Integer>create();
multisets.add(multiset);
queries[i] = random.nextInt();
multiset.add(queries[i]);
}
}
@Benchmark int add(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += multisets.get(j).add(queries[j], 4);
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.collect.DiscreteDomain.integers;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.Set;
/**
* Very simple powerSet iteration benchmark.
*
* @author Kevin Bourrillion
*/
public class PowerSetBenchmark {
@Param({"2", "4", "8", "16"}) int elements;
Set<Set<Integer>> powerSet;
@BeforeExperiment void setUp() {
Set<Integer> set = ContiguousSet.create(Range.closed(1, elements), integers());
powerSet = Sets.powerSet(set);
}
@Benchmark int iteration(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Set<Integer> subset : powerSet) {
for (Integer value : subset) {
sum += value;
}
}
}
return sum;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.collect.CollectionBenchmarkSampleData.Element;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
/**
* A microbenchmark that tests the performance of get() on various map
* implementations. Forked from {@link SetContainsBenchmark}.
*
* @author Nicholaus Shupe
*/
public class MapBenchmark {
@Param({"Hash", "LinkedHM", "MapMaker1", "Immutable"})
private Impl impl;
public enum Impl {
Hash {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = Maps.newHashMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
LinkedHM {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = Maps.newLinkedHashMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
UnmodHM {
@Override Map<Element, Element> create(Collection<Element> keys) {
return Collections.unmodifiableMap(Hash.create(keys));
}
},
SyncHM {
@Override Map<Element, Element> create(Collection<Element> keys) {
return Collections.synchronizedMap(Hash.create(keys));
}
},
Tree {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = Maps.newTreeMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
SkipList {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = new ConcurrentSkipListMap<Element, Element>();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
ConcurrentHM1 {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map =
new ConcurrentHashMap<Element, Element>(keys.size(), 0.75f, 1);
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
ConcurrentHM16 {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map =
new ConcurrentHashMap<Element, Element>(keys.size(), 0.75f, 16);
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
MapMaker1 {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = new MapMaker()
.concurrencyLevel(1)
.makeMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
MapMaker16 {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = new MapMaker()
.concurrencyLevel(16)
.makeMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
Immutable {
@Override Map<Element, Element> create(Collection<Element> keys) {
ImmutableMap.Builder<Element, Element> builder = ImmutableMap.builder();
for (Element element : keys) {
builder.put(element, element);
}
return builder.build();
}
},
ImmutableSorted {
@Override Map<Element, Element> create(Collection<Element> keys) {
ImmutableSortedMap.Builder<Element, Element> builder =
ImmutableSortedMap.naturalOrder();
for (Element element : keys) {
builder.put(element, element);
}
return builder.build();
}
};
abstract Map<Element, Element> create(Collection<Element> contents);
}
@Param({"5", "50", "500", "5000", "50000"})
private int size;
// TODO: look at exact (==) hits vs. equals() hits?
@Param("0.9")
private double hitRate;
@Param("true")
private boolean isUserTypeFast;
// "" means no fixed seed
@Param("")
private SpecialRandom random;
@Param("false")
private boolean sortedData;
// the following must be set during setUp
private Element[] queries;
private Map<Element, Element> mapToTest;
private Collection<Element> values;
@BeforeExperiment void setUp() {
CollectionBenchmarkSampleData sampleData =
new CollectionBenchmarkSampleData(
isUserTypeFast, random, hitRate, size);
if (sortedData) {
List<Element> valueList = Lists.newArrayList(sampleData.getValuesInSet());
Collections.sort(valueList);
values = valueList;
} else {
values = sampleData.getValuesInSet();
}
this.mapToTest = impl.create(values);
this.queries = sampleData.getQueries();
}
@Benchmark boolean get(int reps) {
// Paranoia: acting on hearsay that accessing fields might be slow
// Should write a benchmark to test that!
Map<Element, Element> map = mapToTest;
Element[] queries = this.queries;
// Allows us to use & instead of %, acting on hearsay that division
// operators (/%) are disproportionately expensive; should test this too!
int mask = queries.length - 1;
boolean dummy = false;
for (int i = 0; i < reps; i++) {
dummy ^= map.get(queries[i & mask]) != null;
}
return dummy;
}
@Benchmark int createAndPopulate(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += impl.create(values).size();
}
return dummy;
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
/**
* A benchmark to determine the overhead of sorting with {@link Ordering#from(Comparator)}, or with
* {@link Ordering#natural()}, as opposed to using the inlined {@link Arrays#sort(Object[])}
* implementation, which uses {@link Comparable#compareTo} directly.
*
* @author Louis Wasserman
*/
public class SortedCopyBenchmark {
private final Integer[][] inputArrays = new Integer[0x100][];
@Param({"10000"})
int n;
@BeforeExperiment
void setUp() throws Exception {
Random rng = new Random();
for (int i = 0; i < 0x100; i++) {
Integer[] array = new Integer[n];
for (int j = 0; j < n; j++) {
array[j] = rng.nextInt();
}
inputArrays[i] = array;
}
}
@Benchmark int arraysSortNoComparator(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
Integer[] copy = inputArrays[i & 0xFF].clone();
Arrays.sort(copy);
tmp += copy[0];
}
return tmp;
}
@Benchmark int arraysSortOrderingNatural(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
Integer[] copy = inputArrays[i & 0xFF].clone();
Arrays.sort(copy, Ordering.natural());
tmp += copy[0];
}
return tmp;
}
private static final Comparator<Integer> NATURAL_INTEGER = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
@Benchmark int arraysSortOrderingFromNatural(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
Integer[] copy = inputArrays[i & 0xFF].clone();
Arrays.sort(copy, Ordering.from(NATURAL_INTEGER));
tmp += copy[0];
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.base.Function;
import com.google.common.collect.ForwardingQueue;
import com.google.common.collect.MinMaxPriorityQueue;
import com.google.common.collect.Ordering;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
/**
* Benchmarks to compare performance of MinMaxPriorityQueue and PriorityQueue.
*
* @author Sverre Sundsdal
*/
public class MinMaxPriorityQueueBenchmark {
@Param private ComparatorType comparator;
// TODO(kevinb): add 1000000 back when we have the ability to throw
// NotApplicableException in the expensive comparator case.
@Param({"100", "10000"}) private int size;
@Param private HeapType heap;
private Queue<Integer> queue;
private final Random random = new Random();
@BeforeExperiment void setUp() {
queue = heap.create(comparator.get());
for (int i = 0; i < size; i++) {
queue.add(random.nextInt());
}
}
@Benchmark void pollAndAdd(int reps) {
for (int i = 0; i < reps; i++) {
// TODO(kevinb): precompute random #s?
queue.add(queue.poll() ^ random.nextInt());
}
}
@Benchmark void populate(int reps) {
for (int i = 0; i < reps; i++) {
queue.clear();
for (int j = 0; j < size; j++) {
// TODO(kevinb): precompute random #s?
queue.add(random.nextInt());
}
}
}
/**
* Implementation of the InvertedMinMaxPriorityQueue which forwards all calls to
* a MinMaxPriorityQueue, except poll, which is forwarded to pollMax. That way
* we can benchmark pollMax using the same code that benchmarks poll.
*/
static final class InvertedMinMaxPriorityQueue <T> extends ForwardingQueue<T> {
MinMaxPriorityQueue<T> mmHeap;
public InvertedMinMaxPriorityQueue(Comparator<T> comparator) {
mmHeap = MinMaxPriorityQueue.orderedBy(comparator).create();
}
@Override
protected Queue<T> delegate() {
return mmHeap;
}
@Override
public T poll() {
return mmHeap.pollLast();
}
}
public enum HeapType {
MIN_MAX {
@Override public Queue<Integer> create(Comparator<Integer> comparator) {
return MinMaxPriorityQueue.orderedBy(comparator).create();
}
},
PRIORITY_QUEUE {
@Override public Queue<Integer> create(Comparator<Integer> comparator) {
return new PriorityQueue<Integer>(11, comparator);
}
},
INVERTED_MIN_MAX {
@Override public Queue<Integer> create(Comparator<Integer> comparator) {
return new InvertedMinMaxPriorityQueue<Integer>(comparator);
}
};
public abstract Queue<Integer> create(Comparator<Integer> comparator);
}
/**
* Does a CPU intensive operation on Integer and returns a BigInteger
* Used to implement an ordering that spends a lot of cpu.
*/
static class ExpensiveComputation implements Function<Integer, BigInteger> {
@Override
public BigInteger apply(Integer from) {
BigInteger v = BigInteger.valueOf(from);
// Math.sin is very slow for values outside 4*pi
// Need to take absolute value to avoid inverting the value.
for (double i = 0; i < 100; i += 20) {
v = v.add(v.multiply(
BigInteger.valueOf(
((Double) Math.abs(Math.sin(i) * 10.0)).longValue())));
}
return v;
}
}
public enum ComparatorType {
CHEAP {
@Override public Comparator<Integer> get() {
return Ordering.natural();
}
},
EXPENSIVE {
@Override public Comparator<Integer> get() {
return Ordering.natural().onResultOf(new ExpensiveComputation());
}
};
public abstract Comparator<Integer> get();
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.collect.BenchmarkHelpers.SetImpl;
/**
* This is meant to be used with {@code --measureMemory} to measure the memory
* usage of various {@code Set} implementations.
*
* @author Christopher Swenson
*/
public class SetCreationBenchmark {
@Param({ "3", "6", "11", "23", "45", "91", "181", "362", "724", "1448",
"2896", "5793", "11585", "23170", "46341", "92682", "185364", "370728",
"741455", "1482910", "2965821", "5931642"})
private int size;
// "" means no fixed seed
@Param("1234")
private SpecialRandom random;
@Param({"Immutable", "Hash"})
private SetImpl impl;
// the following must be set during setUp
private CollectionBenchmarkSampleData sampleData;
@BeforeExperiment void setUp() {
sampleData = new CollectionBenchmarkSampleData(true, random, 0.8, size);
}
@Benchmark int creation(int reps) {
int x = 0;
for (int i = 0; i < reps; i++) {
x ^= System.identityHashCode(impl.create(sampleData.getValuesInSet()));
}
return x;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.base.Optional;
import com.google.common.primitives.Ints;
import java.util.List;
import java.util.Random;
/**
* Benchmarks for the {@code TreeTraverser} and optimized {@code BinaryTreeTraverser} operations on
* binary trees.
*
* @author Louis Wasserman
*/
public class BinaryTreeTraverserBenchmark {
private static class BinaryNode {
final int x;
final Optional<BinaryNode> left;
final Optional<BinaryNode> right;
BinaryNode(int x, Optional<BinaryNode> left, Optional<BinaryNode> right) {
this.x = x;
this.left = left;
this.right = right;
}
}
enum Topology {
BALANCED {
@Override
Optional<BinaryNode> createTree(int size, Random rng) {
if (size == 0) {
return Optional.absent();
} else {
int leftChildSize = (size - 1) / 2;
int rightChildSize = size - 1 - leftChildSize;
return Optional.of(new BinaryNode(
rng.nextInt(), createTree(leftChildSize, rng), createTree(rightChildSize, rng)));
}
}
},
ALL_LEFT {
@Override
Optional<BinaryNode> createTree(int size, Random rng) {
Optional<BinaryNode> root = Optional.absent();
for (int i = 0; i < size; i++) {
root = Optional.of(new BinaryNode(rng.nextInt(), root, Optional.<BinaryNode>absent()));
}
return root;
}
},
ALL_RIGHT {
@Override
Optional<BinaryNode> createTree(int size, Random rng) {
Optional<BinaryNode> root = Optional.absent();
for (int i = 0; i < size; i++) {
root = Optional.of(new BinaryNode(rng.nextInt(), Optional.<BinaryNode>absent(), root));
}
return root;
}
},
RANDOM {
/**
* Generates a tree with topology selected uniformly at random from the topologies of binary
* trees of the specified size.
*/
@Override
Optional<BinaryNode> createTree(int size, Random rng) {
int[] keys = new int[size];
for (int i = 0; i < size; i++) {
keys[i] = rng.nextInt();
}
return createTreap(Ints.asList(keys));
}
// See http://en.wikipedia.org/wiki/Treap for details on the algorithm.
private Optional<BinaryNode> createTreap(List<Integer> keys) {
if (keys.isEmpty()) {
return Optional.absent();
}
int minIndex = 0;
for (int i = 1; i < keys.size(); i++) {
if (keys.get(i) < keys.get(minIndex)) {
minIndex = i;
}
}
Optional<BinaryNode> leftChild = createTreap(keys.subList(0, minIndex));
Optional<BinaryNode> rightChild = createTreap(keys.subList(minIndex + 1, keys.size()));
return Optional.of(new BinaryNode(keys.get(minIndex), leftChild, rightChild));
}
};
abstract Optional<BinaryNode> createTree(int size, Random rng);
}
private static final BinaryTreeTraverser<BinaryNode> BINARY_VIEWER =
new BinaryTreeTraverser<BinaryNode>() {
@Override
public Optional<BinaryNode> leftChild(BinaryNode node) {
return node.left;
}
@Override
public Optional<BinaryNode> rightChild(BinaryNode node) {
return node.right;
}
};
private static final TreeTraverser<BinaryNode> VIEWER = new TreeTraverser<BinaryNode>() {
@Override
public Iterable<BinaryNode> children(BinaryNode root) {
return BINARY_VIEWER.children(root);
}
};
enum Traversal {
PRE_ORDER {
@Override
<T> Iterable<T> view(T root, TreeTraverser<T> viewer) {
return viewer.preOrderTraversal(root);
}
},
POST_ORDER {
@Override
<T> Iterable<T> view(T root, TreeTraverser<T> viewer) {
return viewer.postOrderTraversal(root);
}
},
BREADTH_FIRST {
@Override
<T> Iterable<T> view(T root, TreeTraverser<T> viewer) {
return viewer.breadthFirstTraversal(root);
}
};
abstract <T> Iterable<T> view(T root, TreeTraverser<T> viewer);
}
private Iterable<BinaryNode> view;
@Param
Topology topology;
@Param({"1", "100", "10000", "1000000"})
int size;
@Param
Traversal traversal;
@Param
boolean useBinaryTraverser;
@Param({"1234"})
SpecialRandom rng;
@BeforeExperiment
void setUp() {
this.view = traversal.view(
topology.createTree(size, rng).get(),
useBinaryTraverser ? BINARY_VIEWER : VIEWER);
}
@Benchmark int traversal(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
for (BinaryNode node : view) {
tmp += node.x;
}
}
return tmp;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* Tests the speed of iteration of different iteration methods for collections.
*
* @author David Richter
*/
public class IteratorBenchmark {
@Param({"0", "1", "16", "256", "4096", "65536"}) int size;
// use concrete classes to remove any possible polymorphic overhead?
Object[] array;
ArrayList<Object> arrayList;
LinkedList<Object> linkedList;
@BeforeExperiment void setUp() {
array = new Object[size];
arrayList = Lists.newArrayListWithCapacity(size);
linkedList = Lists.newLinkedList();
for (int i = 0; i < size; i++) {
Object value = new Object();
array[i] = value;
arrayList.add(value);
linkedList.add(value);
}
}
@Benchmark int arrayIndexed(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (int index = 0; index < size; index++) {
sum += array[index].hashCode();
}
}
return sum;
}
@Benchmark int arrayIndexedLength(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (int index = 0; index < array.length; index++) {
sum += array[index].hashCode();
}
}
return sum;
}
@Benchmark int arrayFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : array) {
sum += value.hashCode();
}
}
return sum;
}
@Benchmark int arrayListIndexed(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (int index = 0; index < size; index++) {
sum += arrayList.get(index).hashCode();
}
}
return sum;
}
@Benchmark int arrayListIndexedLength(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (int index = 0; index < arrayList.size(); index++) {
sum += arrayList.get(index).hashCode();
}
}
return sum;
}
@Benchmark int arrayListFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : arrayList) {
sum += value.hashCode();
}
}
return sum;
}
@Benchmark int arrayListToArrayFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : arrayList.toArray()) {
sum += value.hashCode();
}
}
return sum;
}
@Benchmark int linkedListFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : linkedList) {
sum += value.hashCode();
}
}
return sum;
}
@Benchmark int linkedListToArrayFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : linkedList.toArray()) {
sum += value.hashCode();
}
}
return sum;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.hash;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.hash.HashFunction;
import java.util.Random;
/**
* Benchmarks for comparing the various {@link HashFunction functions} that we provide.
*
* <p>Parameters for the benchmark are:
* <ul>
* <li>size: The length of the byte array to hash.
* <li>hashFunctionEnum: The {@link HashFunction} to use for hashing.
* </ul>
*
* @author Kurt Alfred Kluever
*/
public class HashFunctionBenchmark {
// Use a statically configured random instance for all of the benchmarks
private static final Random random = new Random(42);
@Param({"10", "1000", "100000", "1000000"})
private int size;
@Param HashFunctionEnum hashFunctionEnum;
private byte[] testBytes;
@BeforeExperiment void setUp() {
testBytes = new byte[size];
random.nextBytes(testBytes);
}
@Benchmark int hashFunction(int reps) {
HashFunction hashFunction = hashFunctionEnum.getHashFunction();
int result = 37;
for (int i = 0; i < reps; i++) {
result ^= hashFunction.hashBytes(testBytes).asBytes()[0];
}
return result;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.hash;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
/**
* Benchmarks for comparing {@link MessageDigest}s and {@link HashFunction}s that wrap
* {@link MessageDigest}s.
*
* <p>Parameters for the benchmark are:
* <ul>
* <li>size: The length of the byte array to hash.
* <li>algorithm: the algorithm to hash with (e.g. MD5, SHA1, etc.).
* <li>hashMethod: how to hash the data (using the Hashing API or the MessageDigest API).
* </ul>
*
* @author Kurt Alfred Kluever
*/
public class MessageDigestAlgorithmBenchmark {
@Param({"10", "1000", "100000", "1000000"}) int size;
@Param Algorithm algorithm;
@Param HashMethod hashMethod;
private enum HashMethod {
MESSAGE_DIGEST_API() {
@Override public byte[] hash(Algorithm algorithm, byte[] input) {
MessageDigest md = algorithm.getMessageDigest();
md.update(input);
return md.digest();
}
},
HASH_FUNCTION_API() {
@Override public byte[] hash(Algorithm algorithm, byte[] input) {
return algorithm.getHashFunction().hashBytes(input).asBytes();
}
};
public abstract byte[] hash(Algorithm algorithm, byte[] input);
}
private enum Algorithm {
MD5("MD5", Hashing.md5()),
SHA_1("SHA-1", Hashing.sha1()),
SHA_256("SHA-256", Hashing.sha256()),
SHA_512("SHA-512", Hashing.sha512());
private final String algorithmName;
private final HashFunction hashFn;
Algorithm(String algorithmName, HashFunction hashFn) {
this.algorithmName = algorithmName;
this.hashFn = hashFn;
}
public MessageDigest getMessageDigest() {
try {
return MessageDigest.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public HashFunction getHashFunction() {
return hashFn;
}
}
// Use a constant seed for all of the benchmarks to ensure apples to apples comparisons.
private static final int RANDOM_SEED = new Random().nextInt();
private byte[] testBytes;
@BeforeExperiment void setUp() {
testBytes = new byte[size];
new Random(RANDOM_SEED).nextBytes(testBytes);
}
@Benchmark byte hashing(int reps) {
byte result = 0x01;
HashMethod hashMethod = this.hashMethod;
Algorithm algorithm = this.algorithm;
for (int i = 0; i < reps; i++) {
result ^= hashMethod.hash(algorithm, testBytes)[0];
}
return result;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.hash;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.security.MessageDigest;
/**
* Benchmarks for comparing instance creation of {@link MessageDigest}s.
*
* @author Kurt Alfred Kluever
*/
public class MessageDigestCreationBenchmark {
@Param({"MD5", "SHA-1", "SHA-256", "SHA-512"})
private String algorithm;
private MessageDigest md;
@BeforeExperiment void setUp() throws Exception {
md = MessageDigest.getInstance(algorithm);
}
@Benchmark int getInstance(int reps) throws Exception {
int retValue = 0;
for (int i = 0; i < reps; i++) {
retValue ^= MessageDigest.getInstance(algorithm).getDigestLength();
}
return retValue;
}
@Benchmark int clone(int reps) throws Exception {
int retValue = 0;
for (int i = 0; i < reps; i++) {
retValue ^= ((MessageDigest) md.clone()).getDigestLength();
}
return retValue;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.hash;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.Random;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
/**
* Benchmarks for comparing {@link Checksum}s and {@link HashFunction}s that wrap {@link Checksum}s.
*
* <p>Parameters for the benchmark are: <ul> <li>size: The length of the byte array to hash. </ul>
*
* @author Colin Decker
*/
public class ChecksumBenchmark {
// Use a constant seed for all of the benchmarks to ensure apples to apples comparisons.
private static final int RANDOM_SEED = new Random().nextInt();
@Param({"10", "1000", "100000", "1000000"})
private int size;
private byte[] testBytes;
@BeforeExperiment
void setUp() {
testBytes = new byte[size];
new Random(RANDOM_SEED).nextBytes(testBytes);
}
// CRC32
@Benchmark byte crc32HashFunction(int reps) {
return runHashFunction(reps, Hashing.crc32());
}
@Benchmark byte crc32Checksum(int reps) throws Exception {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
CRC32 checksum = new CRC32();
checksum.update(testBytes);
result ^= checksum.getValue();
}
return result;
}
// Adler32
@Benchmark byte adler32HashFunction(int reps) {
return runHashFunction(reps, Hashing.adler32());
}
@Benchmark byte adler32Checksum(int reps) throws Exception {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
Adler32 checksum = new Adler32();
checksum.update(testBytes);
result ^= checksum.getValue();
}
return result;
}
// Helpers + main
private byte runHashFunction(int reps, HashFunction hashFunction) {
byte result = 0x01;
// Trick the JVM to prevent it from using the hash function non-polymorphically
result ^= Hashing.crc32().hashInt(reps).asBytes()[0];
result ^= Hashing.adler32().hashInt(reps).asBytes()[0];
for (int i = 0; i < reps; i++) {
result ^= hashFunction.hashBytes(testBytes).asBytes()[0];
}
return result;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.lang.reflect.Constructor;
import java.util.concurrent.BlockingQueue;
/**
* Benchmarks for {@link Monitor}.
*
* @author Justin T. Sampson
*/
public class MonitorBenchmark {
@Param({"10", "100", "1000"}) int capacity;
@Param({"Array", "Priority"}) String queueType;
@Param boolean useMonitor;
private BlockingQueue<String> queue;
private String[] strings;
@BeforeExperiment
@SuppressWarnings("unchecked")
void setUp() throws Exception {
String prefix =
(useMonitor ? "com.google.common.util.concurrent.MonitorBased" : "java.util.concurrent.");
String className = prefix + queueType + "BlockingQueue";
Constructor<?> constructor = Class.forName(className).getConstructor(int.class);
queue = (BlockingQueue<String>) constructor.newInstance(capacity);
strings = new String[capacity];
for (int i = 0; i < capacity; i++) {
strings[i] = String.valueOf(Math.random());
}
}
@Benchmark void addsAndRemoves(int reps) {
int capacity = this.capacity;
BlockingQueue<String> queue = this.queue;
String[] strings = this.strings;
for (int i = 0; i < reps; i++) {
for (int j = 0; j < capacity; j++) {
queue.add(strings[j]);
}
for (int j = 0; j < capacity; j++) {
queue.remove();
}
}
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.SortedSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* An unbounded {@linkplain BlockingQueue blocking queue} that uses
* the same ordering rules as class {@link PriorityQueue} and supplies
* blocking retrieval operations. While this queue is logically
* unbounded, attempted additions may fail due to resource exhaustion
* (causing <tt>OutOfMemoryError</tt>). This class does not permit
* <tt>null</tt> elements. A priority queue relying on {@linkplain
* Comparable natural ordering} also does not permit insertion of
* non-comparable objects (doing so results in
* <tt>ClassCastException</tt>).
*
* <p>This class and its iterator implement all of the
* <em>optional</em> methods of the {@link Collection} and {@link
* Iterator} interfaces. The Iterator provided in method {@link
* #iterator()} is <em>not</em> guaranteed to traverse the elements of
* the MonitorBasedPriorityBlockingQueue in any particular order. If you need
* ordered traversal, consider using
* <tt>Arrays.sort(pq.toArray())</tt>. Also, method <tt>drainTo</tt>
* can be used to <em>remove</em> some or all elements in priority
* order and place them in another collection.
*
* <p>Operations on this class make no guarantees about the ordering
* of elements with equal priority. If you need to enforce an
* ordering, you can define custom classes or comparators that use a
* secondary key to break ties in primary priority values. For
* example, here is a class that applies first-in-first-out
* tie-breaking to comparable elements. To use it, you would insert a
* <tt>new FIFOEntry(anEntry)</tt> instead of a plain entry object.
*
* <pre>
* class FIFOEntry<E extends Comparable<? super E>>
* implements Comparable<FIFOEntry<E>> {
* final static AtomicLong seq = new AtomicLong();
* final long seqNum;
* final E entry;
* public FIFOEntry(E entry) {
* seqNum = seq.getAndIncrement();
* this.entry = entry;
* }
* public E getEntry() { return entry; }
* public int compareTo(FIFOEntry<E> other) {
* int res = entry.compareTo(other.entry);
* if (res == 0 && other.entry != this.entry)
* res = (seqNum < other.seqNum ? -1 : 1);
* return res;
* }
* }</pre>
*
* @author Doug Lea
* @author Justin T. Sampson
* @param <E> the type of elements held in this collection
*/
public class MonitorBasedPriorityBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E> {
// Based on revision 1.55 of PriorityBlockingQueue by Doug Lea, from
// http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/
private static final long serialVersionUID = 5595510919245408276L;
final PriorityQueue<E> q;
final Monitor monitor = new Monitor(true);
private final Monitor.Guard notEmpty =
new Monitor.Guard(monitor) {
@Override public boolean isSatisfied() {
return !q.isEmpty();
}
};
/**
* Creates a <tt>MonitorBasedPriorityBlockingQueue</tt> with the default
* initial capacity (11) that orders its elements according to
* their {@linkplain Comparable natural ordering}.
*/
public MonitorBasedPriorityBlockingQueue() {
q = new PriorityQueue<E>();
}
/**
* Creates a <tt>MonitorBasedPriorityBlockingQueue</tt> with the specified
* initial capacity that orders its elements according to their
* {@linkplain Comparable natural ordering}.
*
* @param initialCapacity the initial capacity for this priority queue
* @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
* than 1
*/
public MonitorBasedPriorityBlockingQueue(int initialCapacity) {
q = new PriorityQueue<E>(initialCapacity, null);
}
/**
* Creates a <tt>MonitorBasedPriorityBlockingQueue</tt> with the specified initial
* capacity that orders its elements according to the specified
* comparator.
*
* @param initialCapacity the initial capacity for this priority queue
* @param comparator the comparator that will be used to order this
* priority queue. If {@code null}, the {@linkplain Comparable
* natural ordering} of the elements will be used.
* @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
* than 1
*/
public MonitorBasedPriorityBlockingQueue(int initialCapacity,
@Nullable Comparator<? super E> comparator) {
q = new PriorityQueue<E>(initialCapacity, comparator);
}
/**
* Creates a <tt>MonitorBasedPriorityBlockingQueue</tt> containing the elements
* in the specified collection. If the specified collection is a
* {@link SortedSet} or a {@link PriorityQueue}, this
* priority queue will be ordered according to the same ordering.
* Otherwise, this priority queue will be ordered according to the
* {@linkplain Comparable natural ordering} of its elements.
*
* @param c the collection whose elements are to be placed
* into this priority queue
* @throws ClassCastException if elements of the specified collection
* cannot be compared to one another according to the priority
* queue's ordering
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
public MonitorBasedPriorityBlockingQueue(Collection<? extends E> c) {
q = new PriorityQueue<E>(c);
}
/**
* Inserts the specified element into this priority queue.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws ClassCastException if the specified element cannot be compared
* with elements currently in the priority queue according to the
* priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
@Override public boolean add(E e) {
return offer(e);
}
/**
* Inserts the specified element into this priority queue.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Queue#offer})
* @throws ClassCastException if the specified element cannot be compared
* with elements currently in the priority queue according to the
* priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
@Override
public boolean offer(E e) {
final Monitor monitor = this.monitor;
monitor.enter();
try {
boolean ok = q.offer(e);
if (!ok) {
throw new AssertionError();
}
return true;
} finally {
monitor.leave();
}
}
/**
* Inserts the specified element into this priority queue. As the queue is
* unbounded this method will never block.
*
* @param e the element to add
* @throws ClassCastException if the specified element cannot be compared
* with elements currently in the priority queue according to the
* priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
@Override
public void put(E e) {
offer(e); // never need to block
}
/**
* Inserts the specified element into this priority queue. As the queue is
* unbounded this method will never block.
*
* @param e the element to add
* @param timeout This parameter is ignored as the method never blocks
* @param unit This parameter is ignored as the method never blocks
* @return <tt>true</tt>
* @throws ClassCastException if the specified element cannot be compared
* with elements currently in the priority queue according to the
* priority queue's ordering
* @throws NullPointerException if the specified element is null
*/
@Override
public boolean offer(E e, long timeout, TimeUnit unit) {
checkNotNull(unit);
return offer(e); // never need to block
}
@Override
public E poll() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return q.poll();
} finally {
monitor.leave();
}
}
@Override
public E take() throws InterruptedException {
final Monitor monitor = this.monitor;
monitor.enterWhen(notEmpty);
try {
return q.poll();
} finally {
monitor.leave();
}
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
final Monitor monitor = this.monitor;
if (monitor.enterWhen(notEmpty, timeout, unit)) {
try {
return q.poll();
} finally {
monitor.leave();
}
} else {
return null;
}
}
@Override
public E peek() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return q.peek();
} finally {
monitor.leave();
}
}
/**
* Returns the comparator used to order the elements in this queue,
* or <tt>null</tt> if this queue uses the {@linkplain Comparable
* natural ordering} of its elements.
*
* @return the comparator used to order the elements in this queue,
* or <tt>null</tt> if this queue uses the natural
* ordering of its elements
*/
public Comparator<? super E> comparator() {
return q.comparator();
}
@Override public int size() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return q.size();
} finally {
monitor.leave();
}
}
/**
* Always returns <tt>Integer.MAX_VALUE</tt> because
* a <tt>MonitorBasedPriorityBlockingQueue</tt> is not capacity constrained.
* @return <tt>Integer.MAX_VALUE</tt>
*/
@Override
public int remainingCapacity() {
return Integer.MAX_VALUE;
}
/**
* Removes a single instance of the specified element from this queue,
* if it is present. More formally, removes an element {@code e} such
* that {@code o.equals(e)}, if this queue contains one or more such
* elements. Returns {@code true} if and only if this queue contained
* the specified element (or equivalently, if this queue changed as a
* result of the call).
*
* @param o element to be removed from this queue, if present
* @return <tt>true</tt> if this queue changed as a result of the call
*/
@Override public boolean remove(@Nullable Object o) {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return q.remove(o);
} finally {
monitor.leave();
}
}
/**
* Returns {@code true} if this queue contains the specified element.
* More formally, returns {@code true} if and only if this queue contains
* at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o object to be checked for containment in this queue
* @return <tt>true</tt> if this queue contains the specified element
*/
@Override public boolean contains(@Nullable Object o) {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return q.contains(o);
} finally {
monitor.leave();
}
}
/**
* Returns an array containing all of the elements in this queue.
* The returned array elements are in no particular order.
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this queue. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this queue
*/
@Override public Object[] toArray() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return q.toArray();
} finally {
monitor.leave();
}
}
@Override public String toString() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return q.toString();
} finally {
monitor.leave();
}
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
@Override
public int drainTo(Collection<? super E> c) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
final Monitor monitor = this.monitor;
monitor.enter();
try {
int n = 0;
E e;
while ( (e = q.poll()) != null) {
c.add(e);
++n;
}
return n;
} finally {
monitor.leave();
}
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
if (maxElements <= 0)
return 0;
final Monitor monitor = this.monitor;
monitor.enter();
try {
int n = 0;
E e;
while (n < maxElements && (e = q.poll()) != null) {
c.add(e);
++n;
}
return n;
} finally {
monitor.leave();
}
}
/**
* Atomically removes all of the elements from this queue.
* The queue will be empty after this call returns.
*/
@Override public void clear() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
q.clear();
} finally {
monitor.leave();
}
}
/**
* Returns an array containing all of the elements in this queue; the
* runtime type of the returned array is that of the specified array.
* The returned array elements are in no particular order.
* If the queue fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of this queue.
*
* <p>If this queue fits in the specified array with room to spare
* (i.e., the array has more elements than this queue), the element in
* the array immediately following the end of the queue is set to
* <tt>null</tt>.
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose <tt>x</tt> is a queue known to contain only strings.
* The following code can be used to dump the queue into a newly
* allocated array of <tt>String</tt>:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* <p>Note that <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>.
*
* @param a the array into which the elements of the queue are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose
* @return an array containing all of the elements in this queue
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this queue
* @throws NullPointerException if the specified array is null
*/
@Override public <T> T[] toArray(T[] a) {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return q.toArray(a);
} finally {
monitor.leave();
}
}
/**
* Returns an iterator over the elements in this queue. The
* iterator does not return the elements in any particular order.
* The returned <tt>Iterator</tt> is a "weakly consistent"
* iterator that will never throw {@link
* ConcurrentModificationException}, and guarantees to traverse
* elements as they existed upon construction of the iterator, and
* may (but is not guaranteed to) reflect any modifications
* subsequent to construction.
*
* @return an iterator over the elements in this queue
*/
@Override public Iterator<E> iterator() {
return new Itr(toArray());
}
/**
* Snapshot iterator that works off copy of underlying q array.
*/
private class Itr implements Iterator<E> {
final Object[] array; // Array of all elements
int cursor; // index of next element to return;
int lastRet; // index of last element, or -1 if no such
Itr(Object[] array) {
lastRet = -1;
this.array = array;
}
@Override
public boolean hasNext() {
return cursor < array.length;
}
@Override
public E next() {
if (cursor >= array.length)
throw new NoSuchElementException();
lastRet = cursor;
// array comes from q.toArray() and so should have only E's in it
@SuppressWarnings("unchecked")
E e = (E) array[cursor++];
return e;
}
@Override
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
Object x = array[lastRet];
lastRet = -1;
// Traverse underlying queue to find == element,
// not just a .equals element.
monitor.enter();
try {
for (Iterator<E> it = q.iterator(); it.hasNext(); ) {
if (it.next() == x) {
it.remove();
return;
}
}
} finally {
monitor.leave();
}
}
}
/**
* Saves the state to a stream (that is, serializes it). This
* merely wraps default serialization within the monitor. The
* serialization strategy for items is left to underlying
* Queue. Note that locking is not needed on deserialization, so
* readObject is not defined, just relying on default.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
monitor.enter();
try {
s.defaultWriteObject();
} finally {
monitor.leave();
}
}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.caliper.AfterExperiment;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import com.google.caliper.api.Footprint;
import com.google.caliper.api.VmOptions;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* Benchmarks for {@link ExecutionList}.
*/
@VmOptions({"-Xms3g", "-Xmx3g"})
public class ExecutionListBenchmark {
private static final int NUM_THREADS = 10; // make a param?
// We execute the listeners on the sameThreadExecutor because we don't really care about what the
// listeners are doing, and they aren't doing much.
private static final Executor SAME_THREAD_EXECUTOR = MoreExecutors.sameThreadExecutor();
// simple interface to wrap our two implementations.
interface ExecutionListWrapper {
void add(Runnable runnable, Executor executor);
void execute();
/** Returns the underlying implementation, useful for the Footprint benchmark. */
Object getImpl();
}
enum Impl {
NEW {
@Override ExecutionListWrapper newExecutionList() {
return new ExecutionListWrapper() {
final ExecutionList list = new ExecutionList();
@Override public void add(Runnable runnable, Executor executor) {
list.add(runnable, executor);
}
@Override public void execute() {
list.execute();
}
@Override public Object getImpl() {
return list;
}
};
}
},
NEW_WITH_CAS {
@Override ExecutionListWrapper newExecutionList() {
return new ExecutionListWrapper() {
final ExecutionListCAS list = new ExecutionListCAS();
@Override public void add(Runnable runnable, Executor executor) {
list.add(runnable, executor);
}
@Override public void execute() {
list.execute();
}
@Override public Object getImpl() {
return list;
}
};
}
},
NEW_WITH_QUEUE {
@Override ExecutionListWrapper newExecutionList() {
return new ExecutionListWrapper() {
final NewExecutionListQueue list = new NewExecutionListQueue();
@Override public void add(Runnable runnable, Executor executor) {
list.add(runnable, executor);
}
@Override public void execute() {
list.execute();
}
@Override public Object getImpl() {
return list;
}
};
}
},
NEW_WITHOUT_REVERSE {
@Override ExecutionListWrapper newExecutionList() {
return new ExecutionListWrapper() {
final NewExecutionListWithoutReverse list = new NewExecutionListWithoutReverse();
@Override public void add(Runnable runnable, Executor executor) {
list.add(runnable, executor);
}
@Override public void execute() {
list.execute();
}
@Override public Object getImpl() {
return list;
}
};
}
},
OLD {
@Override ExecutionListWrapper newExecutionList() {
return new ExecutionListWrapper() {
final OldExecutionList list = new OldExecutionList();
@Override public void add(Runnable runnable, Executor executor) {
list.add(runnable, executor);
}
@Override public void execute() {
list.execute();
}
@Override public Object getImpl() {
return list;
}
};
}
};
abstract ExecutionListWrapper newExecutionList();
}
private ExecutorService executorService;
private CountDownLatch listenerLatch;
private ExecutionListWrapper list;
@Param Impl impl;
@Param({"1", "5", "10"}) int numListeners;
private final Runnable listener = new Runnable() {
@Override public void run() {
listenerLatch.countDown();
}
};
@BeforeExperiment void setUp() throws Exception {
executorService = new ThreadPoolExecutor(NUM_THREADS,
NUM_THREADS,
Long.MAX_VALUE,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(1000));
final AtomicInteger integer = new AtomicInteger();
// Execute a bunch of tasks to ensure that our threads are allocated and hot
for (int i = 0; i < NUM_THREADS * 10; i++) {
executorService.submit(new Runnable() {
@Override public void run() {
integer.getAndIncrement();
}});
}
}
@AfterExperiment void tearDown() throws Exception {
executorService.shutdown();
}
@Footprint(exclude = {Runnable.class, Executor.class})
public Object measureSize() {
list = impl.newExecutionList();
for (int i = 0; i < numListeners; i++) {
list.add(listener, SAME_THREAD_EXECUTOR);
}
return list.getImpl();
}
@Benchmark int addThenExecute_singleThreaded(int reps) {
int returnValue = 0;
for (int i = 0; i < reps; i++) {
list = impl.newExecutionList();
listenerLatch = new CountDownLatch(numListeners);
for (int j = 0; j < numListeners; j++) {
list.add(listener, SAME_THREAD_EXECUTOR);
returnValue += listenerLatch.getCount();
}
list.execute();
returnValue += listenerLatch.getCount();
}
return returnValue;
}
@Benchmark int executeThenAdd_singleThreaded(int reps) {
int returnValue = 0;
for (int i = 0; i < reps; i++) {
list = impl.newExecutionList();
list.execute();
listenerLatch = new CountDownLatch(numListeners);
for (int j = 0; j < numListeners; j++) {
list.add(listener, SAME_THREAD_EXECUTOR);
returnValue += listenerLatch.getCount();
}
returnValue += listenerLatch.getCount();
}
return returnValue;
}
private final Runnable executeTask = new Runnable() {
@Override public void run() {
list.execute();
}
};
@Benchmark int addThenExecute_multiThreaded(final int reps) throws InterruptedException {
Runnable addTask = new Runnable() {
@Override public void run() {
for (int i = 0; i < numListeners; i++) {
list.add(listener, SAME_THREAD_EXECUTOR);
}
}
};
int returnValue = 0;
for (int i = 0; i < reps; i++) {
list = impl.newExecutionList();
listenerLatch = new CountDownLatch(numListeners * NUM_THREADS);
for (int j = 0; j < NUM_THREADS; j++) {
executorService.submit(addTask);
}
executorService.submit(executeTask);
returnValue = (int) listenerLatch.getCount();
listenerLatch.await();
}
return returnValue;
}
@Benchmark int executeThenAdd_multiThreaded(final int reps) throws InterruptedException {
Runnable addTask = new Runnable() {
@Override public void run() {
for (int i = 0; i < numListeners; i++) {
list.add(listener, SAME_THREAD_EXECUTOR);
}
}
};
int returnValue = 0;
for (int i = 0; i < reps; i++) {
list = impl.newExecutionList();
listenerLatch = new CountDownLatch(numListeners * NUM_THREADS);
executorService.submit(executeTask);
for (int j = 0; j < NUM_THREADS; j++) {
executorService.submit(addTask);
}
returnValue = (int) listenerLatch.getCount();
listenerLatch.await();
}
return returnValue;
}
// This is the old implementation of ExecutionList using a LinkedList.
private static final class OldExecutionList {
static final Logger log = Logger.getLogger(OldExecutionList.class.getName());
final Queue<OldExecutionList.RunnableExecutorPair> runnables = Lists.newLinkedList();
boolean executed = false;
public void add(Runnable runnable, Executor executor) {
Preconditions.checkNotNull(runnable, "Runnable was null.");
Preconditions.checkNotNull(executor, "Executor was null.");
boolean executeImmediate = false;
synchronized (runnables) {
if (!executed) {
runnables.add(new RunnableExecutorPair(runnable, executor));
} else {
executeImmediate = true;
}
}
if (executeImmediate) {
new RunnableExecutorPair(runnable, executor).execute();
}
}
public void execute() {
synchronized (runnables) {
if (executed) {
return;
}
executed = true;
}
while (!runnables.isEmpty()) {
runnables.poll().execute();
}
}
private static class RunnableExecutorPair {
final Runnable runnable;
final Executor executor;
RunnableExecutorPair(Runnable runnable, Executor executor) {
this.runnable = runnable;
this.executor = executor;
}
void execute() {
try {
executor.execute(runnable);
} catch (RuntimeException e) {
log.log(Level.SEVERE, "RuntimeException while executing runnable "
+ runnable + " with executor " + executor, e);
}
}
}
}
// A version of the execution list that doesn't reverse the stack in execute().
private static final class NewExecutionListWithoutReverse {
static final Logger log = Logger.getLogger(NewExecutionListWithoutReverse.class.getName());
@GuardedBy("this")
private RunnableExecutorPair runnables;
@GuardedBy("this")
private boolean executed;
public void add(Runnable runnable, Executor executor) {
Preconditions.checkNotNull(runnable, "Runnable was null.");
Preconditions.checkNotNull(executor, "Executor was null.");
synchronized (this) {
if (!executed) {
runnables = new RunnableExecutorPair(runnable, executor, runnables);
return;
}
}
executeListener(runnable, executor);
}
public void execute() {
RunnableExecutorPair list;
synchronized (this) {
if (executed) {
return;
}
executed = true;
list = runnables;
runnables = null; // allow GC to free listeners even if this stays around for a while.
}
while (list != null) {
executeListener(list.runnable, list.executor);
list = list.next;
}
}
private static void executeListener(Runnable runnable, Executor executor) {
try {
executor.execute(runnable);
} catch (RuntimeException e) {
log.log(Level.SEVERE, "RuntimeException while executing runnable "
+ runnable + " with executor " + executor, e);
}
}
private static final class RunnableExecutorPair {
final Runnable runnable;
final Executor executor;
@Nullable RunnableExecutorPair next;
RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) {
this.runnable = runnable;
this.executor = executor;
this.next = next;
}
}
}
// A version of the ExecutionList that uses an explicit tail pointer to keep the nodes in order
// rather than flipping the stack in execute().
private static final class NewExecutionListQueue {
static final Logger log = Logger.getLogger(NewExecutionListQueue.class.getName());
@GuardedBy("this")
private RunnableExecutorPair head;
@GuardedBy("this")
private RunnableExecutorPair tail;
@GuardedBy("this")
private boolean executed;
public void add(Runnable runnable, Executor executor) {
Preconditions.checkNotNull(runnable, "Runnable was null.");
Preconditions.checkNotNull(executor, "Executor was null.");
synchronized (this) {
if (!executed) {
RunnableExecutorPair newTail = new RunnableExecutorPair(runnable, executor);
if (head == null) {
head = newTail;
tail = newTail;
} else {
tail.next = newTail;
tail = newTail;
}
return;
}
}
executeListener(runnable, executor);
}
public void execute() {
RunnableExecutorPair list;
synchronized (this) {
if (executed) {
return;
}
executed = true;
list = head;
head = null; // allow GC to free listeners even if this stays around for a while.
tail = null;
}
while (list != null) {
executeListener(list.runnable, list.executor);
list = list.next;
}
}
private static void executeListener(Runnable runnable, Executor executor) {
try {
executor.execute(runnable);
} catch (RuntimeException e) {
log.log(Level.SEVERE, "RuntimeException while executing runnable "
+ runnable + " with executor " + executor, e);
}
}
private static final class RunnableExecutorPair {
Runnable runnable;
Executor executor;
@Nullable RunnableExecutorPair next;
RunnableExecutorPair(Runnable runnable, Executor executor) {
this.runnable = runnable;
this.executor = executor;
}
}
}
// A version of the list that uses compare and swap to manage the stack without locks.
private static final class ExecutionListCAS {
static final Logger log = Logger.getLogger(ExecutionListCAS.class.getName());
private static final sun.misc.Unsafe UNSAFE;
private static final long HEAD_OFFSET;
/**
* A special instance of {@link RunnableExecutorPair} that is used as a sentinel value for the
* bottom of the stack.
*/
private static final RunnableExecutorPair NULL_PAIR = new RunnableExecutorPair(null, null);
static {
try {
UNSAFE = getUnsafe();
HEAD_OFFSET = UNSAFE.objectFieldOffset(ExecutionListCAS.class.getDeclaredField("head"));
} catch (Exception ex) {
throw new Error(ex);
}
}
/**
* TODO(user): This was copied verbatim from Striped64.java... standardize this?
*/
private static sun.misc.Unsafe getUnsafe() {
try {
return sun.misc.Unsafe.getUnsafe();
} catch (SecurityException tryReflectionInstead) {}
try {
return java.security.AccessController.doPrivileged
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
@Override public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}});
} catch (java.security.PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics",
e.getCause());
}
}
private volatile RunnableExecutorPair head = NULL_PAIR;
public void add(Runnable runnable, Executor executor) {
Preconditions.checkNotNull(runnable, "Runnable was null.");
Preconditions.checkNotNull(executor, "Executor was null.");
RunnableExecutorPair newHead = new RunnableExecutorPair(runnable, executor);
RunnableExecutorPair oldHead;
do {
oldHead = head;
if (oldHead == null) {
// If runnables == null then execute() has been called so we should just execute our
// listener immediately.
newHead.execute();
return;
}
// Try to make newHead the new head of the stack at runnables.
newHead.next = oldHead;
} while(!UNSAFE.compareAndSwapObject(this, HEAD_OFFSET, oldHead, newHead));
}
public void execute() {
RunnableExecutorPair stack;
do {
stack = head;
if (stack == null) {
// If head == null then execute() has been called so we should just return
return;
}
// try to swap null into head.
} while(!UNSAFE.compareAndSwapObject(this, HEAD_OFFSET, stack, null));
RunnableExecutorPair reversedStack = null;
while (stack != NULL_PAIR) {
RunnableExecutorPair head = stack;
stack = stack.next;
head.next = reversedStack;
reversedStack = head;
}
stack = reversedStack;
while (stack != null) {
stack.execute();
stack = stack.next;
}
}
private static class RunnableExecutorPair {
final Runnable runnable;
final Executor executor;
// Volatile because this is written on one thread and read on another with no synchronization.
@Nullable volatile RunnableExecutorPair next;
RunnableExecutorPair(Runnable runnable, Executor executor) {
this.runnable = runnable;
this.executor = executor;
}
void execute() {
try {
executor.execute(runnable);
} catch (RuntimeException e) {
log.log(Level.SEVERE, "RuntimeException while executing runnable "
+ runnable + " with executor " + executor, e);
}
}
}
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.common.collect.ObjectArrays;
import java.util.AbstractQueue;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* A bounded {@linkplain BlockingQueue blocking queue} backed by an
* array. This queue orders elements FIFO (first-in-first-out). The
* <em>head</em> of the queue is that element that has been on the
* queue the longest time. The <em>tail</em> of the queue is that
* element that has been on the queue the shortest time. New elements
* are inserted at the tail of the queue, and the queue retrieval
* operations obtain elements at the head of the queue.
*
* <p>This is a classic "bounded buffer", in which a
* fixed-sized array holds elements inserted by producers and
* extracted by consumers. Once created, the capacity cannot be
* increased. Attempts to <tt>put</tt> an element into a full queue
* will result in the operation blocking; attempts to <tt>take</tt> an
* element from an empty queue will similarly block.
*
* <p> This class supports an optional fairness policy for ordering
* waiting producer and consumer threads. By default, this ordering
* is not guaranteed. However, a queue constructed with fairness set
* to <tt>true</tt> grants threads access in FIFO order. Fairness
* generally decreases throughput but reduces variability and avoids
* starvation.
*
* <p>This class and its iterator implement all of the
* <em>optional</em> methods of the {@link Collection} and {@link
* Iterator} interfaces.
*
* @author Doug Lea
* @author Justin T. Sampson
* @param <E> the type of elements held in this collection
*/
public class MonitorBasedArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E> {
// Based on revision 1.58 of ArrayBlockingQueue by Doug Lea, from
// http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/
/** The queued items */
final E[] items;
/** items index for next take, poll or remove */
int takeIndex;
/** items index for next put, offer, or add. */
int putIndex;
/** Number of items in the queue */
private int count;
/*
* Concurrency control uses the classic two-condition algorithm
* found in any textbook.
*/
/** Monitor guarding all access */
final Monitor monitor;
/** Guard for waiting takes */
private final Monitor.Guard notEmpty;
/** Guard for waiting puts */
private final Monitor.Guard notFull;
// Internal helper methods
/**
* Circularly increment i.
*/
final int inc(int i) {
return (++i == items.length) ? 0 : i;
}
/**
* Inserts element at current put position, advances, and signals.
* Call only when occupying monitor.
*/
private void insert(E x) {
items[putIndex] = x;
putIndex = inc(putIndex);
++count;
}
/**
* Extracts element at current take position, advances, and signals.
* Call only when occupying monitor.
*/
private E extract() {
final E[] items = this.items;
E x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
return x;
}
/**
* Utility for remove and iterator.remove: Delete item at position i.
* Call only when occupying monitor.
*/
void removeAt(int i) {
final E[] items = this.items;
// if removing front item, just advance
if (i == takeIndex) {
items[takeIndex] = null;
takeIndex = inc(takeIndex);
} else {
// slide over all others up through putIndex.
for (;;) {
int nexti = inc(i);
if (nexti != putIndex) {
items[i] = items[nexti];
i = nexti;
} else {
items[i] = null;
putIndex = i;
break;
}
}
}
--count;
}
/**
* Creates an <tt>MonitorBasedArrayBlockingQueue</tt> with the given (fixed)
* capacity and default access policy.
*
* @param capacity the capacity of this queue
* @throws IllegalArgumentException if <tt>capacity</tt> is less than 1
*/
public MonitorBasedArrayBlockingQueue(int capacity) {
this(capacity, false);
}
/**
* Creates an <tt>MonitorBasedArrayBlockingQueue</tt> with the given (fixed)
* capacity and the specified access policy.
*
* @param capacity the capacity of this queue
* @param fair if <tt>true</tt> then queue accesses for threads blocked
* on insertion or removal, are processed in FIFO order;
* if <tt>false</tt> the access order is unspecified.
* @throws IllegalArgumentException if <tt>capacity</tt> is less than 1
*/
public MonitorBasedArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = newEArray(capacity);
monitor = new Monitor(fair);
notEmpty = new Monitor.Guard(monitor) {
@Override public boolean isSatisfied() {
return count > 0;
}
};
notFull = new Monitor.Guard(monitor) {
@Override public boolean isSatisfied() {
return count < items.length;
}
};
}
@SuppressWarnings("unchecked") // please don't try this home, kids
private static <E> E[] newEArray(int capacity) {
return (E[]) new Object[capacity];
}
/**
* Creates an <tt>MonitorBasedArrayBlockingQueue</tt> with the given (fixed)
* capacity, the specified access policy and initially containing the
* elements of the given collection,
* added in traversal order of the collection's iterator.
*
* @param capacity the capacity of this queue
* @param fair if <tt>true</tt> then queue accesses for threads blocked
* on insertion or removal, are processed in FIFO order;
* if <tt>false</tt> the access order is unspecified.
* @param c the collection of elements to initially contain
* @throws IllegalArgumentException if <tt>capacity</tt> is less than
* <tt>c.size()</tt>, or less than 1.
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
public MonitorBasedArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair);
if (capacity < c.size())
throw new IllegalArgumentException();
for (E e : c)
add(e);
}
/**
* Inserts the specified element at the tail of this queue if it is
* possible to do so immediately without exceeding the queue's capacity,
* returning <tt>true</tt> upon success and throwing an
* <tt>IllegalStateException</tt> if this queue is full.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws IllegalStateException if this queue is full
* @throws NullPointerException if the specified element is null
*/
@Override public boolean add(E e) {
return super.add(e);
}
/**
* Inserts the specified element at the tail of this queue if it is
* possible to do so immediately without exceeding the queue's capacity,
* returning <tt>true</tt> upon success and <tt>false</tt> if this queue
* is full. This method is generally preferable to method {@link #add},
* which can fail to insert an element only by throwing an exception.
*
* @throws NullPointerException if the specified element is null
*/
@Override
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
final Monitor monitor = this.monitor;
if (monitor.enterIf(notFull)) {
try {
insert(e);
return true;
} finally {
monitor.leave();
}
} else {
return false;
}
}
/**
* Inserts the specified element at the tail of this queue, waiting
* for space to become available if the queue is full.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
@Override
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
final Monitor monitor = this.monitor;
monitor.enterWhen(notFull);
try {
insert(e);
} finally {
monitor.leave();
}
}
/**
* Inserts the specified element at the tail of this queue, waiting
* up to the specified wait time for space to become available if
* the queue is full.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
@Override
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
if (e == null) throw new NullPointerException();
final Monitor monitor = this.monitor;
if (monitor.enterWhen(notFull, timeout, unit)) {
try {
insert(e);
return true;
} finally {
monitor.leave();
}
} else {
return false;
}
}
@Override
public E poll() {
final Monitor monitor = this.monitor;
if (monitor.enterIf(notEmpty)) {
try {
return extract();
} finally {
monitor.leave();
}
} else {
return null;
}
}
@Override
public E take() throws InterruptedException {
final Monitor monitor = this.monitor;
monitor.enterWhen(notEmpty);
try {
return extract();
} finally {
monitor.leave();
}
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
final Monitor monitor = this.monitor;
if (monitor.enterWhen(notEmpty, timeout, unit)) {
try {
return extract();
} finally {
monitor.leave();
}
} else {
return null;
}
}
@Override
public E peek() {
final Monitor monitor = this.monitor;
if (monitor.enterIf(notEmpty)) {
try {
return items[takeIndex];
} finally {
monitor.leave();
}
} else {
return null;
}
}
// this doc comment is overridden to remove the reference to collections
// greater in size than Integer.MAX_VALUE
/**
* Returns the number of elements in this queue.
*
* @return the number of elements in this queue
*/
@Override public int size() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return count;
} finally {
monitor.leave();
}
}
// this doc comment is a modified copy of the inherited doc comment,
// without the reference to unlimited queues.
/**
* Returns the number of additional elements that this queue can ideally
* (in the absence of memory or resource constraints) accept without
* blocking. This is always equal to the initial capacity of this queue
* less the current <tt>size</tt> of this queue.
*
* <p>Note that you <em>cannot</em> always tell if an attempt to insert
* an element will succeed by inspecting <tt>remainingCapacity</tt>
* because it may be the case that another thread is about to
* insert or remove an element.
*/
@Override
public int remainingCapacity() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return items.length - count;
} finally {
monitor.leave();
}
}
/**
* Removes a single instance of the specified element from this queue,
* if it is present. More formally, removes an element <tt>e</tt> such
* that <tt>o.equals(e)</tt>, if this queue contains one or more such
* elements.
* Returns <tt>true</tt> if this queue contained the specified element
* (or equivalently, if this queue changed as a result of the call).
*
* @param o element to be removed from this queue, if present
* @return <tt>true</tt> if this queue changed as a result of the call
*/
@Override public boolean remove(@Nullable Object o) {
if (o == null) return false;
final E[] items = this.items;
final Monitor monitor = this.monitor;
monitor.enter();
try {
int i = takeIndex;
int k = 0;
for (;;) {
if (k++ >= count)
return false;
if (o.equals(items[i])) {
removeAt(i);
return true;
}
i = inc(i);
}
} finally {
monitor.leave();
}
}
/**
* Returns <tt>true</tt> if this queue contains the specified element.
* More formally, returns <tt>true</tt> if and only if this queue contains
* at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
*
* @param o object to be checked for containment in this queue
* @return <tt>true</tt> if this queue contains the specified element
*/
@Override public boolean contains(@Nullable Object o) {
if (o == null) return false;
final E[] items = this.items;
final Monitor monitor = this.monitor;
monitor.enter();
try {
int i = takeIndex;
int k = 0;
while (k++ < count) {
if (o.equals(items[i]))
return true;
i = inc(i);
}
return false;
} finally {
monitor.leave();
}
}
/**
* Returns an array containing all of the elements in this queue, in
* proper sequence.
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this queue. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this queue
*/
@Override public Object[] toArray() {
final E[] items = this.items;
final Monitor monitor = this.monitor;
monitor.enter();
try {
Object[] a = new Object[count];
int k = 0;
int i = takeIndex;
while (k < count) {
a[k++] = items[i];
i = inc(i);
}
return a;
} finally {
monitor.leave();
}
}
/**
* Returns an array containing all of the elements in this queue, in
* proper sequence; the runtime type of the returned array is that of
* the specified array. If the queue fits in the specified array, it
* is returned therein. Otherwise, a new array is allocated with the
* runtime type of the specified array and the size of this queue.
*
* <p>If this queue fits in the specified array with room to spare
* (i.e., the array has more elements than this queue), the element in
* the array immediately following the end of the queue is set to
* <tt>null</tt>.
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose <tt>x</tt> is a queue known to contain only strings.
* The following code can be used to dump the queue into a newly
* allocated array of <tt>String</tt>:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* <p>Note that <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>.
*
* @param a the array into which the elements of the queue are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose
* @return an array containing all of the elements in this queue
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this queue
* @throws NullPointerException if the specified array is null
*/
@Override public <T> T[] toArray(T[] a) {
final E[] items = this.items;
final Monitor monitor = this.monitor;
monitor.enter();
try {
if (a.length < count)
a = ObjectArrays.newArray(a, count);
int k = 0;
int i = takeIndex;
while (k < count) {
// This cast is not itself safe, but the following statement
// will fail if the runtime type of items[i] is not assignable
// to the runtime type of a[k++], which is all that the method
// contract requires (see @throws ArrayStoreException above).
@SuppressWarnings("unchecked")
T t = (T) items[i];
a[k++] = t;
i = inc(i);
}
if (a.length > count)
a[count] = null;
return a;
} finally {
monitor.leave();
}
}
@Override public String toString() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return super.toString();
} finally {
monitor.leave();
}
}
/**
* Atomically removes all of the elements from this queue.
* The queue will be empty after this call returns.
*/
@Override public void clear() {
final E[] items = this.items;
final Monitor monitor = this.monitor;
monitor.enter();
try {
int i = takeIndex;
int k = count;
while (k-- > 0) {
items[i] = null;
i = inc(i);
}
count = 0;
putIndex = 0;
takeIndex = 0;
} finally {
monitor.leave();
}
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
@Override
public int drainTo(Collection<? super E> c) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
final E[] items = this.items;
final Monitor monitor = this.monitor;
monitor.enter();
try {
int i = takeIndex;
int n = 0;
int max = count;
while (n < max) {
c.add(items[i]);
items[i] = null;
i = inc(i);
++n;
}
if (n > 0) {
count = 0;
putIndex = 0;
takeIndex = 0;
}
return n;
} finally {
monitor.leave();
}
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
if (maxElements <= 0)
return 0;
final E[] items = this.items;
final Monitor monitor = this.monitor;
monitor.enter();
try {
int i = takeIndex;
int n = 0;
int max = (maxElements < count) ? maxElements : count;
while (n < max) {
c.add(items[i]);
items[i] = null;
i = inc(i);
++n;
}
if (n > 0) {
count -= n;
takeIndex = i;
}
return n;
} finally {
monitor.leave();
}
}
/**
* Returns an iterator over the elements in this queue in proper sequence.
* The returned <tt>Iterator</tt> is a "weakly consistent" iterator that
* will never throw {@link ConcurrentModificationException},
* and guarantees to traverse elements as they existed upon
* construction of the iterator, and may (but is not guaranteed to)
* reflect any modifications subsequent to construction.
*
* @return an iterator over the elements in this queue in proper sequence
*/
@Override public Iterator<E> iterator() {
final Monitor monitor = this.monitor;
monitor.enter();
try {
return new Itr();
} finally {
monitor.leave();
}
}
/**
* Iterator for MonitorBasedArrayBlockingQueue
*/
private class Itr implements Iterator<E> {
/**
* Index of element to be returned by next,
* or a negative number if no such.
*/
private int nextIndex;
/**
* nextItem holds on to item fields because once we claim
* that an element exists in hasNext(), we must return it in
* the following next() call even if it was in the process of
* being removed when hasNext() was called.
*/
private E nextItem;
/**
* Index of element returned by most recent call to next.
* Reset to -1 if this element is deleted by a call to remove.
*/
private int lastRet;
Itr() {
lastRet = -1;
if (count == 0)
nextIndex = -1;
else {
nextIndex = takeIndex;
nextItem = items[takeIndex];
}
}
@Override
public boolean hasNext() {
/*
* No sync. We can return true by mistake here
* only if this iterator passed across threads,
* which we don't support anyway.
*/
return nextIndex >= 0;
}
/**
* Checks whether nextIndex is valid; if so setting nextItem.
* Stops iterator when either hits putIndex or sees null item.
*/
private void checkNext() {
if (nextIndex == putIndex) {
nextIndex = -1;
nextItem = null;
} else {
nextItem = items[nextIndex];
if (nextItem == null)
nextIndex = -1;
}
}
@Override
public E next() {
final Monitor monitor = MonitorBasedArrayBlockingQueue.this.monitor;
monitor.enter();
try {
if (nextIndex < 0)
throw new NoSuchElementException();
lastRet = nextIndex;
E x = nextItem;
nextIndex = inc(nextIndex);
checkNext();
return x;
} finally {
monitor.leave();
}
}
@Override
public void remove() {
final Monitor monitor = MonitorBasedArrayBlockingQueue.this.monitor;
monitor.enter();
try {
int i = lastRet;
if (i == -1)
throw new IllegalStateException();
lastRet = -1;
int ti = takeIndex;
removeAt(i);
// back up cursor (reset to front if was first element)
nextIndex = (i == ti) ? takeIndex : i;
checkNext();
} finally {
monitor.leave();
}
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.caliper.BeforeExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Benchmarks for {@link CycleDetectingLockFactory}.
*
* @author Darick Tong
*/
public class CycleDetectingLockFactoryBenchmark {
@Param({"2","3","4","5","10"}) int lockNestingDepth;
CycleDetectingLockFactory factory;
private Lock[] plainLocks;
private Lock[] detectingLocks;
@BeforeExperiment
void setUp() throws Exception {
this.factory = CycleDetectingLockFactory.newInstance(
CycleDetectingLockFactory.Policies.WARN);
this.plainLocks = new Lock[lockNestingDepth];
for (int i = 0; i < lockNestingDepth; i++) {
plainLocks[i] = new ReentrantLock();
}
this.detectingLocks = new Lock[lockNestingDepth];
for (int i = 0; i < lockNestingDepth; i++) {
detectingLocks[i] = factory.newReentrantLock("Lock" + i);
}
}
@Benchmark void unorderedPlainLocks(int reps) {
lockAndUnlock(new ReentrantLock(), reps);
}
@Benchmark void unorderedCycleDetectingLocks(int reps) {
lockAndUnlock(factory.newReentrantLock("foo"), reps);
}
private void lockAndUnlock(Lock lock, int reps) {
for (int i = 0; i < reps; i++) {
lock.lock();
lock.unlock();
}
}
@Benchmark void orderedPlainLocks(int reps) {
lockAndUnlockNested(plainLocks, reps);
}
@Benchmark void orderedCycleDetectingLocks(int reps) {
lockAndUnlockNested(detectingLocks, reps);
}
private void lockAndUnlockNested(Lock[] locks, int reps) {
for (int i = 0; i < reps; i++) {
for (int j = 0; j < locks.length; j++) {
locks[j].lock();
}
for (int j = locks.length - 1; j >= 0; j--) {
locks[j].unlock();
}
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.base;
/**
* Common benchmarking utilities.
*
* @author Christopher Swenson
* @author Louis Wasserman
*/
class BenchmarkHelpers {
private static final String WHITESPACE_CHARACTERS =
"\u00a0\u180e\u202f\t\n\013\f\r \u0085"
+ "\u1680\u2028\u2029\u205f\u3000\u2000\u2001\u2002\u2003\u2004\u2005"
+ "\u2006\u2007\u2008\u2009\u200a";
private static final String ASCII_CHARACTERS;
static {
int spaceInAscii = 32;
int sevenBitAsciiMax = 128;
StringBuilder sb = new StringBuilder(sevenBitAsciiMax - spaceInAscii);
for (int ch = spaceInAscii; ch < sevenBitAsciiMax; ch++) {
sb.append((char) ch);
}
ASCII_CHARACTERS = sb.toString();
}
private static final String ALL_DIGITS;
static {
StringBuilder sb = new StringBuilder();
String zeros =
"0\u0660\u06f0\u07c0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be6\u0c66"
+ "\u0ce6\u0d66\u0e50\u0ed0\u0f20\u1040\u1090\u17e0\u1810\u1946"
+ "\u19d0\u1b50\u1bb0\u1c40\u1c50\ua620\ua8d0\ua900\uaa50\uff10";
for (char base : zeros.toCharArray()) {
for (int offset = 0; offset < 10; offset++) {
sb.append((char) (base + offset));
}
}
ALL_DIGITS = sb.toString();
}
/**
* Sample CharMatcher instances for benchmarking.
*/
public enum SampleMatcherConfig {
WHITESPACE(CharMatcher.WHITESPACE, WHITESPACE_CHARACTERS),
HASH(CharMatcher.is('#'), "#"),
ASCII(CharMatcher.ASCII, ASCII_CHARACTERS),
WESTERN_DIGIT("0123456789"),
ALL_DIGIT(CharMatcher.DIGIT, ALL_DIGITS),
OPS_5("+-*/%"),
HEX_16(CharMatcher.inRange('0', '9').or(CharMatcher.inRange('A', 'F')), "0123456789ABCDEF"),
HEX_22(CharMatcher.inRange('0', '9')
.or(CharMatcher.inRange('A', 'F')).or(CharMatcher.inRange('a', 'f')),
"0123456789ABCDEFabcdef"),
GERMAN_59(CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z')).or(CharMatcher.anyOf("äöüßÄÖÜ")),
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZäöüßÄÖÜ");
public final CharMatcher matcher;
public final String matchingChars;
SampleMatcherConfig(String matchingChars) {
this(CharMatcher.anyOf(matchingChars), matchingChars);
}
SampleMatcherConfig(CharMatcher matcher, String matchingChars) {
this.matcher = matcher;
this.matchingChars = matchingChars;
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.reflect.subpackage;
public class ClassInSubPackage {}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import java.math.BigInteger;
import java.util.Random;
/**
* Utilities for benchmarks.
*
* @author Louis Wasserman
*/
final class MathBenchmarking {
static final int ARRAY_SIZE = 0x10000;
static final int ARRAY_MASK = 0x0ffff;
static final Random RANDOM_SOURCE = new Random(314159265358979L);
static final int MAX_EXPONENT = 100;
/*
* Duplicated from LongMath.
* binomial(biggestBinomials[k], k) fits in a long, but not
* binomial(biggestBinomials[k] + 1, k).
*/
static final int[] biggestBinomials =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733,
887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68,
67, 67, 66, 66, 66, 66};
static BigInteger randomPositiveBigInteger(int numBits) {
int digits = RANDOM_SOURCE.nextInt(numBits) + 1;
return new BigInteger(digits, RANDOM_SOURCE).add(BigInteger.ONE);
}
static BigInteger randomNonNegativeBigInteger(int numBits) {
int digits = RANDOM_SOURCE.nextInt(numBits) + 1;
return new BigInteger(digits, RANDOM_SOURCE);
}
static BigInteger randomNonZeroBigInteger(int numBits) {
BigInteger result = randomPositiveBigInteger(numBits);
return RANDOM_SOURCE.nextBoolean() ? result : result.negate();
}
static BigInteger randomBigInteger(int numBits) {
BigInteger result = randomNonNegativeBigInteger(numBits);
return RANDOM_SOURCE.nextBoolean() ? result : result.negate();
}
static double randomDouble(int maxExponent) {
double result = RANDOM_SOURCE.nextDouble();
result = Math.scalb(result, RANDOM_SOURCE.nextInt(maxExponent + 1));
return RANDOM_SOURCE.nextBoolean() ? result : -result;
}
/**
* Returns a random integer between zero and {@code MAX_EXPONENT}.
*/
static int randomExponent() {
return RANDOM_SOURCE.nextInt(MAX_EXPONENT + 1);
}
static double randomPositiveDouble() {
return Math.exp(randomDouble(6));
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.DOWN;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_DOWN;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import static java.math.RoundingMode.UP;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Doubles;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* Exhaustive input sets for every integral type.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MathTesting {
static final ImmutableSet<RoundingMode> ALL_ROUNDING_MODES = ImmutableSet.copyOf(RoundingMode
.values());
static final ImmutableList<RoundingMode> ALL_SAFE_ROUNDING_MODES = ImmutableList.of(DOWN, UP,
FLOOR, CEILING, HALF_EVEN, HALF_UP, HALF_DOWN);
// Exponents to test for the pow() function.
static final ImmutableList<Integer> EXPONENTS = ImmutableList.of(0, 1, 2, 3, 4, 7, 10, 15,
20, 25, 40, 70);
/* Helper function to make a Long value from an Integer. */
private static final Function<Integer, Long> TO_LONG = new Function<Integer, Long>() {
@Override
public Long apply(Integer n) {
return Long.valueOf(n);
}
};
/* Helper function to make a BigInteger value from a Long. */
private static final Function<Long, BigInteger> TO_BIGINTEGER =
new Function<Long, BigInteger>() {
@Override
public BigInteger apply(Long n) {
return BigInteger.valueOf(n);
}
};
private static final Function<Integer, Integer> NEGATE_INT = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer x) {
return -x;
}
};
private static final Function<Long, Long> NEGATE_LONG = new Function<Long, Long>() {
@Override
public Long apply(Long x) {
return -x;
}
};
private static final Function<BigInteger, BigInteger> NEGATE_BIGINT =
new Function<BigInteger, BigInteger>() {
@Override
public BigInteger apply(BigInteger x) {
return x.negate();
}
};
/*
* This list contains values that attempt to provoke overflow in integer operations. It contains
* positive values on or near 2^N for N near multiples of 8 (near byte boundaries).
*/
static final ImmutableSet<Integer> POSITIVE_INTEGER_CANDIDATES;
static final Iterable<Integer> NEGATIVE_INTEGER_CANDIDATES;
static final Iterable<Integer> NONZERO_INTEGER_CANDIDATES;
static final Iterable<Integer> ALL_INTEGER_CANDIDATES;
static {
ImmutableSet.Builder<Integer> intValues = ImmutableSet.builder();
// Add boundary values manually to avoid over/under flow (this covers 2^N for 0 and 31).
intValues.add(Integer.MAX_VALUE - 1, Integer.MAX_VALUE);
// Add values up to 40. This covers cases like "square of a prime" and such.
for (int i = 1; i <= 40; i++) {
intValues.add(i);
}
// Now add values near 2^N for lots of values of N.
for (int exponent : asList(2, 3, 4, 9, 15, 16, 17, 24, 25, 30)) {
int x = 1 << exponent;
intValues.add(x, x + 1, x - 1);
}
intValues.add(9999).add(10000).add(10001).add(1000000); // near powers of 10
intValues.add(5792).add(5793); // sqrt(2^25) rounded up and down
POSITIVE_INTEGER_CANDIDATES = intValues.build();
NEGATIVE_INTEGER_CANDIDATES = ImmutableList.copyOf(Iterables.concat(
Iterables.transform(POSITIVE_INTEGER_CANDIDATES, NEGATE_INT),
ImmutableList.of(Integer.MIN_VALUE)));
NONZERO_INTEGER_CANDIDATES = ImmutableList.copyOf(
Iterables.concat(POSITIVE_INTEGER_CANDIDATES, NEGATIVE_INTEGER_CANDIDATES));
ALL_INTEGER_CANDIDATES = Iterables.concat(NONZERO_INTEGER_CANDIDATES, ImmutableList.of(0));
}
/*
* This list contains values that attempt to provoke overflow in long operations. It contains
* positive values on or near 2^N for N near multiples of 8 (near byte boundaries). This list is
* a superset of POSITIVE_INTEGER_CANDIDATES.
*/
static final ImmutableSet<Long> POSITIVE_LONG_CANDIDATES;
static final Iterable<Long> NEGATIVE_LONG_CANDIDATES;
static final Iterable<Long> NONZERO_LONG_CANDIDATES;
static final Iterable<Long> ALL_LONG_CANDIDATES;
static {
ImmutableSet.Builder<Long> longValues = ImmutableSet.builder();
// First of all add all the integer candidate values.
longValues.addAll(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, TO_LONG));
// Add boundary values manually to avoid over/under flow (this covers 2^N for 31 and 63).
longValues.add(Integer.MAX_VALUE + 1L, Long.MAX_VALUE - 1L, Long.MAX_VALUE);
// Now add values near 2^N for lots of values of N.
for (int exponent : asList(32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57)) {
long x = 1L << exponent;
longValues.add(x, x + 1, x - 1);
}
longValues.add(194368031998L).add(194368031999L); // sqrt(2^75) rounded up and down
POSITIVE_LONG_CANDIDATES = longValues.build();
NEGATIVE_LONG_CANDIDATES =
Iterables.concat(Iterables.transform(POSITIVE_LONG_CANDIDATES, NEGATE_LONG),
ImmutableList.of(Long.MIN_VALUE));
NONZERO_LONG_CANDIDATES = Iterables.concat(POSITIVE_LONG_CANDIDATES, NEGATIVE_LONG_CANDIDATES);
ALL_LONG_CANDIDATES = Iterables.concat(NONZERO_LONG_CANDIDATES, ImmutableList.of(0L));
}
/*
* This list contains values that attempt to provoke overflow in big integer operations. It
* contains positive values on or near 2^N for N near multiples of 8 (near byte boundaries). This
* list is a superset of POSITIVE_LONG_CANDIDATES.
*/
static final ImmutableSet<BigInteger> POSITIVE_BIGINTEGER_CANDIDATES;
static final Iterable<BigInteger> NEGATIVE_BIGINTEGER_CANDIDATES;
static final Iterable<BigInteger> NONZERO_BIGINTEGER_CANDIDATES;
static final Iterable<BigInteger> ALL_BIGINTEGER_CANDIDATES;
static {
ImmutableSet.Builder<BigInteger> bigValues = ImmutableSet.builder();
// First of all add all the long candidate values.
bigValues.addAll(Iterables.transform(POSITIVE_LONG_CANDIDATES, TO_BIGINTEGER));
// Add boundary values manually to avoid over/under flow.
bigValues.add(BigInteger.valueOf(Long.MAX_VALUE).add(ONE));
// Now add values near 2^N for lots of values of N.
for (int exponent : asList(64, 65, 71, 72, 73, 79, 80, 81, 255, 256, 257, 511, 512, 513,
Double.MAX_EXPONENT - 1, Double.MAX_EXPONENT, Double.MAX_EXPONENT + 1)) {
BigInteger x = ONE.shiftLeft(exponent);
bigValues.add(x, x.add(ONE), x.subtract(ONE));
}
bigValues.add(new BigInteger("218838949120258359057546633")); // sqrt(2^175) rounded up and
// down
bigValues.add(new BigInteger("218838949120258359057546634"));
POSITIVE_BIGINTEGER_CANDIDATES = bigValues.build();
NEGATIVE_BIGINTEGER_CANDIDATES =
Iterables.transform(POSITIVE_BIGINTEGER_CANDIDATES, NEGATE_BIGINT);
NONZERO_BIGINTEGER_CANDIDATES =
Iterables.concat(POSITIVE_BIGINTEGER_CANDIDATES, NEGATIVE_BIGINTEGER_CANDIDATES);
ALL_BIGINTEGER_CANDIDATES =
Iterables.concat(NONZERO_BIGINTEGER_CANDIDATES, ImmutableList.of(ZERO));
}
static final ImmutableSet<Double> INTEGRAL_DOUBLE_CANDIDATES;
static final ImmutableSet<Double> FRACTIONAL_DOUBLE_CANDIDATES;
static final Iterable<Double> INFINITIES = Doubles.asList(
Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY);
static final Iterable<Double> FINITE_DOUBLE_CANDIDATES;
static final Iterable<Double> POSITIVE_FINITE_DOUBLE_CANDIDATES;
static final Iterable<Double> ALL_DOUBLE_CANDIDATES;
static final Iterable<Double> DOUBLE_CANDIDATES_EXCEPT_NAN;
static {
ImmutableSet.Builder<Double> integralBuilder = ImmutableSet.builder();
ImmutableSet.Builder<Double> fractionalBuilder = ImmutableSet.builder();
integralBuilder.addAll(Doubles.asList(0.0, -0.0, Double.MAX_VALUE, -Double.MAX_VALUE));
// Add small multiples of MIN_VALUE and MIN_NORMAL
for (int scale = 1; scale <= 4; scale++) {
for (double d : Doubles.asList(Double.MIN_VALUE, Double.MIN_NORMAL)) {
fractionalBuilder.add(d * scale).add(-d * scale);
}
}
for (double d : Doubles.asList(0, 1, 2, 7, 51, 102, Math.scalb(1.0, 53), Integer.MIN_VALUE,
Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE)) {
for (double delta : Doubles.asList(0.0, 1.0, 2.0)) {
integralBuilder.addAll(Doubles.asList(d + delta, d - delta, -d - delta, -d + delta));
}
for (double delta : Doubles.asList(0.01, 0.1, 0.25, 0.499, 0.5, 0.501, 0.7, 0.8)) {
double x = d + delta;
if (x != Math.round(x)) {
fractionalBuilder.add(x);
}
}
}
INTEGRAL_DOUBLE_CANDIDATES = integralBuilder.build();
fractionalBuilder.add(1.414).add(1.415).add(Math.sqrt(2));
fractionalBuilder.add(5.656).add(5.657).add(4 * Math.sqrt(2));
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
double x = 1 / d;
if (x != Math.rint(x)) {
fractionalBuilder.add(x);
}
}
FRACTIONAL_DOUBLE_CANDIDATES = fractionalBuilder.build();
FINITE_DOUBLE_CANDIDATES =
Iterables.concat(FRACTIONAL_DOUBLE_CANDIDATES, INTEGRAL_DOUBLE_CANDIDATES);
POSITIVE_FINITE_DOUBLE_CANDIDATES =
Iterables.filter(FINITE_DOUBLE_CANDIDATES, new Predicate<Double>() {
@Override
public boolean apply(Double input) {
return input.doubleValue() > 0.0;
}
});
DOUBLE_CANDIDATES_EXCEPT_NAN = Iterables.concat(FINITE_DOUBLE_CANDIDATES, INFINITIES);
ALL_DOUBLE_CANDIDATES =
Iterables.concat(DOUBLE_CANDIDATES_EXCEPT_NAN, asList(Double.NaN));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.eventbus;
import com.google.common.collect.Lists;
import junit.framework.Assert;
import java.util.List;
import javax.annotation.Nullable;
/**
* A simple EventHandler mock that records Strings.
*
* For testing fun, also includes a landmine method that EventBus tests are
* required <em>not</em> to call ({@link #methodWithoutAnnotation(String)}).
*
* @author Cliff Biffle
*/
public class StringCatcher {
private List<String> events = Lists.newArrayList();
@Subscribe
public void hereHaveAString(@Nullable String string) {
events.add(string);
}
public void methodWithoutAnnotation(@Nullable String string) {
Assert.fail("Event bus must not call methods without @Subscribe!");
}
public List<String> getEvents() {
return events;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Random;
/**
* Utility class for being able to seed a {@link Random} value with a passed
* in seed from a benchmark parameter.
*
* TODO: Remove this class once Caliper has a better way.
*
* @author Nicholaus Shupe
*/
public final class SpecialRandom extends Random {
public static SpecialRandom valueOf(String s) {
return (s.length() == 0)
? new SpecialRandom()
: new SpecialRandom(Long.parseLong(s));
}
private final boolean hasSeed;
private final long seed;
public SpecialRandom() {
this.hasSeed = false;
this.seed = 0;
}
public SpecialRandom(long seed) {
super(seed);
this.hasSeed = true;
this.seed = seed;
}
@Override public String toString() {
return hasSeed ? "(seed:" + seed : "(default seed)";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Arrays;
/**
* A class that implements {@code Comparable} without generics, such as those
* found in libraries that support Java 1.4 and before. Our library needs to
* do the bare minimum to accommodate such types, though their use may still
* require an explicit type parameter and/or warning suppression.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
class LegacyComparable implements Comparable, Serializable {
static final LegacyComparable X = new LegacyComparable("x");
static final LegacyComparable Y = new LegacyComparable("y");
static final LegacyComparable Z = new LegacyComparable("z");
static final Iterable<LegacyComparable> VALUES_FORWARD
= Arrays.asList(X, Y, Z);
static final Iterable<LegacyComparable> VALUES_BACKWARD
= Arrays.asList(Z, Y, X);
private final String value;
LegacyComparable(String value) {
this.value = value;
}
@Override
public int compareTo(Object object) {
// This method is spec'd to throw CCE if object is of the wrong type
LegacyComparable that = (LegacyComparable) object;
return this.value.compareTo(that.value);
}
@Override public boolean equals(Object object) {
if (object instanceof LegacyComparable) {
LegacyComparable that = (LegacyComparable) object;
return this.value.equals(that.value);
}
return false;
}
@Override public int hashCode() {
return value.hashCode();
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.primitives.Ints;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Package up sample data for common collections benchmarking.
*
* @author Nicholaus Shupe
*/
class CollectionBenchmarkSampleData {
private final boolean isUserTypeFast;
private final SpecialRandom random;
private final double hitRate;
private final int size;
private final Set<Element> valuesInSet;
private final Element[] queries;
CollectionBenchmarkSampleData(int size) {
this(true, new SpecialRandom(), 1.0, size);
}
CollectionBenchmarkSampleData(
boolean isUserTypeFast,
SpecialRandom random,
double hitRate,
int size) {
this.isUserTypeFast = isUserTypeFast;
this.random = checkNotNull(random);
this.hitRate = hitRate;
this.size = size;
this.valuesInSet = createData();
this.queries = createQueries(valuesInSet, 1024);
}
Set<Element> getValuesInSet() {
return valuesInSet;
}
Element[] getQueries() {
return queries;
}
private Element[] createQueries(Set<Element> elementsInSet, int numQueries) {
List<Element> queryList = Lists.newArrayListWithCapacity(numQueries);
int numGoodQueries = (int) (numQueries * hitRate + 0.5);
// add good queries
int size = elementsInSet.size();
if (size > 0) {
int minCopiesOfEachGoodQuery = numGoodQueries / size;
int extras = numGoodQueries % size;
for (int i = 0; i < minCopiesOfEachGoodQuery; i++) {
queryList.addAll(elementsInSet);
}
List<Element> tmp = Lists.newArrayList(elementsInSet);
Collections.shuffle(tmp, random);
queryList.addAll(tmp.subList(0, extras));
}
// now add bad queries
while (queryList.size() < numQueries) {
Element candidate = newElement();
if (!elementsInSet.contains(candidate)) {
queryList.add(candidate);
}
}
Collections.shuffle(queryList, random);
return queryList.toArray(new Element[0]);
}
private Set<Element> createData() {
Set<Element> set = Sets.newHashSetWithExpectedSize(size);
while (set.size() < size) {
set.add(newElement());
}
return set;
}
private Element newElement() {
int value = random.nextInt();
return isUserTypeFast
? new Element(value)
: new SlowElement(value);
}
static class Element implements Comparable<Element> {
final int hash;
Element(int hash) {
this.hash = hash;
}
@Override public boolean equals(Object obj) {
return this == obj
|| (obj instanceof Element && ((Element) obj).hash == hash);
}
@Override public int hashCode() {
return hash;
}
@Override
public int compareTo(Element that) {
return Ints.compare(hash, that.hash);
}
@Override public String toString() {
return String.valueOf(hash);
}
}
static class SlowElement extends Element {
SlowElement(int hash) {
super(hash);
}
@Override public boolean equals(Object obj) {
return slowItDown() != 1 && super.equals(obj);
}
@Override public int hashCode() {
return slowItDown() + hash;
}
@Override public int compareTo(Element e) {
int x = slowItDown();
return x + super.compareTo(e) - x; // silly attempt to prevent opt
}
static int slowItDown() {
int result = 0;
for (int i = 1; i <= 1000; i++) {
result += i;
}
return result;
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import junit.framework.TestCase;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Base test case for testing the variety of forwarding classes.
*
* @author Robert Konigsberg
* @author Louis Wasserman
*/
public abstract class ForwardingTestCase extends TestCase {
private final List<String> calls = new ArrayList<String>();
private void called(String id) {
calls.add(id);
}
protected String getCalls() {
return calls.toString();
}
protected boolean isCalled() {
return !calls.isEmpty();
}
@SuppressWarnings("unchecked")
protected <T> T createProxyInstance(Class<T> c) {
/*
* This invocation handler only registers that a method was called,
* and then returns a bogus, but acceptable, value.
*/
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
called(asString(method));
return getDefaultValue(method.getReturnType());
}
};
return (T) Proxy.newProxyInstance(c.getClassLoader(),
new Class[] { c }, handler);
}
private static final Joiner COMMA_JOINER = Joiner.on(",");
/*
* Returns string representation of a method.
*
* If the method takes no parameters, it returns the name (e.g.
* "isEmpty". If the method takes parameters, it returns the simple names
* of the parameters (e.g. "put(Object,Object)".)
*/
private String asString(Method method) {
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 0) {
return methodName;
}
Iterable<String> parameterNames = Iterables.transform(
Arrays.asList(parameterTypes),
new Function<Class<?>, String>() {
@Override
public String apply(Class<?> from) {
return from.getSimpleName();
}
});
return methodName + "(" + COMMA_JOINER.join(parameterNames) + ")";
}
private static Object getDefaultValue(Class<?> returnType) {
if (returnType == boolean.class || returnType == Boolean.class) {
return Boolean.FALSE;
} else if (returnType == int.class || returnType == Integer.class) {
return 0;
} else if ((returnType == Set.class) || (returnType == Collection.class)) {
return Collections.emptySet();
} else if (returnType == Iterator.class) {
return Iterators.emptyModifiableIterator();
} else if (returnType.isArray()) {
return Array.newInstance(returnType.getComponentType(), 0);
} else {
return null;
}
}
protected static <T> void callAllPublicMethods(Class<T> theClass, T object)
throws InvocationTargetException {
for (Method method : theClass.getMethods()) {
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] parameters = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
parameters[i] = getDefaultValue(parameterTypes[i]);
}
try {
try {
method.invoke(object, parameters);
} catch (InvocationTargetException ex) {
try {
throw ex.getCause();
} catch (UnsupportedOperationException unsupported) {
// this is a legit exception
}
}
} catch (Throwable cause) {
throw new InvocationTargetException(cause,
method.toString() + " with args: " + Arrays.toString(parameters));
}
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
/**
* Helper classes for various benchmarks.
*
* @author Christopher Swenson
*/
final class BenchmarkHelpers {
/**
* So far, this is the best way to test various implementations of {@link Set} subclasses.
*/
public enum SetImpl {
Hash {
@Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) {
return new HashSet<E>(contents);
}
},
LinkedHash {
@Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) {
return new LinkedHashSet<E>(contents);
}
},
Tree {
@Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) {
return new TreeSet<E>(contents);
}
},
Unmodifiable {
@Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) {
return Collections.unmodifiableSet(new HashSet<E>(contents));
}
},
Synchronized {
@Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) {
return Collections.synchronizedSet(new HashSet<E>(contents));
}
},
Immutable {
@Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) {
return ImmutableSet.copyOf(contents);
}
},
ImmutableSorted {
@Override <E extends Comparable<E>> Set<E> create(Collection<E> contents) {
return ImmutableSortedSet.copyOf(contents);
}
},
;
abstract <E extends Comparable<E>> Set<E> create(Collection<E> contents);
}
public enum ListMultimapImpl {
ArrayList {
@Override
<K, V> ListMultimap<K, V> create(Multimap<K, V> contents) {
return ArrayListMultimap.create(contents);
}
},
LinkedList {
@Override
<K, V> ListMultimap<K, V> create(Multimap<K, V> contents) {
return LinkedListMultimap.create(contents);
}
},
ImmutableList {
@Override
<K, V> ListMultimap<K, V> create(Multimap<K, V> contents) {
return ImmutableListMultimap.copyOf(contents);
}
};
abstract <K, V> ListMultimap<K, V> create(Multimap<K, V> contents);
}
public enum SetMultimapImpl {
Hash {
@Override
<K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create(
Multimap<K, V> contents) {
return HashMultimap.create(contents);
}
},
LinkedHash {
@Override
<K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create(
Multimap<K, V> contents) {
return LinkedHashMultimap.create(contents);
}
},
Tree {
@Override
<K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create(
Multimap<K, V> contents) {
return TreeMultimap.create(contents);
}
},
ImmutableSet {
@Override
<K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create(
Multimap<K, V> contents) {
return ImmutableSetMultimap.copyOf(contents);
}
};
abstract <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create(
Multimap<K, V> contents);
}
public enum MapImpl {
Hash {
@Override
<K, V> Map<K, V> create(Map<K, V> map) {
return Maps.newHashMap(map);
}
},
LinkedHash {
@Override
<K, V> Map<K, V> create(Map<K, V> map) {
return Maps.newLinkedHashMap(map);
}
},
ConcurrentHash {
@Override
<K, V> Map<K, V> create(Map<K, V> map) {
return new ConcurrentHashMap<K, V>(map);
}
},
Immutable {
@Override
<K, V> Map<K, V> create(Map<K, V> map) {
return ImmutableMap.copyOf(map);
}
};
abstract <K, V> Map<K, V> create(Map<K, V> map);
}
enum SortedMapImpl {
Tree {
@Override
<K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) {
SortedMap<K, V> result = Maps.newTreeMap();
result.putAll(map);
return result;
}
},
ConcurrentSkipList {
@Override
<K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) {
return new ConcurrentSkipListMap<K, V>(map);
}
},
ImmutableSorted {
@Override
<K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) {
return ImmutableSortedMap.copyOf(map);
}
};
abstract <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map);
}
enum BiMapImpl {
Hash{
@Override
<K, V> BiMap<K, V> create(BiMap<K, V> map) {
return HashBiMap.create(map);
}
},
Immutable {
@Override
<K, V> BiMap<K, V> create(BiMap<K, V> map) {
return ImmutableBiMap.copyOf(map);
}
};
abstract <K, V> BiMap<K, V> create(BiMap<K, V> map);
}
enum MultisetImpl {
Hash {
@Override
<E> Multiset<E> create(Multiset<E> contents) {
return HashMultiset.create(contents);
}
},
LinkedHash {
@Override
<E> Multiset<E> create(Multiset<E> contents) {
return LinkedHashMultiset.create(contents);
}
},
ConcurrentHash {
@Override
<E> Multiset<E> create(Multiset<E> contents) {
return ConcurrentHashMultiset.create(contents);
}
},
Immutable {
@Override
<E> Multiset<E> create(Multiset<E> contents) {
return ImmutableMultiset.copyOf(contents);
}
};
abstract <E> Multiset<E> create(Multiset<E> contents);
}
enum SortedMultisetImpl {
Tree {
@Override
<E extends Comparable<E>> SortedMultiset<E> create(Multiset<E> contents) {
return TreeMultiset.create(contents);
}
},
ImmutableSorted {
@Override
<E extends Comparable<E>> SortedMultiset<E> create(Multiset<E> contents) {
return ImmutableSortedMultiset.copyOf(contents);
}
};
abstract <E extends Comparable<E>> SortedMultiset<E> create(Multiset<E> contents);
}
enum TableImpl {
HashBased {
@Override
<R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create(
Table<R, C, V> contents) {
return HashBasedTable.create(contents);
}
},
TreeBased {
@Override
<R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create(
Table<R, C, V> contents) {
Table<R, C, V> table = TreeBasedTable.create();
table.putAll(contents);
return table;
}
},
Array {
@Override
<R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create(
Table<R, C, V> contents) {
if (contents.isEmpty()) {
return ImmutableTable.of();
} else {
return ArrayTable.create(contents);
}
}
},
Immutable {
@Override
<R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create(
Table<R, C, V> contents) {
return ImmutableTable.copyOf(contents);
}
};
abstract <R extends Comparable<R>, C extends Comparable<C>, V>
Table<R, C, V> create(Table<R, C, V> contents);
}
public enum Value {
INSTANCE;
}
public enum ListSizeDistribution {
UNIFORM_0_TO_2(0, 2), UNIFORM_0_TO_9(0, 9), ALWAYS_0(0, 0), ALWAYS_10(10, 10);
final int min;
final int max;
private ListSizeDistribution(int min, int max) {
this.min = min;
this.max = max;
}
public int chooseSize(Random random) {
return random.nextInt(max - min + 1) + min;
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.testing.SerializableTester.reserialize;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.testing.SerializableTester;
import java.util.Set;
/**
* Variant of {@link SerializableTester} that does not require the reserialized object's class to be
* identical to the original.
*
* @author Chris Povirk
*/
/*
* The whole thing is really @GwtIncompatible, but GwtJUnitConvertedTestModule doesn't have a
* parameter for non-GWT, non-test files, and it didn't seem worth adding one for this unusual case.
*/
@GwtCompatible(emulated = true)
final class LenientSerializableTester {
/*
* TODO(cpovirk): move this to c.g.c.testing if we allow for c.g.c.annotations dependencies so
* that it can be GWTified?
*/
@GwtIncompatible("SerializableTester")
static <E> Set<E> reserializeAndAssertLenient(Set<E> original) {
Set<E> copy = reserialize(original);
assertEquals(original, copy);
assertTrue(copy instanceof ImmutableSet);
return copy;
}
@GwtIncompatible("SerializableTester")
static <E> Multiset<E> reserializeAndAssertLenient(Multiset<E> original) {
Multiset<E> copy = reserialize(original);
assertEquals(original, copy);
assertTrue(copy instanceof ImmutableMultiset);
return copy;
}
private LenientSerializableTester() {}
}
| Java |
/*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.hash;
/**
* An enum that contains all of the known hash functions.
*
* @author Kurt Alfred Kluever
*/
enum HashFunctionEnum {
ADLER32(Hashing.adler32()),
CRC32(Hashing.crc32()),
GOOD_FAST_HASH_32(Hashing.goodFastHash(32)),
GOOD_FAST_HASH_64(Hashing.goodFastHash(64)),
GOOD_FAST_HASH_128(Hashing.goodFastHash(128)),
GOOD_FAST_HASH_256(Hashing.goodFastHash(256)),
MD5(Hashing.md5()),
MURMUR3_128(Hashing.murmur3_128()),
MURMUR3_32(Hashing.murmur3_32()),
SHA1(Hashing.sha1()),
SHA256(Hashing.sha256()),
SHA512(Hashing.sha512()),
SIP_HASH24(Hashing.sipHash24()),
// Hash functions found in //javatests for comparing against current implementation of CityHash.
// These can probably be removed sooner or later.
;
private final HashFunction hashFunction;
private HashFunctionEnum(HashFunction hashFunction) {
this.hashFunction = hashFunction;
}
HashFunction getHashFunction() {
return hashFunction;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.hash;
import static org.junit.Assert.assertEquals;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.common.testing.EqualsTester;
import org.junit.Assert;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Random;
import java.util.Set;
/**
* Various utilities for testing {@link HashFunction}s.
*
* @author Dimitris Andreou
* @author Kurt Alfred Kluever
*/
final class HashTestUtils {
private HashTestUtils() {}
/**
* Converts a string, which should contain only ascii-representable characters, to a byte[].
*/
static byte[] ascii(String string) {
byte[] bytes = new byte[string.length()];
for (int i = 0; i < string.length(); i++) {
bytes[i] = (byte) string.charAt(i);
}
return bytes;
}
interface HashFn {
byte[] hash(byte[] input, int seed);
}
static void verifyHashFunction(HashFn hashFunction, int hashbits, int expected) {
int hashBytes = hashbits / 8;
byte[] key = new byte[256];
byte[] hashes = new byte[hashBytes * 256];
// Hash keys of the form {}, {0}, {0,1}, {0,1,2}... up to N=255,using 256-N as the seed
for (int i = 0; i < 256; i++) {
key[i] = (byte) i;
int seed = 256 - i;
byte[] hash = hashFunction.hash(Arrays.copyOf(key, i), seed);
System.arraycopy(hash, 0, hashes, i * hashBytes, hash.length);
}
// Then hash the result array
byte[] result = hashFunction.hash(hashes, 0);
// interpreted in little-endian order.
int verification = Integer.reverseBytes(Ints.fromByteArray(result));
if (expected != verification) {
throw new AssertionError("Expected: " + Integer.toHexString(expected)
+ " got: " + Integer.toHexString(verification));
}
}
static final Funnel<Object> BAD_FUNNEL = new Funnel<Object>() {
@Override public void funnel(Object object, PrimitiveSink bytePrimitiveSink) {
bytePrimitiveSink.putInt(object.hashCode());
}
};
static enum RandomHasherAction {
PUT_BOOLEAN() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
boolean value = random.nextBoolean();
for (PrimitiveSink sink : sinks) {
sink.putBoolean(value);
}
}
},
PUT_BYTE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
int value = random.nextInt();
for (PrimitiveSink sink : sinks) {
sink.putByte((byte) value);
}
}
},
PUT_SHORT() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
short value = (short) random.nextInt();
for (PrimitiveSink sink : sinks) {
sink.putShort(value);
}
}
},
PUT_CHAR() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
char value = (char) random.nextInt();
for (PrimitiveSink sink : sinks) {
sink.putChar(value);
}
}
},
PUT_INT() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
int value = random.nextInt();
for (PrimitiveSink sink : sinks) {
sink.putInt(value);
}
}
},
PUT_LONG() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
long value = random.nextLong();
for (PrimitiveSink sink : sinks) {
sink.putLong(value);
}
}
},
PUT_FLOAT() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
float value = random.nextFloat();
for (PrimitiveSink sink : sinks) {
sink.putFloat(value);
}
}
},
PUT_DOUBLE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
double value = random.nextDouble();
for (PrimitiveSink sink : sinks) {
sink.putDouble(value);
}
}
},
PUT_BYTES() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
byte[] value = new byte[random.nextInt(128)];
random.nextBytes(value);
for (PrimitiveSink sink : sinks) {
sink.putBytes(value);
}
}
},
PUT_BYTES_INT_INT() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
byte[] value = new byte[random.nextInt(128)];
random.nextBytes(value);
int off = random.nextInt(value.length + 1);
int len = random.nextInt(value.length - off + 1);
for (PrimitiveSink sink : sinks) {
sink.putBytes(value);
}
}
},
PUT_STRING() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
char[] value = new char[random.nextInt(128)];
for (int i = 0; i < value.length; i++) {
value[i] = (char) random.nextInt();
}
String s = new String(value);
for (PrimitiveSink sink : sinks) {
sink.putUnencodedChars(s);
}
}
},
PUT_STRING_LOW_SURROGATE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
String s = new String(new char[] { randomLowSurrogate(random) });
for (PrimitiveSink sink : sinks) {
sink.putUnencodedChars(s);
}
}
},
PUT_STRING_HIGH_SURROGATE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
String s = new String(new char[] { randomHighSurrogate(random) });
for (PrimitiveSink sink : sinks) {
sink.putUnencodedChars(s);
}
}
},
PUT_STRING_LOW_HIGH_SURROGATE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
String s = new String(new char[] {
randomLowSurrogate(random), randomHighSurrogate(random)});
for (PrimitiveSink sink : sinks) {
sink.putUnencodedChars(s);
}
}
},
PUT_STRING_HIGH_LOW_SURROGATE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
String s = new String(new char[] {
randomHighSurrogate(random), randomLowSurrogate(random)});
for (PrimitiveSink sink : sinks) {
sink.putUnencodedChars(s);
}
}
};
abstract void performAction(Random random, Iterable<? extends PrimitiveSink> sinks);
private static final RandomHasherAction[] actions = values();
static RandomHasherAction pickAtRandom(Random random) {
return actions[random.nextInt(actions.length)];
}
}
/**
* Test that the hash function contains no funnels. A funnel is a situation where a set of input
* (key) bits 'affects' a strictly smaller set of output bits. Funneling is bad because it can
* result in more-than-ideal collisions for a non-uniformly distributed key space. In practice,
* most key spaces are ANYTHING BUT uniformly distributed. A bit(i) in the input is said to
* 'affect' a bit(j) in the output if two inputs, identical but for bit(i), will differ at output
* bit(j) about half the time
*
* <p>Funneling is pretty simple to detect. The key idea is to find example keys which
* unequivocably demonstrate that funneling cannot be occuring. This is done bit-by-bit. For
* each input bit(i) and output bit(j), two pairs of keys must be found with all bits identical
* except bit(i). One pair must differ in output bit(j), and one pair must not. This proves that
* input bit(i) can alter output bit(j).
*/
static void checkNoFunnels(HashFunction function) {
Random rand = new Random(0);
int keyBits = 32;
int hashBits = function.bits();
// output loop tests input bit
for (int i = 0; i < keyBits; i++) {
int same = 0x0; // bitset for output bits with same values
int diff = 0x0; // bitset for output bits with different values
int count = 0;
// originally was 2 * Math.log(...), making it try more times to avoid flakiness issues
int maxCount = (int) (4 * Math.log(2 * keyBits * hashBits) + 1);
while (same != 0xffffffff || diff != 0xffffffff) {
int key1 = rand.nextInt();
// flip input bit for key2
int key2 = key1 ^ (1 << i);
// get hashes
int hash1 = function.hashInt(key1).asInt();
int hash2 = function.hashInt(key2).asInt();
// test whether the hash values have same output bits
same |= ~(hash1 ^ hash2);
// test whether the hash values have different output bits
diff |= (hash1 ^ hash2);
count++;
// check whether we've exceeded the probabilistically
// likely number of trials to have proven no funneling
if (count > maxCount) {
Assert.fail("input bit(" + i + ") was found not to affect all " +
hashBits + " output bits; The unaffected bits are " +
"as follows: " + ~(same & diff) + ". This was " +
"determined after " + count + " trials.");
}
}
}
}
/**
* Test for avalanche. Avalanche means that output bits differ with roughly 1/2 probability on
* different input keys. This test verifies that each possible 1-bit key delta achieves avalanche.
*
* <p>For more information: http://burtleburtle.net/bob/hash/avalanche.html
*/
static void checkAvalanche(HashFunction function, int trials, double epsilon) {
Random rand = new Random(0);
int keyBits = 32;
int hashBits = function.bits();
for (int i = 0; i < keyBits; i++) {
int[] same = new int[hashBits];
int[] diff = new int[hashBits];
// go through trials to compute probability
for (int j = 0; j < trials; j++) {
int key1 = rand.nextInt();
// flip input bit for key2
int key2 = key1 ^ (1 << i);
// compute hash values
int hash1 = function.hashInt(key1).asInt();
int hash2 = function.hashInt(key2).asInt();
for (int k = 0; k < hashBits; k++) {
if ((hash1 & (1 << k)) == (hash2 & (1 << k))) {
same[k] += 1;
} else {
diff[k] += 1;
}
}
}
// measure probability and assert it's within margin of error
for (int j = 0; j < hashBits; j++) {
double prob = (double) diff[j] / (double) (diff[j] + same[j]);
Assert.assertEquals(0.50d, prob, epsilon);
}
}
}
/**
* Test for 2-bit characteristics. A characteristic is a delta in the input which is repeated in
* the output. For example, if f() is a block cipher and c is a characteristic, then
* f(x^c) = f(x)^c with greater than expected probability. The test for funneling is merely a test
* for 1-bit characteristics.
*
* <p>There is more general code provided by Bob Jenkins to test arbitrarily sized characteristics
* using the magic of gaussian elimination: http://burtleburtle.net/bob/crypto/findingc.html.
*/
static void checkNo2BitCharacteristics(HashFunction function) {
Random rand = new Random(0);
int keyBits = 32;
// get every one of (keyBits choose 2) deltas:
for (int i = 0; i < keyBits; i++) {
for (int j = 0; j < keyBits; j++) {
if (j <= i) continue;
int count = 0;
int maxCount = 20; // the probability of error here is miniscule
boolean diff = false;
while (diff == false) {
int delta = (1 << i) | (1 << j);
int key1 = rand.nextInt();
// apply delta
int key2 = key1 ^ delta;
// get hashes
int hash1 = function.hashInt(key1).asInt();
int hash2 = function.hashInt(key2).asInt();
// this 2-bit candidate delta is not a characteristic
// if deltas are different
if ((hash1 ^ hash2) != delta) {
diff = true;
continue;
}
// check if we've exceeded the probabilistically
// likely number of trials to have proven 2-bit candidate
// is not a characteristic
count++;
if (count > maxCount) {
Assert.fail("2-bit delta (" + i + ", " + j + ") is likely a " +
"characteristic for this hash. This was " +
"determined after " + count + " trials");
}
}
}
}
}
/**
* Test for avalanche with 2-bit deltas. Most probabilities of output bit(j) differing are well
* within 50%.
*/
static void check2BitAvalanche(HashFunction function, int trials, double epsilon) {
Random rand = new Random(0);
int keyBits = 32;
int hashBits = function.bits();
for (int bit1 = 0; bit1 < keyBits; bit1++) {
for (int bit2 = 0; bit2 < keyBits; bit2++) {
if (bit2 <= bit1) continue;
int delta = (1 << bit1) | (1 << bit2);
int[] same = new int[hashBits];
int[] diff = new int[hashBits];
// go through trials to compute probability
for (int j = 0; j < trials; j++) {
int key1 = rand.nextInt();
// flip input bit for key2
int key2 = key1 ^ delta;
// compute hash values
int hash1 = function.hashInt(key1).asInt();
int hash2 = function.hashInt(key2).asInt();
for (int k = 0; k < hashBits; k++) {
if ((hash1 & (1 << k)) == (hash2 & (1 << k))) {
same[k] += 1;
} else {
diff[k] += 1;
}
}
}
// measure probability and assert it's within margin of error
for (int j = 0; j < hashBits; j++) {
double prob = (double) diff[j] / (double) (diff[j] + same[j]);
Assert.assertEquals(0.50d, prob, epsilon);
}
}
}
}
/**
* Checks that a Hasher returns the same HashCode when given the same input, and also
* that the collision rate looks sane.
*/
static void assertInvariants(HashFunction hashFunction) {
int objects = 100;
Set<HashCode> hashcodes = Sets.newHashSetWithExpectedSize(objects);
for (int i = 0; i < objects; i++) {
Object o = new Object();
HashCode hashcode1 = hashFunction.hashObject(o, HashTestUtils.BAD_FUNNEL);
HashCode hashcode2 = hashFunction.hashObject(o, HashTestUtils.BAD_FUNNEL);
Assert.assertEquals(hashcode1, hashcode2); // idempotent
Assert.assertEquals(hashFunction.bits(), hashcode1.bits());
Assert.assertEquals(hashFunction.bits(), hashcode1.asBytes().length * 8);
hashcodes.add(hashcode1);
}
Assert.assertTrue(hashcodes.size() > objects * 0.95); // quite relaxed test
assertHashBytesThrowsCorrectExceptions(hashFunction);
assertIndependentHashers(hashFunction);
assertShortcutsAreEquivalent(hashFunction, 512);
}
static void assertHashBytesThrowsCorrectExceptions(HashFunction hashFunction) {
hashFunction.hashBytes(new byte[64], 0, 0);
try {
hashFunction.hashBytes(new byte[128], -1, 128);
Assert.fail();
} catch (IndexOutOfBoundsException expected) {}
try {
hashFunction.hashBytes(new byte[128], 64, 256 /* too long len */);
Assert.fail();
} catch (IndexOutOfBoundsException expected) {}
try {
hashFunction.hashBytes(new byte[64], 0, -1);
Assert.fail();
} catch (IndexOutOfBoundsException expected) {}
}
static void assertIndependentHashers(HashFunction hashFunction) {
int numActions = 100;
// hashcodes from non-overlapping hash computations
HashCode expected1 = randomHash(hashFunction, new Random(1L), numActions);
HashCode expected2 = randomHash(hashFunction, new Random(2L), numActions);
// equivalent, but overlapping, computations (should produce the same results as above)
Random random1 = new Random(1L);
Random random2 = new Random(2L);
Hasher hasher1 = hashFunction.newHasher();
Hasher hasher2 = hashFunction.newHasher();
for (int i = 0; i < numActions; i++) {
RandomHasherAction.pickAtRandom(random1).performAction(random1, ImmutableSet.of(hasher1));
RandomHasherAction.pickAtRandom(random2).performAction(random2, ImmutableSet.of(hasher2));
}
Assert.assertEquals(expected1, hasher1.hash());
Assert.assertEquals(expected2, hasher2.hash());
}
static HashCode randomHash(HashFunction hashFunction, Random random, int numActions) {
Hasher hasher = hashFunction.newHasher();
for (int i = 0; i < numActions; i++) {
RandomHasherAction.pickAtRandom(random).performAction(random, ImmutableSet.of(hasher));
}
return hasher.hash();
}
private static void assertShortcutsAreEquivalent(HashFunction hashFunction, int trials) {
Random random = new Random(42085L);
for (int i = 0; i < trials; i++) {
assertHashBytesEquivalence(hashFunction, random);
assertHashIntEquivalence(hashFunction, random);
assertHashLongEquivalence(hashFunction, random);
assertHashStringEquivalence(hashFunction, random);
assertHashStringWithSurrogatesEquivalence(hashFunction, random);
}
}
private static void assertHashBytesEquivalence(HashFunction hashFunction, Random random) {
int size = random.nextInt(2048);
byte[] bytes = new byte[size];
random.nextBytes(bytes);
assertEquals(hashFunction.hashBytes(bytes),
hashFunction.newHasher(size).putBytes(bytes).hash());
int off = random.nextInt(size);
int len = random.nextInt(size - off);
assertEquals(hashFunction.hashBytes(bytes, off, len),
hashFunction.newHasher(size).putBytes(bytes, off, len).hash());
}
private static void assertHashIntEquivalence(HashFunction hashFunction, Random random) {
int i = random.nextInt();
assertEquals(hashFunction.hashInt(i),
hashFunction.newHasher().putInt(i).hash());
}
private static void assertHashLongEquivalence(HashFunction hashFunction, Random random) {
long l = random.nextLong();
assertEquals(hashFunction.hashLong(l),
hashFunction.newHasher().putLong(l).hash());
}
private static final ImmutableSet<Charset> CHARSETS = ImmutableSet.of(
Charsets.ISO_8859_1,
Charsets.US_ASCII,
Charsets.UTF_16,
Charsets.UTF_16BE,
Charsets.UTF_16LE,
Charsets.UTF_8);
private static void assertHashStringEquivalence(HashFunction hashFunction, Random random) {
// Test that only data and data-order is important, not the individual operations.
new EqualsTester()
.addEqualityGroup(
hashFunction.hashUnencodedChars("abc"),
hashFunction.newHasher().putUnencodedChars("abc").hash(),
hashFunction.newHasher().putUnencodedChars("ab").putUnencodedChars("c").hash(),
hashFunction.newHasher().putUnencodedChars("a").putUnencodedChars("bc").hash(),
hashFunction.newHasher().putUnencodedChars("a").putUnencodedChars("b")
.putUnencodedChars("c").hash(),
hashFunction.newHasher().putChar('a').putUnencodedChars("bc").hash(),
hashFunction.newHasher().putUnencodedChars("ab").putChar('c').hash(),
hashFunction.newHasher().putChar('a').putChar('b').putChar('c').hash())
.testEquals();
int size = random.nextInt(2048);
byte[] bytes = new byte[size];
random.nextBytes(bytes);
String string = new String(bytes);
assertEquals(hashFunction.hashUnencodedChars(string),
hashFunction.newHasher().putUnencodedChars(string).hash());
for (Charset charset : CHARSETS) {
assertEquals(hashFunction.hashString(string, charset),
hashFunction.newHasher().putString(string, charset).hash());
}
}
/**
* This verifies that putUnencodedChars(String) and hashUnencodedChars(String) are equivalent,
* even for funny strings composed by (possibly unmatched, and mostly illegal) surrogate
* characters. (But doesn't test that they do the right thing - just their consistency).
*/
private static void assertHashStringWithSurrogatesEquivalence(
HashFunction hashFunction, Random random) {
int size = random.nextInt(8) + 1;
char[] chars = new char[size];
for (int i = 0; i < chars.length; i++) {
chars[i] = random.nextBoolean() ? randomLowSurrogate(random) : randomHighSurrogate(random);
}
String string = new String(chars);
assertEquals(hashFunction.hashUnencodedChars(string),
hashFunction.newHasher().putUnencodedChars(string).hash());
}
static char randomLowSurrogate(Random random) {
return (char) (Character.MIN_LOW_SURROGATE
+ random.nextInt(Character.MAX_LOW_SURROGATE - Character.MIN_LOW_SURROGATE + 1));
}
static char randomHighSurrogate(Random random) {
return (char) (Character.MIN_HIGH_SURROGATE
+ random.nextInt(Character.MAX_HIGH_SURROGATE - Character.MIN_HIGH_SURROGATE + 1));
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.ForwardingObject;
import com.google.common.collect.Iterables;
import com.google.common.testing.ForwardingWrapperTester;
import org.easymock.EasyMock;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Tester for typical subclass of {@link ForwardingObject} by using EasyMock partial mocks.
*
* @author Ben Yu
*/
final class ForwardingObjectTester {
private static final Method DELEGATE_METHOD;
static {
try {
DELEGATE_METHOD = ForwardingObject.class.getDeclaredMethod("delegate");
DELEGATE_METHOD.setAccessible(true);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
/**
* Ensures that all interface methods of {@code forwarderClass} are forwarded to the
* {@link ForwardingObject#delegate}. {@code forwarderClass} is assumed to only implement one
* interface.
*/
static <T extends ForwardingObject> void testForwardingObject(final Class<T> forwarderClass) {
@SuppressWarnings("unchecked") // super interface type of T
Class<? super T> interfaceType = (Class<? super T>)
Iterables.getOnlyElement(Arrays.asList(forwarderClass.getInterfaces()));
new ForwardingWrapperTester().testForwarding(interfaceType, new Function<Object, T>() {
@Override public T apply(Object delegate) {
T mock = EasyMock.createMockBuilder(forwarderClass)
.addMockedMethod(DELEGATE_METHOD)
.createMock();
try {
DELEGATE_METHOD.invoke(mock);
} catch (Exception e) {
throw Throwables.propagate(e);
}
EasyMock.expectLastCall().andStubReturn(delegate);
EasyMock.replay(mock);
return mock;
}
});
}
}
| Java |
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
/*
* Source:
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/JSR166TestCase.java?revision=1.90
* (We have made some trivial local modifications (commented out
* uncompilable code).)
*/
package com.google.common.util.concurrent;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import junit.framework.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.security.SecurityPermission;
import java.util.Arrays;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.PropertyPermission;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* Base class for JSR166 Junit TCK tests. Defines some constants,
* utility methods and classes, as well as a simple framework for
* helping to make sure that assertions failing in generated threads
* cause the associated test that generated them to itself fail (which
* JUnit does not otherwise arrange). The rules for creating such
* tests are:
*
* <ol>
*
* <li> All assertions in code running in generated threads must use
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
* #threadAssertEquals}, or {@link #threadAssertNull}, (not
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not
* particularly recommended) for other code to use these forms too.
* Only the most typically used JUnit assertion methods are defined
* this way, but enough to live with.</li>
*
* <li> If you override {@link #setUp} or {@link #tearDown}, make sure
* to invoke {@code super.setUp} and {@code super.tearDown} within
* them. These methods are used to clear and check for thread
* assertion failures.</li>
*
* <li>All delays and timeouts must use one of the constants {@code
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
* {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
* discriminable from zero time, and always allows enough time for the
* small amounts of computation (creating a thread, calling a few
* methods, etc) needed to reach a timeout point. Similarly, a SMALL
* is always discriminable as larger than SHORT and smaller than
* MEDIUM. And so on. These constants are set to conservative values,
* but even so, if there is ever any doubt, they can all be increased
* in one spot to rerun tests on slower platforms.</li>
*
* <li> All threads generated must be joined inside each test case
* method (or {@code fail} to do so) before returning from the
* method. The {@code joinPool} method can be used to do this when
* using Executors.</li>
*
* </ol>
*
* <p> <b>Other notes</b>
* <ul>
*
* <li> Usually, there is one testcase method per JSR166 method
* covering "normal" operation, and then as many exception-testing
* methods as there are exceptions the method can throw. Sometimes
* there are multiple tests per JSR166 method when the different
* "normal" behaviors differ significantly. And sometimes testcases
* cover multiple methods when they cannot be tested in
* isolation.</li>
*
* <li> The documentation style for testcases is to provide as javadoc
* a simple sentence or two describing the property that the testcase
* method purports to test. The javadocs do not say anything about how
* the property is tested. To find out, read the code.</li>
*
* <li> These tests are "conformance tests", and do not attempt to
* test throughput, latency, scalability or other performance factors
* (see the separate "jtreg" tests for a set intended to check these
* for the most central aspects of functionality.) So, most tests use
* the smallest sensible numbers of threads, collection sizes, etc
* needed to check basic conformance.</li>
*
* <li>The test classes currently do not declare inclusion in
* any particular package to simplify things for people integrating
* them in TCK test suites.</li>
*
* <li> As a convenience, the {@code main} of this class (JSR166TestCase)
* runs all JSR166 unit tests.</li>
*
* </ul>
*/
abstract class JSR166TestCase extends TestCase {
private static final boolean useSecurityManager =
Boolean.getBoolean("jsr166.useSecurityManager");
protected static final boolean expensiveTests =
Boolean.getBoolean("jsr166.expensiveTests");
/**
* If true, report on stdout all "slow" tests, that is, ones that
* take more than profileThreshold milliseconds to execute.
*/
private static final boolean profileTests =
Boolean.getBoolean("jsr166.profileTests");
/**
* The number of milliseconds that tests are permitted for
* execution without being reported, when profileTests is set.
*/
private static final long profileThreshold =
Long.getLong("jsr166.profileThreshold", 100);
protected void runTest() throws Throwable {
if (profileTests)
runTestProfiled();
else
super.runTest();
}
protected void runTestProfiled() throws Throwable {
long t0 = System.nanoTime();
try {
super.runTest();
} finally {
long elapsedMillis =
(System.nanoTime() - t0) / (1000L * 1000L);
if (elapsedMillis >= profileThreshold)
System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
}
}
// /**
// * Runs all JSR166 unit tests using junit.textui.TestRunner
// */
// public static void main(String[] args) {
// if (useSecurityManager) {
// System.err.println("Setting a permissive security manager");
// Policy.setPolicy(permissivePolicy());
// System.setSecurityManager(new SecurityManager());
// }
// int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
// Test s = suite();
// for (int i = 0; i < iters; ++i) {
// junit.textui.TestRunner.run(s);
// System.gc();
// System.runFinalization();
// }
// System.exit(0);
// }
// public static TestSuite newTestSuite(Object... suiteOrClasses) {
// TestSuite suite = new TestSuite();
// for (Object suiteOrClass : suiteOrClasses) {
// if (suiteOrClass instanceof TestSuite)
// suite.addTest((TestSuite) suiteOrClass);
// else if (suiteOrClass instanceof Class)
// suite.addTest(new TestSuite((Class<?>) suiteOrClass));
// else
// throw new ClassCastException("not a test suite or class");
// }
// return suite;
// }
// /**
// * Collects all JSR166 unit tests as one suite.
// */
// public static Test suite() {
// return newTestSuite(
// ForkJoinPoolTest.suite(),
// ForkJoinTaskTest.suite(),
// RecursiveActionTest.suite(),
// RecursiveTaskTest.suite(),
// LinkedTransferQueueTest.suite(),
// PhaserTest.suite(),
// ThreadLocalRandomTest.suite(),
// AbstractExecutorServiceTest.suite(),
// AbstractQueueTest.suite(),
// AbstractQueuedSynchronizerTest.suite(),
// AbstractQueuedLongSynchronizerTest.suite(),
// ArrayBlockingQueueTest.suite(),
// ArrayDequeTest.suite(),
// AtomicBooleanTest.suite(),
// AtomicIntegerArrayTest.suite(),
// AtomicIntegerFieldUpdaterTest.suite(),
// AtomicIntegerTest.suite(),
// AtomicLongArrayTest.suite(),
// AtomicLongFieldUpdaterTest.suite(),
// AtomicLongTest.suite(),
// AtomicMarkableReferenceTest.suite(),
// AtomicReferenceArrayTest.suite(),
// AtomicReferenceFieldUpdaterTest.suite(),
// AtomicReferenceTest.suite(),
// AtomicStampedReferenceTest.suite(),
// ConcurrentHashMapTest.suite(),
// ConcurrentLinkedDequeTest.suite(),
// ConcurrentLinkedQueueTest.suite(),
// ConcurrentSkipListMapTest.suite(),
// ConcurrentSkipListSubMapTest.suite(),
// ConcurrentSkipListSetTest.suite(),
// ConcurrentSkipListSubSetTest.suite(),
// CopyOnWriteArrayListTest.suite(),
// CopyOnWriteArraySetTest.suite(),
// CountDownLatchTest.suite(),
// CyclicBarrierTest.suite(),
// DelayQueueTest.suite(),
// EntryTest.suite(),
// ExchangerTest.suite(),
// ExecutorsTest.suite(),
// ExecutorCompletionServiceTest.suite(),
// FutureTaskTest.suite(),
// LinkedBlockingDequeTest.suite(),
// LinkedBlockingQueueTest.suite(),
// LinkedListTest.suite(),
// LockSupportTest.suite(),
// PriorityBlockingQueueTest.suite(),
// PriorityQueueTest.suite(),
// ReentrantLockTest.suite(),
// ReentrantReadWriteLockTest.suite(),
// ScheduledExecutorTest.suite(),
// ScheduledExecutorSubclassTest.suite(),
// SemaphoreTest.suite(),
// SynchronousQueueTest.suite(),
// SystemTest.suite(),
// ThreadLocalTest.suite(),
// ThreadPoolExecutorTest.suite(),
// ThreadPoolExecutorSubclassTest.suite(),
// ThreadTest.suite(),
// TimeUnitTest.suite(),
// TreeMapTest.suite(),
// TreeSetTest.suite(),
// TreeSubMapTest.suite(),
// TreeSubSetTest.suite());
// }
public static long SHORT_DELAY_MS;
public static long SMALL_DELAY_MS;
public static long MEDIUM_DELAY_MS;
public static long LONG_DELAY_MS;
/**
* Returns the shortest timed delay. This could
* be reimplemented to use for example a Property.
*/
protected long getShortDelay() {
return 50;
}
/**
* Sets delays as multiples of SHORT_DELAY.
*/
protected void setDelays() {
SHORT_DELAY_MS = getShortDelay();
SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
LONG_DELAY_MS = SHORT_DELAY_MS * 200;
}
/**
* Returns a timeout in milliseconds to be used in tests that
* verify that operations block or time out.
*/
long timeoutMillis() {
return SHORT_DELAY_MS / 4;
}
/**
* Returns a new Date instance representing a time delayMillis
* milliseconds in the future.
*/
Date delayedDate(long delayMillis) {
return new Date(System.currentTimeMillis() + delayMillis);
}
/**
* The first exception encountered if any threadAssertXXX method fails.
*/
private final AtomicReference<Throwable> threadFailure
= new AtomicReference<Throwable>(null);
/**
* Records an exception so that it can be rethrown later in the test
* harness thread, triggering a test case failure. Only the first
* failure is recorded; subsequent calls to this method from within
* the same test have no effect.
*/
public void threadRecordFailure(Throwable t) {
threadFailure.compareAndSet(null, t);
}
public void setUp() {
setDelays();
}
/**
* Extra checks that get done for all test cases.
*
* Triggers test case failure if any thread assertions have failed,
* by rethrowing, in the test harness thread, any exception recorded
* earlier by threadRecordFailure.
*
* Triggers test case failure if interrupt status is set in the main thread.
*/
public void tearDown() throws Exception {
Throwable t = threadFailure.getAndSet(null);
if (t != null) {
if (t instanceof Error)
throw (Error) t;
else if (t instanceof RuntimeException)
throw (RuntimeException) t;
else if (t instanceof Exception)
throw (Exception) t;
else {
AssertionFailedError afe =
new AssertionFailedError(t.toString());
afe.initCause(t);
throw afe;
}
}
if (Thread.interrupted())
throw new AssertionFailedError("interrupt status set in main thread");
}
/**
* Just like fail(reason), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadFail(String reason) {
try {
fail(reason);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
fail(reason);
}
}
/**
* Just like assertTrue(b), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertTrue(boolean b) {
try {
assertTrue(b);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Just like assertFalse(b), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertFalse(boolean b) {
try {
assertFalse(b);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Just like assertNull(x), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertNull(Object x) {
try {
assertNull(x);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Just like assertEquals(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertEquals(long x, long y) {
try {
assertEquals(x, y);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Just like assertEquals(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertEquals(Object x, Object y) {
try {
assertEquals(x, y);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
/**
* Just like assertSame(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertSame(Object x, Object y) {
try {
assertSame(x, y);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Calls threadFail with message "should throw exception".
*/
public void threadShouldThrow() {
threadFail("should throw exception");
}
/**
* Calls threadFail with message "should throw" + exceptionName.
*/
public void threadShouldThrow(String exceptionName) {
threadFail("should throw " + exceptionName);
}
/**
* Records the given exception using {@link #threadRecordFailure},
* then rethrows the exception, wrapping it in an
* AssertionFailedError if necessary.
*/
public void threadUnexpectedException(Throwable t) {
threadRecordFailure(t);
t.printStackTrace();
if (t instanceof RuntimeException)
throw (RuntimeException) t;
else if (t instanceof Error)
throw (Error) t;
else {
AssertionFailedError afe =
new AssertionFailedError("unexpected exception: " + t);
afe.initCause(t);
throw afe;
}
}
/**
* Delays, via Thread.sleep, for the given millisecond delay, but
* if the sleep is shorter than specified, may re-sleep or yield
* until time elapses.
*/
static void delay(long millis) throws InterruptedException {
long startTime = System.nanoTime();
long ns = millis * 1000 * 1000;
for (;;) {
if (millis > 0L)
Thread.sleep(millis);
else // too short to sleep
Thread.yield();
long d = ns - (System.nanoTime() - startTime);
if (d > 0L)
millis = d / (1000 * 1000);
else
break;
}
}
/**
* Waits out termination of a thread pool or fails doing so.
*/
void joinPool(ExecutorService exec) {
try {
exec.shutdown();
assertTrue("ExecutorService did not terminate in a timely manner",
exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
} catch (SecurityException ok) {
// Allowed in case test doesn't have privs
} catch (InterruptedException ie) {
fail("Unexpected InterruptedException");
}
}
/**
* Checks that thread does not terminate within the default
* millisecond delay of {@code timeoutMillis()}.
*/
void assertThreadStaysAlive(Thread thread) {
assertThreadStaysAlive(thread, timeoutMillis());
}
/**
* Checks that thread does not terminate within the given millisecond delay.
*/
void assertThreadStaysAlive(Thread thread, long millis) {
try {
// No need to optimize the failing case via Thread.join.
delay(millis);
assertTrue(thread.isAlive());
} catch (InterruptedException ie) {
fail("Unexpected InterruptedException");
}
}
/**
* Checks that the threads do not terminate within the default
* millisecond delay of {@code timeoutMillis()}.
*/
void assertThreadsStayAlive(Thread... threads) {
assertThreadsStayAlive(timeoutMillis(), threads);
}
/**
* Checks that the threads do not terminate within the given millisecond delay.
*/
void assertThreadsStayAlive(long millis, Thread... threads) {
try {
// No need to optimize the failing case via Thread.join.
delay(millis);
for (Thread thread : threads)
assertTrue(thread.isAlive());
} catch (InterruptedException ie) {
fail("Unexpected InterruptedException");
}
}
/**
* Checks that future.get times out, with the default timeout of
* {@code timeoutMillis()}.
*/
void assertFutureTimesOut(Future future) {
assertFutureTimesOut(future, timeoutMillis());
}
/**
* Checks that future.get times out, with the given millisecond timeout.
*/
void assertFutureTimesOut(Future future, long timeoutMillis) {
long startTime = System.nanoTime();
try {
future.get(timeoutMillis, MILLISECONDS);
shouldThrow();
} catch (TimeoutException success) {
} catch (Exception e) {
threadUnexpectedException(e);
} finally { future.cancel(true); }
assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
}
/**
* Fails with message "should throw exception".
*/
public void shouldThrow() {
fail("Should throw exception");
}
/**
* Fails with message "should throw " + exceptionName.
*/
public void shouldThrow(String exceptionName) {
fail("Should throw " + exceptionName);
}
/**
* The number of elements to place in collections, arrays, etc.
*/
public static final int SIZE = 20;
// Some convenient Integer constants
public static final Integer zero = new Integer(0);
public static final Integer one = new Integer(1);
public static final Integer two = new Integer(2);
public static final Integer three = new Integer(3);
public static final Integer four = new Integer(4);
public static final Integer five = new Integer(5);
public static final Integer six = new Integer(6);
public static final Integer seven = new Integer(7);
public static final Integer eight = new Integer(8);
public static final Integer nine = new Integer(9);
public static final Integer m1 = new Integer(-1);
public static final Integer m2 = new Integer(-2);
public static final Integer m3 = new Integer(-3);
public static final Integer m4 = new Integer(-4);
public static final Integer m5 = new Integer(-5);
public static final Integer m6 = new Integer(-6);
public static final Integer m10 = new Integer(-10);
/**
* Runs Runnable r with a security policy that permits precisely
* the specified permissions. If there is no current security
* manager, the runnable is run twice, both with and without a
* security manager. We require that any security manager permit
* getPolicy/setPolicy.
*/
public void runWithPermissions(Runnable r, Permission... permissions) {
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
r.run();
Policy savedPolicy = Policy.getPolicy();
try {
Policy.setPolicy(permissivePolicy());
System.setSecurityManager(new SecurityManager());
runWithPermissions(r, permissions);
} finally {
System.setSecurityManager(null);
Policy.setPolicy(savedPolicy);
}
} else {
Policy savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy(permissions);
Policy.setPolicy(policy);
try {
r.run();
} finally {
policy.addPermission(new SecurityPermission("setPolicy"));
Policy.setPolicy(savedPolicy);
}
}
}
/**
* Runs a runnable without any permissions.
*/
public void runWithoutPermissions(Runnable r) {
runWithPermissions(r);
}
/**
* A security policy where new permissions can be dynamically added
* or all cleared.
*/
public static class AdjustablePolicy extends java.security.Policy {
Permissions perms = new Permissions();
AdjustablePolicy(Permission... permissions) {
for (Permission permission : permissions)
perms.add(permission);
}
void addPermission(Permission perm) { perms.add(perm); }
void clearPermissions() { perms = new Permissions(); }
public PermissionCollection getPermissions(CodeSource cs) {
return perms;
}
public PermissionCollection getPermissions(ProtectionDomain pd) {
return perms;
}
public boolean implies(ProtectionDomain pd, Permission p) {
return perms.implies(p);
}
public void refresh() {}
}
/**
* Returns a policy containing all the permissions we ever need.
*/
public static Policy permissivePolicy() {
return new AdjustablePolicy
// Permissions j.u.c. needs directly
(new RuntimePermission("modifyThread"),
new RuntimePermission("getClassLoader"),
new RuntimePermission("setContextClassLoader"),
// Permissions needed to change permissions!
new SecurityPermission("getPolicy"),
new SecurityPermission("setPolicy"),
new RuntimePermission("setSecurityManager"),
// Permissions needed by the junit test harness
new RuntimePermission("accessDeclaredMembers"),
new PropertyPermission("*", "read"),
new java.io.FilePermission("<<ALL FILES>>", "read"));
}
/**
* Sleeps until the given time has elapsed.
* Throws AssertionFailedError if interrupted.
*/
void sleep(long millis) {
try {
delay(millis);
} catch (InterruptedException ie) {
AssertionFailedError afe =
new AssertionFailedError("Unexpected InterruptedException");
afe.initCause(ie);
throw afe;
}
}
/**
* Spin-waits up to the specified number of milliseconds for the given
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
*/
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
long startTime = System.nanoTime();
for (;;) {
Thread.State s = thread.getState();
if (s == Thread.State.BLOCKED ||
s == Thread.State.WAITING ||
s == Thread.State.TIMED_WAITING)
return;
else if (s == Thread.State.TERMINATED)
fail("Unexpected thread termination");
else if (millisElapsedSince(startTime) > timeoutMillis) {
threadAssertTrue(thread.isAlive());
return;
}
Thread.yield();
}
}
/**
* Waits up to LONG_DELAY_MS for the given thread to enter a wait
* state: BLOCKED, WAITING, or TIMED_WAITING.
*/
void waitForThreadToEnterWaitState(Thread thread) {
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
}
/**
* Returns the number of milliseconds since time given by
* startNanoTime, which must have been previously returned from a
* call to {@link System.nanoTime()}.
*/
long millisElapsedSince(long startNanoTime) {
return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
}
/**
* Returns a new started daemon Thread running the given runnable.
*/
Thread newStartedThread(Runnable runnable) {
Thread t = new Thread(runnable);
t.setDaemon(true);
t.start();
return t;
}
/**
* Waits for the specified time (in milliseconds) for the thread
* to terminate (using {@link Thread#join(long)}), else interrupts
* the thread (in the hope that it may terminate later) and fails.
*/
void awaitTermination(Thread t, long timeoutMillis) {
try {
t.join(timeoutMillis);
} catch (InterruptedException ie) {
threadUnexpectedException(ie);
} finally {
if (t.getState() != Thread.State.TERMINATED) {
t.interrupt();
fail("Test timed out");
}
}
}
/**
* Waits for LONG_DELAY_MS milliseconds for the thread to
* terminate (using {@link Thread#join(long)}), else interrupts
* the thread (in the hope that it may terminate later) and fails.
*/
void awaitTermination(Thread t) {
awaitTermination(t, LONG_DELAY_MS);
}
// Some convenient Runnable classes
public abstract class CheckedRunnable implements Runnable {
protected abstract void realRun() throws Throwable;
public final void run() {
try {
realRun();
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
}
public abstract class RunnableShouldThrow implements Runnable {
protected abstract void realRun() throws Throwable;
final Class<?> exceptionClass;
<T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
this.exceptionClass = exceptionClass;
}
public final void run() {
try {
realRun();
threadShouldThrow(exceptionClass.getSimpleName());
} catch (Throwable t) {
if (! exceptionClass.isInstance(t))
threadUnexpectedException(t);
}
}
}
public abstract class ThreadShouldThrow extends Thread {
protected abstract void realRun() throws Throwable;
final Class<?> exceptionClass;
<T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
this.exceptionClass = exceptionClass;
}
public final void run() {
try {
realRun();
threadShouldThrow(exceptionClass.getSimpleName());
} catch (Throwable t) {
if (! exceptionClass.isInstance(t))
threadUnexpectedException(t);
}
}
}
public abstract class CheckedInterruptedRunnable implements Runnable {
protected abstract void realRun() throws Throwable;
public final void run() {
try {
realRun();
threadShouldThrow("InterruptedException");
} catch (InterruptedException success) {
threadAssertFalse(Thread.interrupted());
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
}
public abstract class CheckedCallable<T> implements Callable<T> {
protected abstract T realCall() throws Throwable;
public final T call() {
try {
return realCall();
} catch (Throwable t) {
threadUnexpectedException(t);
return null;
}
}
}
public abstract class CheckedInterruptedCallable<T>
implements Callable<T> {
protected abstract T realCall() throws Throwable;
public final T call() {
try {
T result = realCall();
threadShouldThrow("InterruptedException");
return result;
} catch (InterruptedException success) {
threadAssertFalse(Thread.interrupted());
} catch (Throwable t) {
threadUnexpectedException(t);
}
return null;
}
}
public static class NoOpRunnable implements Runnable {
public void run() {}
}
public static class NoOpCallable implements Callable {
public Object call() { return Boolean.TRUE; }
}
public static final String TEST_STRING = "a test string";
public static class StringTask implements Callable<String> {
public String call() { return TEST_STRING; }
}
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
return new CheckedCallable<String>() {
protected String realCall() {
try {
latch.await();
} catch (InterruptedException quittingTime) {}
return TEST_STRING;
}};
}
public Runnable awaiter(final CountDownLatch latch) {
return new CheckedRunnable() {
public void realRun() throws InterruptedException {
await(latch);
}};
}
public void await(CountDownLatch latch) {
try {
assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
public void await(Semaphore semaphore) {
try {
assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
// /**
// * Spin-waits up to LONG_DELAY_MS until flag becomes true.
// */
// public void await(AtomicBoolean flag) {
// await(flag, LONG_DELAY_MS);
// }
// /**
// * Spin-waits up to the specified timeout until flag becomes true.
// */
// public void await(AtomicBoolean flag, long timeoutMillis) {
// long startTime = System.nanoTime();
// while (!flag.get()) {
// if (millisElapsedSince(startTime) > timeoutMillis)
// throw new AssertionFailedError("timed out");
// Thread.yield();
// }
// }
public static class NPETask implements Callable<String> {
public String call() { throw new NullPointerException(); }
}
public static class CallableOne implements Callable<Integer> {
public Integer call() { return one; }
}
public class ShortRunnable extends CheckedRunnable {
protected void realRun() throws Throwable {
delay(SHORT_DELAY_MS);
}
}
public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
protected void realRun() throws InterruptedException {
delay(SHORT_DELAY_MS);
}
}
public class SmallRunnable extends CheckedRunnable {
protected void realRun() throws Throwable {
delay(SMALL_DELAY_MS);
}
}
public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
protected void realRun() {
try {
delay(SMALL_DELAY_MS);
} catch (InterruptedException ok) {}
}
}
public class SmallCallable extends CheckedCallable {
protected Object realCall() throws InterruptedException {
delay(SMALL_DELAY_MS);
return Boolean.TRUE;
}
}
public class MediumRunnable extends CheckedRunnable {
protected void realRun() throws Throwable {
delay(MEDIUM_DELAY_MS);
}
}
public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
protected void realRun() throws InterruptedException {
delay(MEDIUM_DELAY_MS);
}
}
public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
return new CheckedRunnable() {
protected void realRun() {
try {
delay(timeoutMillis);
} catch (InterruptedException ok) {}
}};
}
public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
protected void realRun() {
try {
delay(MEDIUM_DELAY_MS);
} catch (InterruptedException ok) {}
}
}
public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
protected void realRun() {
try {
delay(LONG_DELAY_MS);
} catch (InterruptedException ok) {}
}
}
/**
* For use as ThreadFactory in constructors
*/
public static class SimpleThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new Thread(r);
}
}
public interface TrackedRunnable extends Runnable {
boolean isDone();
}
public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
return new TrackedRunnable() {
private volatile boolean done = false;
public boolean isDone() { return done; }
public void run() {
try {
delay(timeoutMillis);
done = true;
} catch (InterruptedException ok) {}
}
};
}
public static class TrackedShortRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
try {
delay(SHORT_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
}
}
public static class TrackedSmallRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
try {
delay(SMALL_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
}
}
public static class TrackedMediumRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
try {
delay(MEDIUM_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
}
}
public static class TrackedLongRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
try {
delay(LONG_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
}
}
public static class TrackedNoOpRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
done = true;
}
}
public static class TrackedCallable implements Callable {
public volatile boolean done = false;
public Object call() {
try {
delay(SMALL_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
return Boolean.TRUE;
}
}
// /**
// * Analog of CheckedRunnable for RecursiveAction
// */
// public abstract class CheckedRecursiveAction extends RecursiveAction {
// protected abstract void realCompute() throws Throwable;
// public final void compute() {
// try {
// realCompute();
// } catch (Throwable t) {
// threadUnexpectedException(t);
// }
// }
// }
// /**
// * Analog of CheckedCallable for RecursiveTask
// */
// public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
// protected abstract T realCompute() throws Throwable;
// public final T compute() {
// try {
// return realCompute();
// } catch (Throwable t) {
// threadUnexpectedException(t);
// return null;
// }
// }
// }
/**
* For use as RejectedExecutionHandler in constructors
*/
public static class NoOpREHandler implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r,
ThreadPoolExecutor executor) {}
}
/**
* A CyclicBarrier that uses timed await and fails with
* AssertionFailedErrors instead of throwing checked exceptions.
*/
public class CheckedBarrier extends CyclicBarrier {
public CheckedBarrier(int parties) { super(parties); }
public int await() {
try {
return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
} catch (TimeoutException e) {
throw new AssertionFailedError("timed out");
} catch (Exception e) {
AssertionFailedError afe =
new AssertionFailedError("Unexpected exception: " + e);
afe.initCause(e);
throw afe;
}
}
}
void checkEmpty(BlockingQueue q) {
try {
assertTrue(q.isEmpty());
assertEquals(0, q.size());
assertNull(q.peek());
assertNull(q.poll());
assertNull(q.poll(0, MILLISECONDS));
assertEquals(q.toString(), "[]");
assertTrue(Arrays.equals(q.toArray(), new Object[0]));
assertFalse(q.iterator().hasNext());
try {
q.element();
shouldThrow();
} catch (NoSuchElementException success) {}
try {
q.iterator().next();
shouldThrow();
} catch (NoSuchElementException success) {}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success) {}
} catch (InterruptedException ie) {
threadUnexpectedException(ie);
}
}
@SuppressWarnings("unchecked")
<T> T serialClone(T o) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(o);
oos.flush();
oos.close();
ObjectInputStream ois = new ObjectInputStream
(new ByteArrayInputStream(bos.toByteArray()));
T clone = (T) ois.readObject();
assertSame(o.getClass(), clone.getClass());
return clone;
} catch (Throwable t) {
threadUnexpectedException(t);
return null;
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Used to test listenable future implementations.
*
* @author Sven Mawson
*/
public class ListenableFutureTester {
private final ExecutorService exec;
private final ListenableFuture<?> future;
private final CountDownLatch latch;
public ListenableFutureTester(ListenableFuture<?> future) {
this.exec = Executors.newCachedThreadPool();
this.future = checkNotNull(future);
this.latch = new CountDownLatch(1);
}
public void setUp() {
future.addListener(new Runnable() {
@Override public void run() {
latch.countDown();
}
}, exec);
assertEquals(1, latch.getCount());
assertFalse(future.isDone());
assertFalse(future.isCancelled());
}
public void tearDown() {
exec.shutdown();
}
public void testCompletedFuture(@Nullable Object expectedValue)
throws InterruptedException, ExecutionException {
assertTrue(future.isDone());
assertFalse(future.isCancelled());
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(future.isDone());
assertFalse(future.isCancelled());
assertEquals(expectedValue, future.get());
}
public void testCancelledFuture()
throws InterruptedException, ExecutionException {
assertTrue(future.isDone());
assertTrue(future.isCancelled());
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(future.isDone());
assertTrue(future.isCancelled());
try {
future.get();
fail("Future should throw CancellationException on cancel.");
} catch (CancellationException expected) {}
}
public void testFailedFuture(@Nullable String message)
throws InterruptedException {
assertTrue(future.isDone());
assertFalse(future.isCancelled());
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(future.isDone());
assertFalse(future.isCancelled());
try {
future.get();
fail("Future should rethrow the exception.");
} catch (ExecutionException e) {
assertEquals(message, e.getCause().getMessage());
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static junit.framework.Assert.fail;
import com.google.common.testing.TearDown;
import com.google.common.testing.TearDownAccepter;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
* Utilities for performing thread interruption in tests
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
final class InterruptionUtil {
private static final Logger logger =
Logger.getLogger(InterruptionUtil.class.getName());
/**
* Runnable which will interrupt the target thread repeatedly when run.
*/
private static final class Interruptenator implements Runnable {
private final long everyMillis;
private final Thread interruptee;
private volatile boolean shouldStop = false;
Interruptenator(Thread interruptee, long everyMillis) {
this.everyMillis = everyMillis;
this.interruptee = interruptee;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(everyMillis);
} catch (InterruptedException e) {
// ok. just stop sleeping.
}
if (shouldStop) {
break;
}
interruptee.interrupt();
}
}
void stopInterrupting() {
shouldStop = true;
}
}
/**
* Interrupts the current thread after sleeping for the specified delay.
*/
static void requestInterruptIn(final long time, final TimeUnit unit) {
checkNotNull(unit);
final Thread interruptee = Thread.currentThread();
new Thread(new Runnable() {
@Override
public void run() {
try {
unit.sleep(time);
} catch (InterruptedException wontHappen) {
throw new AssertionError(wontHappen);
}
interruptee.interrupt();
}
}).start();
}
static void repeatedlyInterruptTestThread(
long interruptPeriodMillis, TearDownAccepter tearDownAccepter) {
final Interruptenator interruptingTask =
new Interruptenator(Thread.currentThread(), interruptPeriodMillis);
final Thread interruptingThread = new Thread(interruptingTask);
interruptingThread.start();
tearDownAccepter.addTearDown(new TearDown() {
@Override public void tearDown() throws Exception {
interruptingTask.stopInterrupting();
interruptingThread.interrupt();
joinUninterruptibly(interruptingThread, 2500, MILLISECONDS);
Thread.interrupted();
if (interruptingThread.isAlive()) {
// This will be hidden by test-output redirection:
logger.severe(
"InterruptenatorTask did not exit; future tests may be affected");
/*
* This won't do any good under JUnit 3, but I'll leave it around in
* case we ever switch to JUnit 4:
*/
fail();
}
}
});
}
// TODO(cpovirk): promote to Uninterruptibles, and add untimed version
private static void joinUninterruptibly(
Thread thread, long timeout, TimeUnit unit) {
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(timeout);
long end = System.nanoTime() + remainingNanos;
while (true) {
try {
// TimeUnit.timedJoin() treats negative timeouts just like zero.
NANOSECONDS.timedJoin(thread, remainingNanos);
return;
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import java.io.File;
import java.io.IOException;
/**
* A test factory for byte or char sources or sinks. In addition to creating sources or sinks, the
* factory specifies what content should be expected to be read from a source or contained in a sink
* given the content data that was used to create the source or that was written to the sink.
*
* <p>A single {@code SourceSinkFactory} implementation generally corresponds to one specific way of
* creating a source or sink, such as {@link Files#asByteSource(File)}. Implementations of
* {@code SourceSinkFactory} for common.io are found in {@link SourceSinkFactories}.
*
* @param <S> the source or sink type
* @param <T> the data type (byte[] or String)
* @author Colin Decker
*/
public interface SourceSinkFactory<S, T> {
/**
* Returns the data to expect the source or sink to contain given the data that was used to create
* the source or written to the sink. Typically, this will just return the input directly, but in
* some cases it may alter the input. For example, if the factory returns a sliced view of a
* source created with some given bytes, this method would return a subsequence of the given
* (byte[]) data.
*/
T getExpected(T data);
/**
* Cleans up anything created when creating the source or sink.
*/
public abstract void tearDown() throws IOException;
/**
* Factory for byte or char sources.
*/
public interface SourceFactory<S, T> extends SourceSinkFactory<S, T> {
/**
* Creates a new source containing some or all of the given data.
*/
S createSource(T data) throws IOException;
}
/**
* Factory for byte or char sinks.
*/
public interface SinkFactory<S, T> extends SourceSinkFactory<S, T> {
/**
* Creates a new sink.
*/
S createSink() throws IOException;
/**
* Gets the current content of the created sink.
*/
T getSinkContents() throws IOException;
}
/**
* Factory for {@link ByteSource} instances.
*/
public interface ByteSourceFactory extends SourceFactory<ByteSource, byte[]> {
}
/**
* Factory for {@link ByteSink} instances.
*/
public interface ByteSinkFactory extends SinkFactory<ByteSink, byte[]> {
}
/**
* Factory for {@link CharSource} instances.
*/
public interface CharSourceFactory extends SourceFactory<CharSource, String> {
}
/**
* Factory for {@link CharSink} instances.
*/
public interface CharSinkFactory extends SinkFactory<CharSink, String> {
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.SourceSinkFactory.ByteSinkFactory;
import static com.google.common.io.SourceSinkFactory.ByteSourceFactory;
import static com.google.common.io.SourceSinkFactory.CharSinkFactory;
import static com.google.common.io.SourceSinkFactory.CharSourceFactory;
import com.google.common.base.Charsets;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* {@link SourceSinkFactory} implementations.
*
* @author Colin Decker
*/
public class SourceSinkFactories {
private SourceSinkFactories() {}
public static CharSourceFactory stringCharSourceFactory() {
return new StringSourceFactory();
}
public static ByteSourceFactory byteArraySourceFactory() {
return new ByteArraySourceFactory();
}
public static ByteSourceFactory emptyByteSourceFactory() {
return new EmptyByteSourceFactory();
}
public static CharSourceFactory emptyCharSourceFactory() {
return new EmptyCharSourceFactory();
}
public static ByteSourceFactory fileByteSourceFactory() {
return new FileByteSourceFactory();
}
public static ByteSinkFactory fileByteSinkFactory() {
return new FileByteSinkFactory(null);
}
public static ByteSinkFactory appendingFileByteSinkFactory() {
String initialString = IoTestCase.ASCII + IoTestCase.I18N;
return new FileByteSinkFactory(initialString.getBytes(Charsets.UTF_8));
}
public static CharSourceFactory fileCharSourceFactory() {
return new FileCharSourceFactory();
}
public static CharSinkFactory fileCharSinkFactory() {
return new FileCharSinkFactory(null);
}
public static CharSinkFactory appendingFileCharSinkFactory() {
String initialString = IoTestCase.ASCII + IoTestCase.I18N;
return new FileCharSinkFactory(initialString);
}
public static ByteSourceFactory urlByteSourceFactory() {
return new UrlByteSourceFactory();
}
public static CharSourceFactory urlCharSourceFactory() {
return new UrlCharSourceFactory();
}
public static CharSourceFactory asCharSourceFactory(final ByteSourceFactory factory) {
checkNotNull(factory);
return new CharSourceFactory() {
@Override
public CharSource createSource(String string) throws IOException {
return factory.createSource(string.getBytes(Charsets.UTF_8))
.asCharSource(Charsets.UTF_8);
}
@Override
public String getExpected(String data) {
return new String(factory.getExpected(data.getBytes(Charsets.UTF_8)), Charsets.UTF_8);
}
@Override
public void tearDown() throws IOException {
factory.tearDown();
}
};
}
public static CharSinkFactory asCharSinkFactory(final ByteSinkFactory factory) {
checkNotNull(factory);
return new CharSinkFactory() {
@Override
public CharSink createSink() throws IOException {
return factory.createSink().asCharSink(Charsets.UTF_8);
}
@Override
public String getSinkContents() throws IOException {
return new String(factory.getSinkContents(), Charsets.UTF_8);
}
@Override
public String getExpected(String data) {
/*
* Get what the byte sink factory would expect for no written bytes, then append expected
* string to that.
*/
byte[] factoryExpectedForNothing = factory.getExpected(new byte[0]);
return new String(factoryExpectedForNothing, Charsets.UTF_8) + checkNotNull(data);
}
@Override
public void tearDown() throws IOException {
factory.tearDown();
}
};
}
public static ByteSourceFactory asSlicedByteSourceFactory(final ByteSourceFactory factory,
final int off, final int len) {
checkNotNull(factory);
return new ByteSourceFactory() {
@Override
public ByteSource createSource(byte[] bytes) throws IOException {
return factory.createSource(bytes).slice(off, len);
}
@Override
public byte[] getExpected(byte[] bytes) {
byte[] baseExpected = factory.getExpected(bytes);
return Arrays.copyOfRange(baseExpected, off, Math.min(baseExpected.length, off + len));
}
@Override
public void tearDown() throws IOException {
factory.tearDown();
}
};
}
private static class StringSourceFactory implements CharSourceFactory {
@Override
public CharSource createSource(String data) throws IOException {
return CharSource.wrap(data);
}
@Override
public String getExpected(String data) {
return data;
}
@Override
public void tearDown() throws IOException {
}
}
private static class ByteArraySourceFactory implements ByteSourceFactory {
@Override
public ByteSource createSource(byte[] bytes) throws IOException {
return ByteSource.wrap(bytes);
}
@Override
public byte[] getExpected(byte[] bytes) {
return bytes;
}
@Override
public void tearDown() throws IOException {
}
}
private static class EmptyCharSourceFactory implements CharSourceFactory {
@Override
public CharSource createSource(String data) throws IOException {
return CharSource.empty();
}
@Override
public String getExpected(String data) {
return "";
}
@Override
public void tearDown() throws IOException {
}
}
private static class EmptyByteSourceFactory implements ByteSourceFactory {
@Override
public ByteSource createSource(byte[] bytes) throws IOException {
return ByteSource.empty();
}
@Override
public byte[] getExpected(byte[] bytes) {
return new byte[0];
}
@Override
public void tearDown() throws IOException {
}
}
private abstract static class FileFactory {
private static final Logger logger = Logger.getLogger(FileFactory.class.getName());
private final ThreadLocal<File> fileThreadLocal = new ThreadLocal<File>();
protected File createFile() throws IOException {
File file = File.createTempFile("SinkSourceFile", "txt");
fileThreadLocal.set(file);
return file;
}
protected File getFile() {
return fileThreadLocal.get();
}
public final void tearDown() throws IOException {
if (!fileThreadLocal.get().delete()) {
logger.warning("Unable to delete file: " + fileThreadLocal.get());
}
fileThreadLocal.remove();
}
}
private static class FileByteSourceFactory extends FileFactory implements ByteSourceFactory {
@Override
public ByteSource createSource(byte[] bytes) throws IOException {
checkNotNull(bytes);
File file = createFile();
OutputStream out = new FileOutputStream(file);
try {
out.write(bytes);
} finally {
out.close();
}
return Files.asByteSource(file);
}
@Override
public byte[] getExpected(byte[] bytes) {
return checkNotNull(bytes);
}
}
private static class FileByteSinkFactory extends FileFactory implements ByteSinkFactory {
private final byte[] initialBytes;
private FileByteSinkFactory(@Nullable byte[] initialBytes) {
this.initialBytes = initialBytes;
}
@Override
public ByteSink createSink() throws IOException {
File file = createFile();
if (initialBytes != null) {
FileOutputStream out = new FileOutputStream(file);
try {
out.write(initialBytes);
} finally {
out.close();
}
return Files.asByteSink(file, FileWriteMode.APPEND);
}
return Files.asByteSink(file);
}
@Override
public byte[] getExpected(byte[] bytes) {
if (initialBytes == null) {
return checkNotNull(bytes);
} else {
byte[] result = new byte[initialBytes.length + bytes.length];
System.arraycopy(initialBytes, 0, result, 0, initialBytes.length);
System.arraycopy(bytes, 0, result, initialBytes.length, bytes.length);
return result;
}
}
@Override
public byte[] getSinkContents() throws IOException {
File file = getFile();
InputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[100];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
return out.toByteArray();
}
}
private static class FileCharSourceFactory extends FileFactory implements CharSourceFactory {
@Override
public CharSource createSource(String string) throws IOException {
checkNotNull(string);
File file = createFile();
Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
try {
writer.write(string);
} finally {
writer.close();
}
return Files.asCharSource(file, Charsets.UTF_8);
}
@Override
public String getExpected(String string) {
return checkNotNull(string);
}
}
private static class FileCharSinkFactory extends FileFactory implements CharSinkFactory {
private final String initialString;
private FileCharSinkFactory(@Nullable String initialString) {
this.initialString = initialString;
}
@Override
public CharSink createSink() throws IOException {
File file = createFile();
if (initialString != null) {
Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
try {
writer.write(initialString);
} finally {
writer.close();
}
return Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
}
return Files.asCharSink(file, Charsets.UTF_8);
}
@Override
public String getExpected(String string) {
checkNotNull(string);
return initialString == null
? string
: initialString + string;
}
@Override
public String getSinkContents() throws IOException {
File file = getFile();
Reader reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8);
StringBuilder builder = new StringBuilder();
CharBuffer buffer = CharBuffer.allocate(100);
while (reader.read(buffer) != -1) {
buffer.flip();
builder.append(buffer);
buffer.clear();
}
return builder.toString();
}
}
private static class UrlByteSourceFactory extends FileByteSourceFactory {
@Override
public ByteSource createSource(byte[] bytes) throws IOException {
super.createSource(bytes);
return Resources.asByteSource(getFile().toURI().toURL());
}
}
private static class UrlCharSourceFactory extends FileCharSourceFactory {
@Override
public CharSource createSource(String string) throws IOException {
super.createSource(string); // just ignore returned CharSource
return Resources.asCharSource(getFile().toURI().toURL(), Charsets.UTF_8);
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
/** Returns a random portion of the requested bytes on each call. */
class RandomAmountInputStream extends FilterInputStream {
private final Random random;
public RandomAmountInputStream(InputStream in, Random random) {
super(checkNotNull(in));
this.random = checkNotNull(random);
}
@Override public int read(byte[] b, int off, int len) throws IOException {
return super.read(b, off, random.nextInt(len) + 1);
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import junit.framework.TestCase;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
/**
* @param <S> the source or sink type
* @param <T> the data type (byte[] or String)
* @param <F> the factory type
* @author Colin Decker
*/
public class SourceSinkTester<S, T, F extends SourceSinkFactory<S, T>> extends TestCase {
static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing "
+ "elit. Cras fringilla elit ac ipsum adipiscing vulputate. Maecenas in lorem nulla, ac "
+ "sollicitudin quam. Praesent neque elit, sodales quis vestibulum vel, pellentesque nec "
+ "erat. Proin cursus commodo lacus eget congue. Aliquam erat volutpat. Fusce ut leo sed "
+ "risus tempor vehicula et a odio. Nam aliquet dolor viverra libero rutrum accumsan quis "
+ "in augue. Suspendisse id dui in lorem tristique placerat eget vel risus. Sed metus neque, "
+ "scelerisque in molestie ac, mattis quis lectus. Pellentesque viverra justo commodo quam "
+ "bibendum ut gravida leo accumsan. Nullam malesuada sagittis diam, quis suscipit mauris "
+ "euismod vulputate. Pellentesque ultrices tellus sed lorem aliquet pulvinar. Nam lorem "
+ "nunc, ultrices at auctor non, scelerisque eget turpis. Nullam eget varius erat. Sed a "
+ "lorem id arcu dictum euismod. Fusce lectus odio, elementum ullamcorper mattis viverra, "
+ "dictum sit amet lacus.\n"
+ "\n"
+ "Nunc quis lacus est. Sed aliquam pretium cursus. Sed eu libero eros. In hac habitasse "
+ "platea dictumst. Pellentesque molestie, nibh nec iaculis luctus, justo sem lobortis enim, "
+ "at feugiat leo magna nec libero. Mauris quis odio eget nisl rutrum cursus nec eget augue. "
+ "Sed nec arcu sem. In hac habitasse platea dictumst.";
static final ImmutableMap<String, String> TEST_STRINGS
= ImmutableMap.<String, String>builder()
.put("empty", "")
.put("1 char", "0")
.put("1 word", "hello")
.put("2 words", "hello world")
.put("\\n line break", "hello\nworld")
.put("\\r line break", "hello\rworld")
.put("\\r\\n line break", "hello\r\nworld")
.put("\\n at EOF", "hello\nworld\n")
.put("\\r at EOF", "hello\nworld\r")
.put("lorem ipsum", LOREM_IPSUM)
.build();
protected final F factory;
protected final T data;
protected final T expected;
private final String suiteName;
private final String caseDesc;
SourceSinkTester(F factory, T data, String suiteName, String caseDesc, Method method) {
super(method.getName());
this.factory = checkNotNull(factory);
this.data = checkNotNull(data);
this.expected = checkNotNull(factory.getExpected(data));
this.suiteName = checkNotNull(suiteName);
this.caseDesc = checkNotNull(caseDesc);
}
@Override
public String getName() {
return super.getName() + " [" + suiteName + " [" + caseDesc + "]]";
}
protected static ImmutableList<String> getLines(final String string) {
try {
return new CharSource() {
@Override
public Reader openStream() throws IOException {
return new StringReader(string);
}
}.readLines();
} catch (IOException e) {
throw new AssertionError();
}
}
@Override
public void tearDown() throws IOException {
factory.tearDown();
}
static ImmutableList<Method> getTestMethods(Class<?> testClass) {
List<Method> result = Lists.newArrayList();
for (Method method : testClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getReturnType() == void.class
&& method.getParameterTypes().length == 0
&& method.getName().startsWith("test")) {
result.add(method);
}
}
return ImmutableList.copyOf(result);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.