Created
March 10, 2016 13:38
-
-
Save lumue/4560d25266e67be571d9 to your computer and use it in GitHub Desktop.
parse KiB and MiB to bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.lumue.ydlwrapper; | |
import java.math.BigDecimal; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Objects; | |
import java.util.function.Function; | |
/** | |
* | |
* Parse byte value from human readable format | |
* | |
* Created by lm on 09.03.16. | |
*/ | |
public class HumanReadableByteParser implements Function<String,Long>{ | |
public static class ValueConverter implements Function<BigDecimal,Long> { | |
private final BigDecimal faktor; | |
private ValueConverter(BigDecimal faktor) { | |
this.faktor = Objects.requireNonNull(faktor,"faktor must not be null"); | |
} | |
public Long apply(BigDecimal input){ | |
Objects.requireNonNull(input,"input must not be null"); | |
return input.multiply(faktor).longValue(); | |
} | |
} | |
private final static ValueConverter KIB_CONVERTER=new ValueConverter(new BigDecimal(1024)); | |
private final static ValueConverter MIB_CONVERTER=new ValueConverter(new BigDecimal(1024*1024)); | |
@Override | |
public Long apply(String input) { | |
Objects.requireNonNull(input,"input must not be null"); | |
if(input.endsWith("MiB")) | |
return MIB_CONVERTER.apply(new BigDecimal(input.substring(0, input.length() - 3))); | |
if(input.endsWith("KiB")) | |
return KIB_CONVERTER.apply(new BigDecimal(input.substring(0, input.length() - 3))); | |
throw new IllegalArgumentException("failure parsing "+input); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment