Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

C#: pass NaN and infinity between C# and the port

Mohit Mishra401ed98dfbd1
diff --git a/src/csharp.rs b/src/csharp.rs
index fa3ed75..e9a7e7c 100644
--- a/src/csharp.rs
+++ b/src/csharp.rs
@@ -650,7 +650,7 @@ pub const FLAVOR: Flavor = Flavor {
"`ToLowerInvariant` maps one UTF-16 unit at a time; Rust's `to_lowercase` can differ on a few characters (İ, final sigma). `Split((char[]?)null)` splits on Unicode whitespace, like `split_whitespace`.",
"Arrays and lists arrive as JSON arrays, dictionaries as objects with string keys.",
],
- floats: None,
+ floats: Some(native::FLOATS),
};
pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
@@ -712,6 +712,54 @@ pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn json_carries_nan_and_infinity() {
+ let Some(version) = Command::new("dotnet").arg("--version").output().ok().filter(|o| o.status.success()) else {
+ eprintln!("no dotnet on PATH, skipping");
+ return;
+ };
+ let major = String::from_utf8_lossy(&version.stdout).split('.').next().unwrap_or("8").trim().to_string();
+ let dir = std::env::temp_dir().join(format!("fa-cs-json-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(
+ dir.join("Check.csproj"),
+ format!("<Project Sdk=\"Microsoft.NET.Sdk\"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net{major}.0</TargetFramework><Nullable>enable</Nullable></PropertyGroup></Project>"),
+ )
+ .unwrap();
+ let usings = "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n";
+ fs::write(dir.join("Json.cs"), format!("{usings}static class Holder\n{{\n{JSON}\n}}\n")).unwrap();
+ let check = r#"using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+var inv = CultureInfo.InvariantCulture;
+Console.WriteLine(Holder.Json.Enc(new object?[] { double.NaN, -0.5, float.PositiveInfinity, new[] { 1.0, double.NegativeInfinity } }));
+var d = (double[])Holder.Json.Dec(JsonNode.Parse("""[1.5,{"$float":"NaN"},{"$float":"-Infinity"}]"""), typeof(double[]))!;
+Console.WriteLine($"{d[0].ToString(inv)} {double.IsNaN(d[1])} {double.IsNegativeInfinity(d[2])}");
+Console.WriteLine(float.IsPositiveInfinity((float)Holder.Json.Dec(JsonNode.Parse("""{"$float":"Infinity"}"""), typeof(float))!));
+var m = JsonSerializer.Deserialize<Dictionary<string, double?>>("""{"a":{"$float":"NaN"},"b":null}""", Holder.Json.Options)!;
+Console.WriteLine($"{double.IsNaN(m["a"]!.Value)} {m["b"] is null}");
+Console.WriteLine(JsonSerializer.Serialize(new[] { double.PositiveInfinity, 2.5 }, Holder.Json.Options));
+try { Holder.Json.Dec(JsonNode.Parse("""{"$float":"nan"}"""), typeof(double)); Console.WriteLine("no error"); }
+catch (JsonException) { Console.WriteLine("error"); }
+"#;
+ fs::write(dir.join("Program.cs"), check).unwrap();
+ let run = Command::new("dotnet").args(["run", "--nologo"]).current_dir(&dir).output().unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(
+ run.status.success(),
+ "{}{}",
+ String::from_utf8_lossy(&run.stdout),
+ String::from_utf8_lossy(&run.stderr)
+ );
+ assert_eq!(
+ String::from_utf8_lossy(&run.stdout).replace("\r\n", "\n"),
+ "[{\"$float\":\"NaN\"},-0.5,{\"$float\":\"Infinity\"},[1.0,{\"$float\":\"-Infinity\"}]]\n\
+ 1.5 True True\nTrue\nTrue True\n[{\"$float\":\"Infinity\"},2.5]\nerror\n"
+ );
+ }
+
#[test]
fn csharp_bits() {
assert_eq!(rust_type("int[][]").as_deref(), Some("Vec<Vec<i32>>"));
diff --git a/src/csharp/Json.cs b/src/csharp/Json.cs
index 8d066d3..3fbaa03 100644
--- a/src/csharp/Json.cs
+++ b/src/csharp/Json.cs
@@ -12,9 +12,56 @@
{
var o = new JsonSerializerOptions();
o.Converters.Add(new BytesAsNumbers());
+ o.Converters.Add(new DoubleTags());
+ o.Converters.Add(new FloatTags());
return o;
}
+ // NaN and infinity travel as {"$float": name}: JSON has no numbers for them
+ static string FloatName(double d) => double.IsNaN(d) ? "NaN" : d > 0 ? "Infinity" : "-Infinity";
+
+ static double ReadDouble(ref Utf8JsonReader r)
+ {
+ if (r.TokenType == JsonTokenType.Number) return r.GetDouble();
+ if (r.TokenType == JsonTokenType.StartObject && r.Read() && r.TokenType == JsonTokenType.PropertyName
+ && r.GetString() == "$float" && r.Read() && r.TokenType == JsonTokenType.String)
+ {
+ double d = r.GetString() switch
+ {
+ "NaN" => double.NaN,
+ "Infinity" => double.PositiveInfinity,
+ "-Infinity" => double.NegativeInfinity,
+ _ => throw new JsonException("not a number"),
+ };
+ if (r.Read() && r.TokenType == JsonTokenType.EndObject) return d;
+ }
+ throw new JsonException("not a number");
+ }
+
+ static void WriteDouble(Utf8JsonWriter w, double d, Action<Utf8JsonWriter> finite)
+ {
+ if (double.IsFinite(d))
+ {
+ finite(w);
+ return;
+ }
+ w.WriteStartObject();
+ w.WriteString("$float", FloatName(d));
+ w.WriteEndObject();
+ }
+
+ sealed class DoubleTags : JsonConverter<double>
+ {
+ public override double Read(ref Utf8JsonReader r, Type t, JsonSerializerOptions o) => ReadDouble(ref r);
+ public override void Write(Utf8JsonWriter w, double v, JsonSerializerOptions o) => WriteDouble(w, v, x => x.WriteNumberValue(v));
+ }
+
+ sealed class FloatTags : JsonConverter<float>
+ {
+ public override float Read(ref Utf8JsonReader r, Type t, JsonSerializerOptions o) => (float)ReadDouble(ref r);
+ public override void Write(Utf8JsonWriter w, float v, JsonSerializerOptions o) => WriteDouble(w, v, x => x.WriteNumberValue(v));
+ }
+
// byte[] travels as a list of numbers, like every other array (System.Text.Json would use base64)
sealed class BytesAsNumbers : JsonConverter<byte[]>
{
@@ -62,12 +109,12 @@
b.Append(((IFormattable)v).ToString(null, inv));
break;
case double d:
- if (!double.IsFinite(d)) throw new Unsupported("NaN or Infinity");
- Number(d.ToString("R", inv), b);
+ if (!double.IsFinite(d)) b.Append("{\"$float\":\"").Append(FloatName(d)).Append("\"}");
+ else Number(d.ToString("R", inv), b);
break;
case float f:
- if (!float.IsFinite(f)) throw new Unsupported("NaN or Infinity");
- Number(f.ToString("R", inv), b);
+ if (!float.IsFinite(f)) b.Append("{\"$float\":\"").Append(FloatName(f)).Append("\"}");
+ else Number(f.ToString("R", inv), b);
break;
case IDictionary m:
{
diff --git a/src/csharp/Rec.cs b/src/csharp/Rec.cs
index 8a65c56..b919f19 100644
--- a/src/csharp/Rec.cs
+++ b/src/csharp/Rec.cs
@@ -104,14 +104,18 @@ static class FastAnythingRec
return t.IsGenericType ? t.GetGenericArguments()[^1] : typeof(object);
}
- // Special values for one argument: zero and ±1, -0.0, non-ASCII text, empty collections.
+ // Special values for one argument: zero and ±1, -0.0, NaN and ±infinity, non-ASCII text, empty collections.
static IEnumerable<JsonNode?> Edges(JsonNode? v, Type t)
{
var u = Nullable.GetUnderlyingType(t) ?? t;
if (u == typeof(string)) foreach (var s in Texts) yield return JsonValue.Create(s);
else if (u == typeof(char)) foreach (var s in new[] { "a", "é", "日", " " }) yield return JsonValue.Create(s);
else if (u == typeof(bool)) { yield return JsonValue.Create(true); yield return JsonValue.Create(false); }
- else if (u == typeof(double) || u == typeof(float)) foreach (var d in new[] { 0.0, -0.0, 1.0, -1.0, 0.5 }) yield return JsonValue.Create(d);
+ else if (u == typeof(double) || u == typeof(float))
+ {
+ foreach (var d in new[] { 0.0, -0.0, 1.0, -1.0, 0.5 }) yield return JsonValue.Create(d);
+ foreach (var name in new[] { "NaN", "Infinity", "-Infinity" }) yield return new JsonObject { ["$float"] = name };
+ }
else if (u.IsPrimitive) foreach (var i in new[] { 0, 1, -1 }) yield return JsonValue.Create(i);
else if (v is JsonArray arr)
{