Skip to content

Commit a47aed2

Browse files
committed
Refactor NumberToDataSizeConverter to use DataSize.ofBytes(long) directly
Prior to this commit, `Number` is converted to `String` and then using regular expressions to match/parse the string back into a suitable `long`, it was based on Spring Boot's string-based implementation which included support for `@DataSizeUnit`. Closes GH-36956 Signed-off-by: Yanming Zhou <zhouyanming@gmail.com>
1 parent 9130ded commit a47aed2

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

spring-core/src/main/java/org/springframework/core/convert/support/NumberToDataSizeConverter.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,20 @@
2323
* Converts from a {@link Number} to a {@link DataSize}.
2424
*
2525
* @author YeongJae Min
26+
* @author Yanming Zhou
2627
* @since 7.1
27-
* @see DataSize#parse(CharSequence)
28+
* @see DataSize#ofBytes(long)
2829
* @see StringToDataSizeConverter
2930
*/
3031
final class NumberToDataSizeConverter implements Converter<Number, DataSize> {
3132

3233
@Override
3334
public DataSize convert(Number source) {
34-
return DataSize.parse(source.toString());
35+
long bytes = source.longValue();
36+
if (source.doubleValue() - bytes != 0) {
37+
throw new IllegalArgumentException("'" + source + "' is not a valid data size");
38+
}
39+
return DataSize.ofBytes(bytes);
3540
}
3641

3742
}

spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@
7676
* @author Juergen Hoeller
7777
* @author Stephane Nicoll
7878
* @author Sam Brannen
79+
* @author YeongJae Min
80+
* @author Yanming Zhou
7981
*/
8082
class DefaultConversionServiceTests {
8183

@@ -258,12 +260,16 @@ void stringToDataSize() {
258260
void numberToDataSizeWithDecimalNumber() {
259261
assertThatExceptionOfType(ConversionFailedException.class)
260262
.isThrownBy(() -> conversionService.convert(10.5, DataSize.class));
263+
assertThatExceptionOfType(ConversionFailedException.class)
264+
.isThrownBy(() -> conversionService.convert(new BigDecimal("10.5"), DataSize.class));
261265
}
262266

263267
@Test // gh-36830
264268
void numberToDataSize() {
265269
assertThat(conversionService.convert(10, DataSize.class)).isEqualTo(DataSize.ofBytes(10));
266270
assertThat(conversionService.convert(-10L, DataSize.class)).isEqualTo(DataSize.ofBytes(-10));
271+
assertThat(conversionService.convert(new BigDecimal("10"), DataSize.class)).isEqualTo(DataSize.ofBytes(10));
272+
assertThat(conversionService.convert(new BigDecimal("10.0"), DataSize.class)).isEqualTo(DataSize.ofBytes(10));
267273
}
268274

269275
@Test

0 commit comments

Comments
 (0)