2N/A/*
2N/A * CDDL HEADER START
2N/A *
2N/A * The contents of this file are subject to the terms of the
2N/A * Common Development and Distribution License (the "License").
2N/A * You may not use this file except in compliance with the License.
2N/A *
2N/A * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
2N/A * or http://www.opensolaris.org/os/licensing.
2N/A * See the License for the specific language governing permissions
2N/A * and limitations under the License.
2N/A *
2N/A * When distributing Covered Code, include this CDDL HEADER in each
2N/A * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
2N/A * If applicable, add the following below this CDDL HEADER, with the
2N/A * fields enclosed by brackets "[]" replaced with your own identifying
2N/A * information: Portions Copyright [yyyy] [name of copyright owner]
2N/A *
2N/A * CDDL HEADER END
2N/A */
2N/A
2N/A/*
2N/A * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
2N/A * Use is subject to license terms.
2N/A */
2N/A
2N/A/*
2N/A * Much like calloc, but with functions to report the size of the
2N/A * allocation given only the pointer.
2N/A */
2N/A
2N/A#include <assert.h>
2N/A#include <string.h>
2N/A#include <malloc.h>
2N/A#include "sized_array.h"
2N/A
2N/A/*
2N/A * Assumes that int is at least 32 bits and that nothing needs more than
2N/A * 8-byte alignment.
2N/A */
2N/A
2N/A/* COOKIE provides some bad-pointer protection. */
2N/A#define COOKIE "SACOOKIE"
2N/A
2N/Astruct sized_array {
2N/A int n;
2N/A int sz;
2N/A#if defined(COOKIE)
2N/A char cookie[8];
2N/A#endif
2N/A};
2N/A
2N/A
2N/Avoid *
2N/Asized_array(size_t n, size_t sz)
2N/A{
2N/A struct sized_array *sa;
2N/A size_t total;
2N/A
2N/A total = sizeof (struct sized_array) + n*sz;
2N/A
2N/A sa = malloc(total);
2N/A
2N/A if (sa == NULL)
2N/A return (NULL);
2N/A
2N/A (void) memset(sa, 0, total);
2N/A
2N/A sa->n = n;
2N/A sa->sz = sz;
2N/A
2N/A#if defined(COOKIE)
2N/A (void) memcpy(sa->cookie, COOKIE, sizeof (sa->cookie));
2N/A#endif
2N/A
2N/A return ((void *)(sa + 1));
2N/A}
2N/A
2N/Avoid
2N/Asized_array_free(void *p)
2N/A{
2N/A struct sized_array *sa;
2N/A
2N/A if (p == NULL)
2N/A return;
2N/A
2N/A sa = ((struct sized_array *)p)-1;
2N/A
2N/A#if defined(COOKIE)
2N/A assert(memcmp(sa->cookie, COOKIE, sizeof (sa->cookie)) == 0);
2N/A#endif
2N/A
2N/A free(sa);
2N/A}
2N/A
2N/Asize_t
2N/Asized_array_n(void *p)
2N/A{
2N/A struct sized_array *sa;
2N/A
2N/A sa = ((struct sized_array *)p)-1;
2N/A
2N/A#if defined(COOKIE)
2N/A assert(memcmp(sa->cookie, COOKIE, sizeof (sa->cookie)) == 0);
2N/A#endif
2N/A
2N/A return (sa->n);
2N/A}
2N/A
2N/Asize_t
2N/Asized_array_sz(void *p)
2N/A{
2N/A struct sized_array *sa;
2N/A
2N/A sa = ((struct sized_array *)p)-1;
2N/A
2N/A#if defined(COOKIE)
2N/A assert(memcmp(sa->cookie, COOKIE, sizeof (sa->cookie)) == 0);
2N/A#endif
2N/A
2N/A return (sa->sz);
2N/A}