Skip to content

Commit

Permalink
Fix ArgumentValidation.getDouble32()
Browse files Browse the repository at this point in the history
Float precision check would unexpectedly throw an exception on certain valid values. This changes it to a range check.
PseudoKnight committed Apr 7, 2024
1 parent a1c7f5d commit e0ce000
Showing 2 changed files with 25 additions and 11 deletions.
16 changes: 5 additions & 11 deletions src/main/java/com/laytonsmith/core/ArgumentValidation.java
Original file line number Diff line number Diff line change
@@ -197,26 +197,20 @@ public static double getDouble(Mixed c, Target t) {
}

/**
* Returns a 32 bit float from the construct. Since the backing value is actually a double, if the number contained
* in the construct is not the same after truncating, an exception is thrown (fail fast). When needing an float from
* a construct, this method is much preferred over silently truncating.
* Returns a 32-bit float from the construct. Since the backing value is actually a double, if the number contained
* in the construct is not within range after truncating, an exception is thrown (fail fast). When needing a float
* from a construct, this method is much preferred over silently truncating.
*
* @param c
* @param t
* @return
*/
public static float getDouble32(Mixed c, Target t) {
if(c instanceof CMutablePrimitive) {
c = ((CMutablePrimitive) c).get();
}
// Use 6 places at most else the imprecisions of float makes this function throw the exception.
double delta = 0.0000001;
double l = getDouble(c, t);
float f = (float) l;
if(Math.abs(f - l) > delta) {
if(l > Float.MAX_VALUE || l < Float.MIN_VALUE) {
throw new CRERangeException("Expecting a 32 bit float, but a larger value was found: " + l, t);
}
return f;
return (float) l;
}

/**
20 changes: 20 additions & 0 deletions src/main/java/com/laytonsmith/core/functions/ByteArrays.java
Original file line number Diff line number Diff line change
@@ -478,6 +478,11 @@ public String getName() {
return "ba_put_byte";
}

@Override
public Class<? extends CREThrowable>[] thrown() {
return new Class[]{CRECastException.class, CRERangeException.class};
}

}

@api
@@ -542,6 +547,11 @@ public String getName() {
return "ba_put_short";
}

@Override
public Class<? extends CREThrowable>[] thrown() {
return new Class[]{CRECastException.class, CRERangeException.class};
}

}

@api
@@ -571,6 +581,11 @@ public MSVersion since() {
public String getName() {
return "ba_put_int";
}

@Override
public Class<? extends CREThrowable>[] thrown() {
return new Class[]{CRECastException.class, CRERangeException.class};
}
}

@api
@@ -631,6 +646,11 @@ public String getName() {
return "ba_put_float";
}

@Override
public Class<? extends CREThrowable>[] thrown() {
return new Class[]{CRECastException.class, CRERangeException.class};
}

}

@api

0 comments on commit e0ce000

Please sign in to comment.