@@ -220,7 +220,12 @@ internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSeriali
220220 // Remember if we were a continuation here since Push() may affect IsContinuation.
221221 bool wasContinuation = state . IsContinuation ;
222222
223+ #if DEBUG
224+ // DEBUG: ensure push/pop operations preserve stack integrity
225+ JsonTypeInfo originalJsonTypeInfo = state . Current . JsonTypeInfo ;
226+ #endif
223227 state . Push ( ) ;
228+ Debug . Assert ( TypeToConvert . IsAssignableFrom ( state . Current . JsonTypeInfo . Type ) ) ;
224229
225230#if ! DEBUG
226231 // For performance, only perform validation on internal converters on debug builds.
@@ -257,6 +262,9 @@ internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSeriali
257262
258263 value = default ;
259264 state . Pop ( true ) ;
265+ #if DEBUG
266+ Debug . Assert ( ReferenceEquals ( originalJsonTypeInfo , state . Current . JsonTypeInfo ) ) ;
267+ #endif
260268 return true ;
261269 }
262270
@@ -288,6 +296,9 @@ internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSeriali
288296 }
289297
290298 state . Pop ( success ) ;
299+ #if DEBUG
300+ Debug . Assert ( ReferenceEquals ( originalJsonTypeInfo , state . Current . JsonTypeInfo ) ) ;
301+ #endif
291302 return success ;
292303 }
293304
@@ -298,6 +309,9 @@ internal override sealed bool TryReadAsObject(ref Utf8JsonReader reader, JsonSer
298309 return success ;
299310 }
300311
312+ /// <summary>
313+ /// Overridden by the nullable converter to prevent boxing of values by the JIT.
314+ /// </summary>
301315 internal virtual bool IsNull ( in T value ) => value == null ;
302316
303317 internal bool TryWrite ( Utf8JsonWriter writer , in T value , JsonSerializerOptions options , ref WriteStack state )
@@ -416,7 +430,12 @@ internal bool TryWrite(Utf8JsonWriter writer, in T value, JsonSerializerOptions
416430
417431 bool isContinuation = state . IsContinuation ;
418432
433+ #if DEBUG
434+ // DEBUG: ensure push/pop operations preserve stack integrity
435+ JsonTypeInfo originalJsonTypeInfo = state . Current . JsonTypeInfo ;
436+ #endif
419437 state . Push ( ) ;
438+ Debug . Assert ( TypeToConvert . IsAssignableFrom ( state . Current . JsonTypeInfo . Type ) ) ;
420439
421440 if ( ! isContinuation )
422441 {
@@ -432,6 +451,9 @@ internal bool TryWrite(Utf8JsonWriter writer, in T value, JsonSerializerOptions
432451 }
433452
434453 state . Pop ( success ) ;
454+ #if DEBUG
455+ Debug . Assert ( ReferenceEquals ( originalJsonTypeInfo , state . Current . JsonTypeInfo ) ) ;
456+ #endif
435457
436458 if ( ignoreCyclesPopReference )
437459 {
0 commit comments