Skip to content

Conversation

@GrahamDennis
Copy link
Contributor

No description provided.

@GrahamDennis
Copy link
Contributor Author

Note: This repo doesn't have a changelog policy, but the changelog status check is required to pass.


@Test
public void testParseByte() {
assetStringsEqualToBytes(10L, "10", "10b", "10 byte", "10 bytes");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

* @return a human-readable string representation of this byte string, not null
*/
@Override
@JsonValue
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Matches HumanReadableDuration which already applies @JsonValue to toString() 👍

@iamdanfox
Copy link

iamdanfox commented Nov 25, 2019

One thing that's slightly interesting here is that this type doesn't do a byte-for-byte round-trip, because the jsoncreator does some normalizing.

For example, I think 10 MB would come out as 10mb.

I think this is fine, just kinda interesting.

    @JsonCreator
    public static HumanReadableByteCount valueOf(String byteCount) {
        String lower = byteCount.toLowerCase(Locale.ROOT).trim();

        try {
            Matcher matcher = BYTE_COUNT_PATTERN.matcher(lower);

            Preconditions.checkArgument(matcher.matches(), "Invalid byte string: %s", byteCount);

            long size = Long.parseLong(matcher.group(1));
            String suffix = matcher.group(2);

            if (suffix != null && !SUFFIXES.containsKey(suffix)) {
                throw new IllegalArgumentException("Invalid byte string: " + byteCount + ". Wrong byte unit");
            }

            return new HumanReadableByteCount(size, suffix != null ? SUFFIXES.get(suffix) : ByteUnit.BYTE);

        } catch (NumberFormatException e) {
            String byteError = "Size must be specified as bytes (b), "
                    + "kibibytes (k), mebibytes (m), gibibytes (g), tebibytes (t), or pebibytes(p). "
                    + "E.g. 50b, 100k, or 250m.";

            throw new NumberFormatException(byteError + "\n" + e.getMessage());
        }
    }

https://github.com/GrahamDennis/human-readable-types/blob/b5f5a804ac1dd2753ce812a230bd9e0d333d7da7/human-readable-types/src/main/java/com/palantir/humanreadabletypes/HumanReadableByteCount.java#L139-L164

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants