001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.commons.lang;
020
021import lucee.runtime.op.Caster;
022
023public final class ByteSizeParser {
024
025        private static final long B=1;
026        private static final long KB=1024;
027        private static final long MB=KB*1024;
028        private static final long GB=MB*1024;
029        private static final long TB=GB*1024;
030        
031        public static long parseByteSizeDefinition(String value, long defaultValue) {
032        value=value.trim().toLowerCase();
033        
034        long factor=B;
035        String num=value;
036        if(value.endsWith("kb")) {
037                factor=KB;
038                num=value.substring(0,value.length()-2).trim();
039        }
040        else if(value.endsWith("k")) {
041                factor=KB;
042                num=value.substring(0,value.length()-1).trim();
043        }
044        else if(value.endsWith("mb")) {
045                factor=MB;
046                num=value.substring(0,value.length()-2).trim();
047        }
048        else if(value.endsWith("m")) {
049                factor=MB;
050                num=value.substring(0,value.length()-1).trim();
051        }
052        else if(value.endsWith("gb")) {
053                factor=GB;
054                num=value.substring(0,value.length()-2).trim();
055        }
056        else if(value.endsWith("g")) {
057                factor=GB;
058                num=value.substring(0,value.length()-1).trim();
059        }
060        else if(value.endsWith("tb")) {
061                factor=TB;
062                num=value.substring(0,value.length()-2).trim();
063        }
064        else if(value.endsWith("t")) {
065                factor=TB;
066                num=value.substring(0,value.length()-1).trim();
067        }
068        else if(value.endsWith("b")) {
069                factor=B;
070                num=value.substring(0,value.length()-1).trim();
071        }
072        
073        long tmp = Caster.toLongValue(num,Long.MIN_VALUE);
074        if(tmp==Long.MIN_VALUE) return defaultValue;
075        return tmp*factor;
076        }
077}