Skip to content

Commit 1390fd2

Browse files
author
epriestley
committed
Support "x bits in bytes" in phutil_units()
Summary: Ref T11140. I need to generate some encryption keys to do at-rest encryption, and the code can be a little more readable as `256 bits in bytes`, etc. Test Plan: Unit tests. Reviewers: chad Reviewed By: chad Maniphest Tasks: T11140 Differential Revision: https://secure.phabricator.com/D16123
1 parent fb1e159 commit 1390fd2

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/utils/__tests__/PhutilUtilsTestCase.php

+7
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,9 @@ public function testPhutilUnits() {
471471
'1 hour in seconds' => 3600,
472472
'1 day in seconds' => 86400,
473473
'3 days in seconds' => 259200,
474+
'128 bits in bytes' => 16,
475+
'1 byte in bytes' => 1,
476+
'8 bits in bytes' => 1,
474477
);
475478

476479
foreach ($cases as $input => $expect) {
@@ -487,6 +490,10 @@ public function testPhutilUnits() {
487490
'1 day in days',
488491
'-1 minutes in seconds',
489492
'1.5 minutes in seconds',
493+
'7 bits in bytes',
494+
'2 hours in bytes',
495+
'1 dram in bytes',
496+
'24 bits in seconds',
490497
);
491498

492499
foreach ($bad_cases as $input) {

src/utils/utils.php

+31-1
Original file line numberDiff line numberDiff line change
@@ -1070,6 +1070,8 @@ function phutil_units($description) {
10701070
$src_unit = $matches[2];
10711071
$dst_unit = $matches[3];
10721072

1073+
$is_divisor = false;
1074+
10731075
switch ($dst_unit) {
10741076
case 'seconds':
10751077
switch ($src_unit) {
@@ -1096,14 +1098,42 @@ function phutil_units($description) {
10961098
$src_unit));
10971099
}
10981100
break;
1101+
case 'bytes':
1102+
switch ($src_unit) {
1103+
case 'byte':
1104+
case 'bytes':
1105+
$factor = 1;
1106+
break;
1107+
case 'bit':
1108+
case 'bits':
1109+
$factor = 8;
1110+
$is_divisor = true;
1111+
break;
1112+
default:
1113+
throw new InvalidArgumentException(
1114+
pht(
1115+
'This function can not convert from the unit "%s".',
1116+
$src_unit));
1117+
}
1118+
break;
10991119
default:
11001120
throw new InvalidArgumentException(
11011121
pht(
11021122
'This function can not convert into the unit "%s".',
11031123
$dst_unit));
11041124
}
11051125

1106-
return $quantity * $factor;
1126+
if ($is_divisor) {
1127+
if ($quantity % $factor) {
1128+
throw new InvalidArgumentException(
1129+
pht(
1130+
'"%s" is not an exact quantity.',
1131+
$description));
1132+
}
1133+
return (int)($quantity / $factor);
1134+
} else {
1135+
return $quantity * $factor;
1136+
}
11071137
}
11081138

11091139

0 commit comments

Comments
 (0)