001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.imagery.vectortile.mapbox; 003 004import java.util.Arrays; 005 006/** 007 * An indicator for a command to be executed 008 * @author Taylor Smock 009 * @since 17862 010 */ 011public class CommandInteger { 012 private final Command type; 013 private final short[] parameters; 014 private int added; 015 016 /** 017 * Create a new command 018 * @param command the command (treated as an unsigned int) 019 */ 020 public CommandInteger(final int command) { 021 // Technically, the int is unsigned, but it is easier to work with the long 022 final long unsigned = Integer.toUnsignedLong(command); 023 // By avoiding using a stream for getting the Command type, we go from 72 MB to 13 MB. 024 // By using a cached value for Command.values(), we further reduce the allocations to 5 MB (new short[] call 025 // at end of initializer) 026 Command rType = null; 027 for (Command tType : Command.getAllValues()) { 028 if (tType.getId() == (unsigned & 0x7)) { 029 rType = tType; 030 break; 031 } 032 } 033 this.type = rType; 034 if (this.type == null) { 035 throw new InvalidMapboxVectorTileException(); 036 } 037 038 // This is safe, since we are shifting right 3 when we converted an int to a long (for unsigned). 039 // So we <i>cannot</i> lose anything. 040 final int operationsInt = (int) (unsigned >> 3); 041 this.parameters = new short[operationsInt * this.type.getParameterNumber()]; 042 } 043 044 /** 045 * Add a parameter 046 * @param parameterInteger The parameter to add (converted to {@code short}). 047 */ 048 public void addParameter(Number parameterInteger) { 049 this.parameters[added++] = parameterInteger.shortValue(); 050 } 051 052 /** 053 * Add a parameter 054 * @param parameterInteger The parameter to add (converted to {@code short}). 055 * @since 18695 056 */ 057 public void addParameter(long parameterInteger) { 058 this.parameters[added++] = (short) parameterInteger; 059 } 060 061 /** 062 * Get the operations for the command 063 * @return The operations 064 */ 065 public short[] getOperations() { 066 return this.parameters; 067 } 068 069 /** 070 * Get the command type 071 * @return the command type 072 */ 073 public Command getType() { 074 return this.type; 075 } 076 077 /** 078 * Get the expected parameter length 079 * @return The expected parameter size 080 */ 081 public boolean hasAllExpectedParameters() { 082 return this.added >= this.parameters.length; 083 } 084 085 @Override 086 public String toString() { 087 return "CommandInteger [type=" + type + ", parameters=" + Arrays.toString(parameters) + ']'; 088 } 089}