aboutsummaryrefslogtreecommitdiff
path: root/src/square.c
blob: 8aef28305f63afc739bcfaa43a4f0d732fc9bdc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdlib.h>
#include <stddef.h>
#include "square.h"

struct square
{
    double width;
};

/* Shape interface */

double shape_area_impl(struct shape *shape)
{
    struct square *square = ((void *)shape) + shape_sizeof();
    return square_area(square);
}

void shape_destroy_impl(struct shape *shape)
{
    struct square *square = ((void *)shape) + shape_sizeof();
    square_destroy(square);
}

struct shape *square_as_shape(struct square *square)
{
    return ((void *)square) - shape_sizeof();
}

/* End of shape interface */

struct square *square_create(double width)
{
    struct shape *shape = malloc(shape_sizeof() + sizeof(struct square));
    struct square *square = ((void *)shape) + shape_sizeof();
    square->width = width;

    shape_init(shape, shape_area_impl, shape_destroy_impl);
    return square;
}

double square_area(struct square *square)
{
    return square->width * square->width;
}

void square_destroy(struct square *square)
{
    free(((void *)square) - shape_sizeof());
}