sdl12-compat: Factor out FreeSurfaceContents, and handle surface20 more defensively

From 3c2bde93d4360516b080f163fafeca78fbf33ba2 Mon Sep 17 00:00:00 2001
From: Simon McVittie <[EMAIL REDACTED]>
Date: Thu, 20 Jul 2023 14:00:08 +0100
Subject: [PATCH] Factor out FreeSurfaceContents, and handle surface20 more
 defensively

This is a step towards making it possible to use the same SDL12_Surface
for the video surface at all times, and only reallocating its underlying
SDL 2 SDL_Surface.

Signed-off-by: Simon McVittie <smcv@debian.org>
---
 src/SDL12_compat.c | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)

diff --git a/src/SDL12_compat.c b/src/SDL12_compat.c
index 531fd73a1..d06225124 100644
--- a/src/SDL12_compat.c
+++ b/src/SDL12_compat.c
@@ -2616,6 +2616,19 @@ SDL_WasInit(Uint32 sdl12flags)
     return InitFlags20to12(SDL20_WasInit(sdl20flags)) | extraflags;
 }
 
+static void
+FreeSurfaceContents(SDL12_Surface *surface12)
+{
+    if (surface12->surface20) {
+        SDL20_FreeSurface(surface12->surface20);
+        surface12->surface20 = NULL;
+    }
+    if (surface12->format) {
+        SDL20_free(surface12->format->palette);
+        SDL20_free(surface12->format);
+        surface12->format = NULL;
+    }
+}
 
 static SDL12_Surface *EndVidModeCreate(void);
 static void
@@ -5223,11 +5236,7 @@ SDL_FreeSurface(SDL12_Surface *surface12)
         surface12->refcount--;
         if (surface12->refcount)
             return;
-        SDL20_FreeSurface(surface12->surface20);
-        if (surface12->format) {
-            SDL20_free(surface12->format->palette);
-            SDL20_free(surface12->format);
-        }
+        FreeSurfaceContents(surface12);
         SDL20_free(surface12);
     }
 }