11using System . Diagnostics . CodeAnalysis ;
2- using System . Globalization ;
32using System . Text . Json ;
43using System . Text . Json . Serialization ;
54
6- using Rustic ;
5+ using Superpower ;
6+ using Superpower . Model ;
77
8- namespace SurrealDB . Json ;
8+ namespace SurrealDB . Json . Time ;
99
1010public sealed class DateOnlyConv : JsonConverter < DateOnly > {
1111 public override DateOnly Read ( ref Utf8JsonReader reader , Type typeToConvert , JsonSerializerOptions options ) {
@@ -28,34 +28,27 @@ public override void WriteAsPropertyName(Utf8JsonWriter writer, DateOnly value,
2828 writer . WritePropertyName ( ToString ( in value ) ) ;
2929 }
3030
31- public static DateOnly Parse ( in ReadOnlySpan < char > str ) {
32- ReadOnlySpan < char > slc , rem = str ;
33- slc = rem . Slice ( 0 , 4 ) ;
34- rem = rem . Slice ( 4 ) ;
35- int y = Int32 . Parse ( slc , NumberStyles . Integer , NumberFormatInfo . InvariantInfo ) ;
36- slc = rem . Slice ( 1 , 2 ) ;
37- rem = rem . Slice ( 3 ) ;
38- int m = Int32 . Parse ( slc , NumberStyles . Integer , NumberFormatInfo . InvariantInfo ) ;
39- slc = rem . Slice ( 1 , 2 ) ;
40- int d = Int32 . Parse ( slc , NumberStyles . Integer , NumberFormatInfo . InvariantInfo ) ;
41- return new ( y , m , d ) ;
31+ public static DateOnly Parse ( string ? s ) {
32+ return TryParse ( s , out DateOnly value ) ? value : ThrowParseInvalid ( s ) ;
4233 }
43-
44- // Needs 10 chars
45- public static void ToString ( ref StrBuilder builder , in DateOnly dt ) {
46- dt . Year . TryFormat ( builder . AppendSpan ( 4 ) , out _ , "0000" , NumberFormatInfo . InvariantInfo ) ;
47- builder . Append ( '-' ) ;
48- dt . Month . TryFormat ( builder . AppendSpan ( 2 ) , out _ , "00" , NumberFormatInfo . InvariantInfo ) ;
49- builder . Append ( '-' ) ;
50- dt . Day . TryFormat ( builder . AppendSpan ( 2 ) , out _ , "00" , NumberFormatInfo . InvariantInfo ) ;
34+ public static bool TryParse ( string ? s , out DateOnly value ) {
35+ if ( String . IsNullOrEmpty ( s ) ) {
36+ return false ;
37+ }
38+ Result < DateOnly > res = TimeParsers . IsoDate ( new TextSpan ( s ) ) ;
39+ value = res . HasValue ? res . Value : default ;
40+ return res . HasValue ;
5141 }
5242
53- public static string ToString ( in DateOnly dt ) {
54- StrBuilder builder = new ( stackalloc char [ 11 ] ) ;
55- ToString ( ref builder , dt ) ;
56- return builder . ToString ( ) ;
43+ public static string ToString ( in DateOnly value ) {
44+ return $ "{ value . Year . ToString ( "D4" ) } -{ value . Month . ToString ( "D2" ) } -{ value . Day . ToString ( "D2" ) } ";
5745 }
5846
47+ [ DoesNotReturn ]
48+ private static DateOnly ThrowParseInvalid ( string ? s ) {
49+ throw new ParseException ( $ "Unable to parse DateOnly from `{ s } `") ;
50+ }
51+
5952 [ DoesNotReturn ]
6053 private DateOnly ThrowJsonTokenTypeInvalid ( ) {
6154 throw new JsonException ( "Cannot deserialize a non string token as a DateOnly." ) ;
0 commit comments