Ejemplo n.º 1
0
  public static BufferedImage convertToImage(TextureRegion textureRegion) {
    final int width = textureRegion.getWidth();
    final int height = textureRegion.getHeight();

    final Rect2i pixelRegion = textureRegion.getPixelRegion();
    final Texture texture = textureRegion.getTexture();
    ByteBuffer textureBytes = texture.getData().getBuffers()[0];
    int stride = texture.getWidth() * 4;
    int posX = pixelRegion.minX();
    int posY = pixelRegion.minY();

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        int r = UnsignedBytes.toInt(textureBytes.get((posY + y) * stride + (posX + x) * 4));
        int g = UnsignedBytes.toInt(textureBytes.get((posY + y) * stride + (posX + x) * 4 + 1));
        int b = UnsignedBytes.toInt(textureBytes.get((posY + y) * stride + (posX + x) * 4 + 2));
        int a = UnsignedBytes.toInt(textureBytes.get((posY + y) * stride + (posX + x) * 4 + 3));

        int argb = (a << 24) + (r << 16) + (g << 8) + b;
        image.setRGB(x, y, argb);
      }
    }
    return image;
  }
Ejemplo n.º 2
0
  // This method is a hotspot, logic from RocksDbKeyValueServices.parseCellAndTs
  // is duplicated and tuned for perf.
  @Override
  public int compare(Slice a, Slice b) {
    byte[] adata = a.data();
    byte[] bdata = b.data();
    byte[] rowSizeBytes = new byte[2];
    rowSizeBytes[0] = adata[adata.length - 1];
    rowSizeBytes[1] = adata[adata.length - 2];
    int aRowSize = (int) EncodingUtils.decodeVarLong(rowSizeBytes);
    rowSizeBytes[0] = bdata[bdata.length - 1];
    rowSizeBytes[1] = bdata[bdata.length - 2];
    int bRowSize = (int) EncodingUtils.decodeVarLong(rowSizeBytes);

    int comp =
        UnsignedBytes.lexicographicalComparator()
            .compare(Arrays.copyOf(adata, aRowSize), Arrays.copyOf(bdata, bRowSize));
    if (comp != 0) {
      return comp;
    }

    int aColEnd = adata.length - 8 - EncodingUtils.sizeOfVarLong(aRowSize);
    int bColEnd = bdata.length - 8 - EncodingUtils.sizeOfVarLong(bRowSize);
    comp =
        UnsignedBytes.lexicographicalComparator()
            .compare(
                Arrays.copyOfRange(adata, aRowSize, aColEnd),
                Arrays.copyOfRange(bdata, bRowSize, bColEnd));
    if (comp != 0) {
      return comp;
    }

    long aTs =
        Longs.fromBytes(
            adata[aColEnd + 0],
            adata[aColEnd + 1],
            adata[aColEnd + 2],
            adata[aColEnd + 3],
            adata[aColEnd + 4],
            adata[aColEnd + 5],
            adata[aColEnd + 6],
            adata[aColEnd + 7]);
    long bTs =
        Longs.fromBytes(
            bdata[bColEnd + 0],
            bdata[bColEnd + 1],
            bdata[bColEnd + 2],
            bdata[bColEnd + 3],
            bdata[bColEnd + 4],
            bdata[bColEnd + 5],
            bdata[bColEnd + 6],
            bdata[bColEnd + 7]);

    // Note: Ordering is reversed, later timestamps come before eariler ones.
    return Long.compare(bTs, aTs);
  }
Ejemplo n.º 3
0
  @Test
  public void testEqualsPerformance() {
    boolean testEnabled = false;

    if (testEnabled) {
      final int ITERATIONS = 10000000;
      long start1 = System.currentTimeMillis();
      for (int i = 0; i < ITERATIONS; i++) {
        Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator();

        comparator.compare(wrapper1.getData(), wrapper2.getData());
      }
      System.out.println(System.currentTimeMillis() - start1 + "ms");

      long start2 = System.currentTimeMillis();
      for (int i = 0; i < ITERATIONS; i++) {
        Arrays.equals(wrapper1.getData(), wrapper2.getData());
      }
      System.out.println(System.currentTimeMillis() - start2 + "ms");

      long start3 = System.currentTimeMillis();
      for (int i = 0; i < ITERATIONS; i++) {
        FastByteComparisons.compareTo(
            wrapper1.getData(),
            0,
            wrapper1.getData().length,
            wrapper2.getData(),
            0,
            wrapper1.getData().length);
      }
      System.out.println(System.currentTimeMillis() - start3 + "ms");
    }
  }
Ejemplo n.º 4
0
  @Override
  public int compareTo(Employee o) {
    int diff =
        ComparisonChain.start()
            .compare(lastName, o.lastName, Ordering.from(String.CASE_INSENSITIVE_ORDER))
            .compare(firstName, o.firstName, Ordering.from(String.CASE_INSENSITIVE_ORDER))
            .compare(title, o.title, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(
                titleCourtesy,
                o.titleCourtesy,
                Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(birthDate, o.birthDate, Ordering.natural().nullsFirst())
            .compare(hireDate, o.hireDate, Ordering.natural().nullsFirst())
            .compare(address, o.address, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(city, o.city, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(region, o.region, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(
                postalCode, o.postalCode, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(country, o.country, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(
                homePhone, o.homePhone, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(
                extension, o.extension, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(reportsTo, o.reportsTo, Ordering.natural().nullsFirst())
            .result();
    if (diff != 0) return diff;

    if (photo == null) return o.photo == null ? 0 : -1;
    if (o.photo == null) return 1;
    return UnsignedBytes.lexicographicalComparator().compare(photo, o.photo);
  }
Ejemplo n.º 5
0
 public void addEnderBookRecipe(int recipe) {
   if (!hasEnderBookRecipe(recipe)) {
     enderbookRecipes = Arrays.copyOf(enderbookRecipes, enderbookRecipes.length + 1);
     enderbookRecipes[enderbookRecipes.length - 1] = UnsignedBytes.checkedCast(recipe);
     setDirty();
   }
 }
Ejemplo n.º 6
0
    private int validateAndClaimId(int id)
    {
        // workaround for broken ML
        int realId = id;
        if (id < Byte.MIN_VALUE)
        {
            FMLLog.warning("Compensating for modloader out of range compensation by mod : entityId %d for mod %s is now %d", id, Loader.instance().activeModContainer().getModId(), realId);
            realId += 3000;
        }

        if (realId < 0)
        {
            realId += Byte.MAX_VALUE;
        }
        try
        {
            UnsignedBytes.checkedCast(realId);
        }
        catch (IllegalArgumentException e)
        {
            FMLLog.log(Level.SEVERE, "The entity ID %d for mod %s is not an unsigned byte and may not work", id, Loader.instance().activeModContainer().getModId());
        }

        if (!availableIndicies.get(realId))
        {
            FMLLog.severe("The mod %s has attempted to register an entity ID %d which is already reserved. This could cause severe problems", Loader.instance().activeModContainer().getModId(), id);
        }
        availableIndicies.clear(realId);
        return realId;
    }
Ejemplo n.º 7
0
 /**
  * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code
  * BloomFilter<T>}.
  *
  * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here.
  * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate
  * the original Bloom filter!
  *
  * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not
  *     appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method.
  */
 public static <T> BloomFilter<T> readFrom(InputStream in, Funnel<T> funnel) throws IOException {
   checkNotNull(in, "InputStream");
   checkNotNull(funnel, "Funnel");
   int strategyOrdinal = -1;
   int numHashFunctions = -1;
   int dataLength = -1;
   try {
     DataInputStream din = new DataInputStream(in);
     // currently this assumes there is no negative ordinal; will have to be updated if we
     // add non-stateless strategies (for which we've reserved negative ordinals; see
     // Strategy.ordinal()).
     strategyOrdinal = din.readByte();
     numHashFunctions = UnsignedBytes.toInt(din.readByte());
     dataLength = din.readInt();
     Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal];
     long[] data = new long[dataLength];
     for (int i = 0; i < data.length; i++) {
       data[i] = din.readLong();
     }
     return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy);
   } catch (RuntimeException e) {
     IOException ioException =
         new IOException(
             "Unable to deserialize BloomFilter from InputStream."
                 + " strategyOrdinal: "
                 + strategyOrdinal
                 + " numHashFunctions: "
                 + numHashFunctions
                 + " dataLength: "
                 + dataLength);
     ioException.initCause(e);
     throw ioException;
   }
 }
Ejemplo n.º 8
0
 @Nonnull
 public static <T extends Enum<T> & Code.DescriptiveWrapper> String toString(@Nonnull T value) {
   return value.name()
       + "(0x"
       + UnsignedBytes.toString(value.getCode(), 16)
       + "): "
       + value.getDescription();
 }
Ejemplo n.º 9
0
  @Test
  public void testRangesPrefixed() throws Exception {

    File dir0 = Files.createTempDir();
    VersionedPartitionName versionedPartitionName =
        new VersionedPartitionName(
            new PartitionName(false, "r1".getBytes(), "t1".getBytes()),
            VersionedPartitionName.STATIC_VERSION);
    BerkeleyDBWALIndex index = getIndex(dir0, versionedPartitionName);

    index.merge(
        (TxKeyPointerStream stream) -> {
          for (long i = 0; i < 64; i++) {
            byte[] prefix = {0, (byte) (i % 4)};
            byte[] key = {0, 0, (byte) (i % 2), (byte) i};
            if (!stream.stream(
                i, prefix, key, null, System.currentTimeMillis(), false, Long.MAX_VALUE, i)) {
              return false;
            }
          }
          return true;
        },
        null);

    int[] count = new int[1];
    byte[] fromPrefix = {0, 1};
    byte[] toPrefix = {0, 2};
    index.rangeScan(
        fromPrefix,
        new byte[0],
        toPrefix,
        new byte[0],
        (prefix, key, timestamp, tombstoned, version, fp, hasValue, value) -> {
          count[0]++;
          Assert.assertTrue(
              UnsignedBytes.lexicographicalComparator().compare(fromPrefix, prefix) <= 0);
          Assert.assertTrue(
              UnsignedBytes.lexicographicalComparator().compare(prefix, toPrefix) < 0);
          // System.out.println("prefix: " + Arrays.toString(prefix) + " key: " +
          // Arrays.toString(key));
          return true;
        },
        true);
    Assert.assertEquals(count[0], 16);
  }
 @Override
 public byte getTag(final Object o) {
   if (o == null) {
     return -1;
   }
   final TFieldIdEnum setField =
       ((TUnion<? extends TUnion<?, ?>, ? extends TFieldIdEnum>) o).getSetField();
   return UnsignedBytes.checkedCast((setField.getThriftFieldId() - 1));
 }
Ejemplo n.º 11
0
 @Override
 public void toStringBuilder(StringBuilder buf, int depth) {
   appendHeader(buf, depth, getClass().getSimpleName());
   depth++;
   appendValue(buf, depth, "MessageTag", "0x" + UnsignedBytes.toString(messageTag, 16));
   appendValue(buf, depth, "RequestedMaximumPrivilegeLevel", requestedMaximumPrivilegeLevel);
   appendValue(buf, depth, "ConsoleSessionId", "0x" + Integer.toHexString(consoleSessionId));
   appendValue(buf, depth, "AuthenticationAlgorithm", authenticationAlgorithm);
   appendValue(buf, depth, "IntegrityAlgorithm", integrityAlgorithm);
   appendValue(buf, depth, "ConfidentialityAlgorithm", confidentialityAlgorithm);
 }
Ejemplo n.º 12
0
 @Override
 public int compare(byte[] left, byte[] right) {
   int minLength = Math.min(left.length, right.length);
   for (int i = 0; i < minLength; i++) {
     int result = UnsignedBytes.compare(left[i], right[i]);
     if (result != 0) {
       return result;
     }
   }
   return left.length - right.length;
 }
Ejemplo n.º 13
0
      @Override
      public int compare(byte[] left, byte[] right) {
        int minLength = Math.min(left.length, right.length);
        int minWords = minLength / Longs.BYTES;

        /*
         * Compare 8 bytes at a time. Benchmarking shows comparing 8 bytes at a
         * time is no slower than comparing 4 bytes at a time even on 32-bit.
         * On the other hand, it is substantially faster on 64-bit.
         */
        for (int i = 0; i < minWords * Longs.BYTES; i += Longs.BYTES) {
          long lw = theUnsafe.getLong(left, BYTE_ARRAY_BASE_OFFSET + (long) i);
          long rw = theUnsafe.getLong(right, BYTE_ARRAY_BASE_OFFSET + (long) i);
          long diff = lw ^ rw;

          if (diff != 0) {
            if (!littleEndian) {
              return UnsignedLongs.compare(lw, rw);
            }

            // Use binary search
            int n = 0;
            int y;
            int x = (int) diff;
            if (x == 0) {
              x = (int) (diff >>> 32);
              n = 32;
            }

            y = x << 16;
            if (y == 0) {
              n += 16;
            } else {
              x = y;
            }

            y = x << 8;
            if (y == 0) {
              n += 8;
            }
            return (int) (((lw >>> n) & UNSIGNED_MASK) - ((rw >>> n) & UNSIGNED_MASK));
          }
        }

        // The epilogue to cover the last (minLength % 8) elements.
        for (int i = minWords * Longs.BYTES; i < minLength; i++) {
          int result = UnsignedBytes.compare(left[i], right[i]);
          if (result != 0) {
            return result;
          }
        }
        return left.length - right.length;
      }
Ejemplo n.º 14
0
  /**
   * Converts a BufferedImage into a ByteBuffer based on 32-bit values in RGBA byte order
   *
   * @param image any type of BufferedImage
   * @return a ByteBuffer that contains the data in RGBA byte order
   */
  public static ByteBuffer convertToByteBuffer(BufferedImage image) {
    int width = image.getWidth();
    int height = image.getHeight();
    ByteBuffer data = ByteBuffer.allocateDirect(4 * width * height);

    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        int argb = image.getRGB(x, y);
        int r = (argb >> 16) & 0xFF;
        int g = (argb >> 8) & 0xFF;
        int b = argb & 0xFF;
        int a = (argb >> 24) & 0xFF;
        data.put(UnsignedBytes.checkedCast(r));
        data.put(UnsignedBytes.checkedCast(g));
        data.put(UnsignedBytes.checkedCast(b));
        data.put(UnsignedBytes.checkedCast(a));
      }
    }
    data.rewind();
    return data;
  }
Ejemplo n.º 15
0
      @Override
      public int compareTo(
          byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) {
        if (buffer1 == buffer2 && offset1 == offset2 && length1 == length2) {
          return 0;
        }
        int minLength = Math.min(length1, length2);
        int minWords = minLength / Longs.BYTES;
        int offset1Adj = offset1 + BYTE_ARRAY_BASE_OFFSET;
        int offset2Adj = offset2 + BYTE_ARRAY_BASE_OFFSET;

        for (int i = 0; i < minWords * Longs.BYTES; i += Longs.BYTES) {
          long lw = theUnsafe.getLong(buffer1, offset1Adj + (long) i);
          long rw = theUnsafe.getLong(buffer2, offset2Adj + (long) i);
          long diff = lw ^ rw;

          if (diff != 0) {
            if (!littleEndian) {
              return lessThanUnsigned(lw, rw) ? -1 : 1;
            }
            int n = 0;
            int y;
            int x = (int) diff;
            if (x == 0) {
              x = (int) (diff >>> 32);
              n = 32;
            }

            y = x << 16;
            if (y == 0) {
              n += 16;
            } else {
              x = y;
            }

            y = x << 8;
            if (y == 0) {
              n += 8;
            }
            return (int) (((lw >>> n) & 0xFFL) - ((rw >>> n) & 0xFFL));
          }
        }

        for (int i = minWords * Longs.BYTES; i < minLength; i++) {
          int result = UnsignedBytes.compare(buffer1[offset1 + i], buffer2[offset2 + i]);
          if (result != 0) {
            return result;
          }
        }
        return length1 - length2;
      }
Ejemplo n.º 16
0
 /**
  * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java
  * serialization). This has been measured to save at least 400 bytes compared to regular
  * serialization.
  *
  * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter.
  */
 public void writeTo(OutputStream out) throws IOException {
   // Serial form:
   // 1 signed byte for the strategy
   // 1 unsigned byte for the number of hash functions
   // 1 big endian int, the number of longs in our bitset
   // N big endian longs of our bitset
   DataOutputStream dout = new DataOutputStream(out);
   dout.writeByte(SignedBytes.checkedCast(strategy.ordinal()));
   dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor
   dout.writeInt(bits.data.length);
   for (long value : bits.data) {
     dout.writeLong(value);
   }
 }
  private String toStringRepresentation(byte[] bytes, int offset, int length) {
    final StringBuilder result = new StringBuilder();
    for (int i = 0; i < length; i++) {
      byte aByte = bytes[offset + i];
      // An unsigned byte results in max 3 decimal digits (because max value is "255") and we want
      // to use
      // always the max size such that if two byte arrays have the same length,
      // the two encoded byte arrays also have the same length (such that byte sort order is
      // remained).
      // Therefore, we fill the gaps with a filler character.
      result.append(prependZeroes(3, "" + UnsignedBytes.toInt(aByte)));
    }

    return result.toString();
  }
Ejemplo n.º 18
0
 public static void serialiseKey(Key key, ByteBuf w) {
   byte[] id = key.getArray();
   BitBuffer bbuf = BitBuffer.create((key instanceof Key.Inf), (id == null));
   boolean byteFlag = (id != null) && (id.length <= Key.BYTE_KEY_SIZE);
   bbuf.write(byteFlag);
   byte[] flags = bbuf.finalise();
   w.writeBytes(flags);
   if (id != null) {
     if (byteFlag) {
       w.writeByte(UnsignedBytes.checkedCast(id.length));
     } else {
       w.writeInt(id.length);
     }
     w.writeBytes(id);
   }
 }
Ejemplo n.º 19
0
 private boolean isLatestValueEmpty(Cell cell, PeekingIterator<RowResult<Value>> values) {
   while (values.hasNext()) {
     RowResult<Value> result = values.peek();
     int comparison =
         UnsignedBytes.lexicographicalComparator().compare(cell.getRowName(), result.getRowName());
     if (comparison == 0) {
       Value matchingValue = result.getColumns().get(cell.getColumnName());
       return matchingValue != null && matchingValue.getContents().length == 0;
     } else if (comparison < 0) {
       return false;
     } else {
       values.next();
     }
   }
   return false;
 }
Ejemplo n.º 20
0
  private static int compare(
      @NotNull final Buffer left,
      long leftFrom,
      final long leftLength,
      @NotNull final Buffer right,
      long rightFrom,
      final long rightLength) {
    assert leftLength > 0;
    assert rightLength > 0;

    // Adapted from Guava UnsignedBytes

    long length = Math.min(leftLength, rightLength);

    for (;
        length >= Longs.BYTES;
        leftFrom += Longs.BYTES, rightFrom += Longs.BYTES, length -= Longs.BYTES) {
      final long lw = left.getLong(leftFrom);
      final long rw = right.getLong(rightFrom);
      if (lw != rw) {
        return UnsignedLongs.compare(lw, rw);
      }
    }

    if (length >= Ints.BYTES) {
      final int lw = left.getInt(leftFrom);
      final int rw = right.getInt(rightFrom);
      if (lw != rw) {
        return UnsignedInts.compare(lw, rw);
      }
      leftFrom += Ints.BYTES;
      rightFrom += Ints.BYTES;
      length -= Ints.BYTES;
    }

    for (; length > 0; leftFrom++, rightFrom++, length--) {
      final int result = UnsignedBytes.compare(left.get(leftFrom), right.get(rightFrom));

      if (result != 0) {
        return result;
      }
    }

    return (leftLength < rightLength) ? -1 : ((leftLength == rightLength) ? 0 : 1);
  }
Ejemplo n.º 21
0
 public static Key deserialiseKey(ByteBuf r) {
   byte[] flagBytes = new byte[1];
   r.readBytes(flagBytes);
   boolean[] flags = BitBuffer.extract(3, flagBytes);
   boolean infFlag = flags[0];
   boolean nullFlag = flags[1];
   boolean byteFlag = flags[2];
   if (infFlag) {
     return Key.INF;
   }
   if (nullFlag) {
     return new Key((byte[]) null);
   }
   int keySize;
   if (byteFlag) {
     keySize = UnsignedBytes.toInt(r.readByte());
   } else {
     keySize = r.readInt();
   }
   byte[] id;
   id = new byte[keySize];
   r.readBytes(id);
   return new Key(id);
 }
  public void deserializeOnto(
      MutableComponentContainer entity,
      EntityData.PackedEntity entityData,
      FieldSerializeCheck<Component> fieldCheck) {
    int fieldPos = 0;
    for (int componentIndex = 0;
        componentIndex < entityData.getComponentIdCount();
        ++componentIndex) {
      Class<? extends Component> componentClass =
          idTable.inverse().get((Integer) entityData.getComponentId(componentIndex));
      ComponentMetadata<?> metadata = componentLibrary.getMetadata(componentClass);
      if (metadata == null) {
        logger.warn("Skipping unknown component {}", entityData.getComponentId(componentIndex));
        fieldPos +=
            UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex));
        continue;
      }
      if (!componentSerializeCheck.serialize(metadata)) {
        fieldPos +=
            UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex));
        continue;
      }

      Component component = entity.getComponent(metadata.getType());
      boolean createdNewComponent = false;
      if (component == null) {
        createdNewComponent = true;
        component = metadata.newInstance();
      }
      Serializer serializer = typeSerializationLibrary.getSerializerFor(metadata);
      for (int fieldIndex = 0;
          fieldIndex
              < UnsignedBytes.toInt(entityData.getComponentFieldCounts().byteAt(componentIndex));
          ++fieldIndex) {
        byte fieldId = entityData.getFieldIds().byteAt(fieldPos);
        ReplicatedFieldMetadata fieldMetadata = metadata.getField(fieldId);
        if (fieldMetadata != null && fieldCheck.shouldDeserialize(metadata, fieldMetadata)) {
          logger.trace(
              "Deserializing field {} of component {} as value {}",
              fieldMetadata,
              metadata,
              entityData.getFieldValue(fieldPos));
          serializer.deserializeOnto(
              component,
              fieldMetadata,
              new ProtobufPersistedData(entityData.getFieldValue(fieldPos)),
              deserializationContext);
        }
        fieldPos++;
      }
      if (createdNewComponent) {
        entity.addComponent(component);
      } else {
        entity.saveComponent(component);
      }
    }

    for (int componentId : entityData.getRemovedComponentList()) {
      Class<? extends Component> componentClass = idTable.inverse().get(componentId);
      ComponentMetadata<?> metadata = componentLibrary.getMetadata(componentClass);
      if (componentSerializeCheck.serialize(metadata)) {
        entity.removeComponent(metadata.getType());
      }
    }
  }
Ejemplo n.º 23
0
public class Value {
  static final Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator();

  protected Map<String, byte[]> fields;

  public Value() {
    fields = new HashMap<String, byte[]>();
  }

  public Value(Value v) {
    fields = new HashMap<String, byte[]>(v.fields);
  }

  public byte[] getField(String field) {
    return fields.get(field);
  }

  public Value setField(String field, byte[] data) {
    fields.put(field, data);
    return this;
  }

  public Value clearFields() {
    fields.clear();
    return this;
  }

  public Set<String> getFields() {
    return fields.keySet();
  }

  public Map<String, byte[]> getFieldsMap() {
    return Collections.unmodifiableMap(fields);
  }

  /**
   * Select parts of fields.
   *
   * @param fields Parts of fields
   * @return new value with specified fields
   */
  public Value project(Set<String> fields) {
    if (ALL_FIELDS == fields) {
      return new Value(this);
    }
    Value v = new Value();
    for (String f : fields) {
      byte[] data = this.fields.get(f);
      v.setField(f, data);
    }
    return v;
  }

  @Override
  public int hashCode() {
    HashFunction hf = Hashing.murmur3_32();
    Hasher hc = hf.newHasher();
    for (String key : fields.keySet()) {
      hc.putString(key, Charsets.UTF_8);
    }
    return hc.hash().asInt();
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof Value)) {
      return false;
    }
    Value other = (Value) o;
    if (fields.size() != other.fields.size()) {
      return false;
    }
    for (String f : fields.keySet()) {
      byte[] v1 = fields.get(f);
      byte[] v2 = other.fields.get(f);
      if (0 != comparator.compare(v1, v2)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Merge other value.
   *
   * @param other Other Value
   */
  public Value merge(Value other) {
    for (Map.Entry<String, byte[]> entry : other.fields.entrySet()) {
      if (null == entry.getValue()) {
        fields.remove(entry.getKey());
      } else {
        fields.put(entry.getKey(), entry.getValue());
      }
    }
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (Map.Entry<String, byte[]> entry : fields.entrySet()) {
      String f = entry.getKey();
      if (null == f) {
        f = "NULL";
      }
      String value;
      if (null == entry.getValue()) {
        value = "NONE";
      } else {
        value = new String(entry.getValue(), UTF_8);
      }
      sb.append("('").append(f).append("'=").append(value).append(")");
    }
    sb.append("]");
    return sb.toString();
  }
}
Ejemplo n.º 24
0
 public boolean hasEnderBookRecipe(int recipe) {
   return Bytes.contains(enderbookRecipes, UnsignedBytes.checkedCast(recipe));
 }
Ejemplo n.º 25
0
 @Nonnull
 public static <T extends Enum<T> & Code.Wrapper> T fromInt(
     @Nonnull Class<T> type, @Nonnegative int code) {
   return fromByte(type, UnsignedBytes.checkedCast(code));
 }
Ejemplo n.º 26
0
 @Nonnull
 public static <T extends Enum<T> & Code.Wrapper> T fromByte(@Nonnull Class<T> type, byte code) {
   for (T value : type.getEnumConstants()) if (value.getCode() == code) return value;
   throw new IllegalArgumentException(
       "Unknown " + type.getSimpleName() + " code 0x" + UnsignedBytes.toString(code, 16));
 }
Ejemplo n.º 27
0
 @Override
 public int compareTo(U8 o) {
   return UnsignedBytes.compare(raw, o.raw);
 }