/*
 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL). See the LICENSE file in the root
 * directory for license terms. You may choose either license, or both.
 */

#include <string.h>
#include "util_memory.h"

#ifdef IOTCS_USE_STATIC_HEAP
#include <string.h> /* memset */
#include "external/umm_malloc/umm_malloc.h"

#ifdef IOTCS_MEM_STATISTIC
static unsigned int max_allocted = 0;
static unsigned int cur_allocted = 0;

static void update_stats(void) {
    umm_info(NULL, 0);
    cur_allocted = heapInfo.usedBlocks * 8;
    if (max_allocted < cur_allocted) {
        max_allocted = cur_allocted;
    }
}
#else
#define update_stats()
#endif /* IOTCS_MEM_STATISTIC */

#else
#include <stdlib.h>
#endif /* IOTCS_USE_STATIC_HEAP */

#include "iotcs_port_memory.h"

void* util_malloc(size_t size) {
#ifdef IOTCS_USE_STATIC_HEAP
    void* ptr = umm_malloc(size);
    update_stats();
    return ptr;
#else
    return iotcs_port_malloc(size);
#endif
}

void* util_calloc(size_t num, size_t size) {

    void* ptr = util_malloc(num * size);
    if (ptr)
        memset(ptr, 0, num * size);
    return ptr;
}

void util_free(void* ptr) {

#ifdef IOTCS_USE_STATIC_HEAP
    umm_free(ptr);
    update_stats();
#else
    iotcs_port_free(ptr);
#endif
}


