Skip to content

Commit

Permalink
improve conversion from number argument to string
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeloffner committed Jan 18, 2024
1 parent 23f5d19 commit e715484
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions source/java/src/lucee/extension/io/cache/util/Coder.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.bson.BsonDocument;
import org.bson.BsonValue;

import lucee.loader.engine.CFMLEngine;
import lucee.loader.engine.CFMLEngineFactory;
import lucee.loader.util.Util;

Expand All @@ -22,6 +25,12 @@ public class Coder {
private static final byte GZIP0 = (byte) 0x1f;
private static final byte GZIP1 = (byte) 0x8b;

private static DecimalFormat ff = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
private static CFMLEngine eng;
static {
ff.applyLocalizedPattern("#.#######");
}

private static byte[] OBJECT_STREAM_HEADER = new byte[] { -84, -19, 0, 5 };

public static final Charset UTF8 = Charset.forName("UTF-8");
Expand Down Expand Up @@ -133,11 +142,32 @@ private static boolean isObjectStream(byte[] data) {
}

public static byte[] serialize(Object value) throws IOException {
if (eng == null) {
// this fails when executed outside a Lucee engine
try {
eng = CFMLEngineFactory.getInstance();
}
catch (Exception e) {
}
}
if (value instanceof CharSequence) {
return toBytes(value.toString());
try {
return toBytes(eng.getCastUtil().toString(value));
}
catch (Exception e) {
return toBytes(value.toString());
}
}
if (value instanceof Number) {
return toBytes(value.toString());
if (value instanceof Float) { // avoid bug in older Lucee version
return toBytes(toString(((Float) value).floatValue()));
}
try {
return toBytes(eng.getCastUtil().toString(value));
}
catch (Exception e) {
return toBytes(value.toString());
}
}

BsonDocument doc = BSON.toBsonDocument(value, false, null);
Expand Down Expand Up @@ -186,4 +216,13 @@ public static boolean isGzip(byte[] barr) throws IOException {
return barr != null && barr.length > 1 && barr[0] == GZIP0 && barr[1] == GZIP1;
}

private static String toString(float f) {
long l = (long) f;
if (l == f) return Long.toString(l, 10);

if (f > l && (f - l) < 0.000000000001) return Long.toString(l, 10);
if (l > f && (l - f) < 0.000000000001) return Long.toString(l, 10);

return ff.format(f);
}
}

0 comments on commit e715484

Please sign in to comment.