/* =============================================================================
 * 06_unions.c  --  unions: one block of memory, several views of it
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - A union's fields all start at offset 0 and share the storage. What does
 *     sizeof a union mean, and how big is it?
 *   - How can a union read the bit pattern of a float (the slides'
 *     bit2float / float2bit)?
 *   - Reading one field after writing another exposes the machine's byte
 *     order. What does little-endian x86-64 show (the slides' dw example)?
 *   - When is a union a good idea (a tagged "sum type"), and when is it a bug?
 *
 * [How to build & run]
 *   make && ./build/04_unions          (native)
 *          ./build/04_unions_x86       (x86-64 under Rosetta 2, if built)
 *
 * [How to read the output]
 *   PART A prints the size and field offsets. PART B round-trips floats
 *   through their bits and checks against Lecture 2's formula. PART C is the
 *   slides' byte-order table. PART D shows a tagged union used safely.
 *
 * [Systems link / CS:APP 3.9.2]
 *   A union says "these interpretations share one storage; I will use one at
 *   a time". The language does not remember which, so a union is only safe
 *   with a separate TAG saying which field is live -- or as a deliberate
 *   reinterpretation of bits, as in bit2float.
 * -------------------------------------------------------------------------- */

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "structs.h"

/* The slides: reinterpret a 32-bit pattern as a float and back. */
typedef union { float f; unsigned u; } bit_float_t;

static float bit2float(unsigned u) { bit_float_t a; a.u = u; return a.f; }
static unsigned float2bit(float f) { bit_float_t a; a.f = f; return a.u; }

/* [Idea] Lecture 2's formula: rebuild the float value from its sign, exponent
 *   and fraction fields, to check that bit2float really reinterprets the bits
 *   rather than converting the number. Returns the value as a double. */
static double float_from_fields(unsigned u)
{
    int sign = (u >> 31) & 1;
    int exp = (u >> 23) & 0xFF;
    unsigned frac = u & 0x7FFFFF;
    double m, e;
    if (exp == 0) {                         /* denormal (or zero) */
        m = frac / 8388608.0;
        e = -126;
    } else if (exp == 0xFF) {
        return frac ? 0.0 / 0.0 : (sign ? -1.0 : 1.0) / 0.0;   /* NaN / +-inf */
    } else {                                /* normalized */
        m = 1.0 + frac / 8388608.0;
        e = exp - 127;
    }
    double val = m;
    for (double k = 0; k < (e < 0 ? -e : e); k++) val = e < 0 ? val / 2 : val * 2;
    return sign ? -val : val;
}

static void part_a(void)
{
    printf("PART A: union U1 { char c; int i[2]; long v; }\n");
    printf("  sizeof = %zu (as large as its biggest field, the 8-byte long)\n", sizeof(union U1));
    union U1 u;
    printf("  offsets: c at %ld, i at %ld, v at %ld  -- all 0: the fields OVERLAP\n",
           (long)((char *)&u.c - (char *)&u), (long)((char *)&u.i - (char *)&u),
           (long)((char *)&u.v - (char *)&u));
    struct SU { char c; int i[2]; long v; };
    printf("  a struct with the same fields is %zu bytes: fields do NOT overlap\n\n",
           sizeof(struct SU));
}

static void part_b(void)
{
    printf("PART B: reading a float's bits with a union (the slides' bit2float/float2bit)\n");
    struct { const char *name; float f; } cases[] = {
        {"1.0", 1.0f}, {"-2.0", -2.0f}, {"0.5", 0.5f}, {"15213.0", 15213.0f},
        {"0.1", 0.1f}, {"0.0", 0.0f},
    };
    int ok = 0, n = (int)(sizeof cases / sizeof cases[0]);
    printf("  %-9s %-12s %-14s %s\n", "value", "float2bit", "rebuilt", "round-trip");
    for (int k = 0; k < n; k++) {
        unsigned bits = float2bit(cases[k].f);
        float back = bit2float(bits);
        double rebuilt = float_from_fields(bits);
        int rt = memcmp(&back, &cases[k].f, sizeof back) == 0;
        int formula = (double)(float)rebuilt == (double)cases[k].f;
        ok += rt && formula;
        printf("  %-9s 0x%08x   %-14.6g %s\n", cases[k].name, bits, rebuilt,
               rt && formula ? "ok" : "MISMATCH");
    }
    printf("  %d of %d: bit2float(float2bit(f)) == f, and the bits match Lecture 2's\n"
           "  field formula. Note: this is NOT (unsigned)f -- a cast CONVERTS the\n"
           "  number (1.0 -> 1), a union REINTERPRETS the bytes (1.0 -> 0x3f800000).\n\n", ok, n);
}

static void part_c(void)
{
    /* The slides' byte-ordering demo. */
    union { unsigned char c[8]; unsigned short s[4]; unsigned int i[2]; unsigned long l[1]; } dw;
    for (int j = 0; j < 8; j++)
        dw.c[j] = 0xf0 + j;
    printf("PART C: one 8-byte object, four views (the slides' dw example)\n");
    printf("  bytes written:  c[0..7] = f0 f1 f2 f3 f4 f5 f6 f7 (low address first)\n");
    printf("  chars  c[0..7] = ");
    for (int j = 0; j < 8; j++) printf("%02x ", dw.c[j]);
    printf("\n  shorts s[0..3] = ");
    for (int j = 0; j < 4; j++) printf("%04x ", dw.s[j]);
    printf("\n  ints   i[0..1] = ");
    for (int j = 0; j < 2; j++) printf("%08x ", dw.i[j]);
    printf("\n  long   l[0]    = %016lx\n", dw.l[0]);
    printf("  Little-endian: the FIRST byte written (f0) is the LEAST significant, so\n"
           "  s[0] reads as f1f0 and l[0] as f7f6f5f4f3f2f1f0. A big-endian machine\n"
           "  would show s[0] = f0f1 and l[0] = f0f1...f7.\n\n");
}

/* A tagged union ("sum type"): the tag says which field is valid. */
typedef union { long i; double d; } num_t;
typedef struct { bool is_double; num_t val; } value_t;

static void print_value(value_t v)
{
    if (v.is_double) printf("double %g", v.val.d);     /* read d only when is_double */
    else             printf("long %ld", v.val.i);      /* read i otherwise */
}

static void part_d(void)
{
    printf("PART D: a union used SAFELY -- a tagged value\n");
    value_t a = {false, {.i = 15213}};
    value_t b = {true, {.d = 3.14}};
    printf("  value_t { bool is_double; union { long i; double d; } }  (sizeof = %zu)\n",
           sizeof(value_t));
    printf("  a = "); print_value(a); printf("\n  b = "); print_value(b); printf("\n");
    printf("  The TAG is_double records which field is live. Reading the other field\n"
           "  would reinterpret the bytes (part B) -- here that would be a bug, not a\n"
           "  feature, so the tag is what makes the union safe.\n\n");
}

int main(void)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#elif defined(__aarch64__)
    const char *arch = "arm64";
#else
    const char *arch = "unknown";
#endif
    printf("=== Demo 06: unions (%s) ===\n\n", arch);
    part_a();
    part_b();
    part_c();
    part_d();
    printf("Observations:\n");
    printf("  * A union is one block of memory as big as its largest field; every field\n"
           "    starts at offset 0, so the fields share the storage.\n");
    printf("  * Writing one field and reading another reinterprets the bytes -- useful\n"
           "    for inspecting a float's bits, and exactly how endianness becomes visible.\n");
    printf("  * The language does not track which field is live. A safe union carries a\n"
           "    separate tag; without one, reading the wrong field is undefined in intent.\n");
    return 0;
}
