Skip to content

Commit

Permalink
introduces FieldType.inferFrom and a simplified OptionSpec.Builder.se…
Browse files Browse the repository at this point in the history
…tValue which makes use of it.
  • Loading branch information
perezd committed Aug 5, 2019
1 parent 19d8654 commit 75a92ef
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 8 deletions.
51 changes: 43 additions & 8 deletions java/protopoet/FieldType.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@

package protopoet;

/**
* All standard scalar types a field may represent.
* Learn more: https://developers.google.com/protocol-buffers/docs/reference/proto3-spec#fields
/**
* All standard scalar types a field may represent. Learn more:
* https://developers.google.com/protocol-buffers/docs/reference/proto3-spec#fields
*/
public enum FieldType {
DOUBLE,
Expand All @@ -39,18 +39,53 @@ public enum FieldType {
MESSAGE,
ENUM;

/**
* Attempts to guess at the FieldType based on the provided value. Note, this outputs INT32
* forInteger and INT64 for Long, if you need more specific types for numerics, don't use this.
*/
public static FieldType inferFrom(Object value) {
if (value instanceof Double) {
return DOUBLE;
}
if (value instanceof Float) {
return FLOAT;
}
if (value instanceof Integer) {
return INT32;
}
if (value instanceof Long) {
return INT64;
}
if (value instanceof Boolean) {
return BOOL;
}
if (value instanceof String) {
return STRING;
}
if (value instanceof byte[]) {
return BYTES;
}
if (value instanceof Enum) {
return ENUM;
}
if (value instanceof Object) {
return MESSAGE;
}
throw new IllegalArgumentException("unable to express FieldType for value");
}

@Override
public String toString() {
return name().toLowerCase();
}

String formatValue(Object value) {
switch (this) {
case STRING:
case BYTES:
return String.format("\"%s\"", value);
default:
return value.toString();
case STRING:
case BYTES:
return String.format("\"%s\"", value);
default:
return value.toString();
}
}
}
10 changes: 10 additions & 0 deletions java/protopoet/OptionSpec.java
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,16 @@ public Builder setOptionComment(String... lines) {
return setOptionComment(ImmutableList.copyOf(lines));
}

/**
* Sets value and infers the field type based on passed in value. Check {@link FieldType} for
* more info on how it does it, if you need more granularity or predictibility, don't use this.
*/
public Builder setValue(Object value) {
optionValueType = FieldType.inferFrom(value);
optionValue = value;
return this;
}

/** Sets an integer-based value (eg: int32, uint32, fixed32, sfixed32). */
public Builder setValue(FieldType valueType, int intValue) {
switch (valueType) {
Expand Down

0 comments on commit 75a92ef

Please sign in to comment.