1 /**********************************************************************
2 * Copyright (c) 2017 Andrew Poelstra *
3 * Distributed under the MIT software license, see the accompanying *
4 * file COPYING or http://www.opensource.org/licenses/mit-license.php.*
5 **********************************************************************/
7 #ifndef _SECP256K1_SCRATCH_IMPL_H_
8 #define _SECP256K1_SCRATCH_IMPL_H_
13 static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t size) {
14 const size_t base_alloc = ROUND_TO_ALIGN(sizeof(secp256k1_scratch));
15 void *alloc = checked_malloc(error_callback, base_alloc + size);
16 secp256k1_scratch* ret = (secp256k1_scratch *)alloc;
18 memset(ret, 0, sizeof(*ret));
19 memcpy(ret->magic, "scratch", 8);
20 ret->data = (void *) ((char *) alloc + base_alloc);
26 static void secp256k1_scratch_destroy(const secp256k1_callback* error_callback, secp256k1_scratch* scratch) {
27 if (scratch != NULL) {
28 VERIFY_CHECK(scratch->alloc_size == 0); /* all checkpoints should be applied */
29 if (memcmp(scratch->magic, "scratch", 8) != 0) {
30 secp256k1_callback_call(error_callback, "invalid scratch space");
33 memset(scratch->magic, 0, sizeof(scratch->magic));
38 static size_t secp256k1_scratch_checkpoint(const secp256k1_callback* error_callback, const secp256k1_scratch* scratch) {
39 if (memcmp(scratch->magic, "scratch", 8) != 0) {
40 secp256k1_callback_call(error_callback, "invalid scratch space");
43 return scratch->alloc_size;
46 static void secp256k1_scratch_apply_checkpoint(const secp256k1_callback* error_callback, secp256k1_scratch* scratch, size_t checkpoint) {
47 if (memcmp(scratch->magic, "scratch", 8) != 0) {
48 secp256k1_callback_call(error_callback, "invalid scratch space");
51 if (checkpoint > scratch->alloc_size) {
52 secp256k1_callback_call(error_callback, "invalid checkpoint");
55 scratch->alloc_size = checkpoint;
58 static size_t secp256k1_scratch_max_allocation(const secp256k1_callback* error_callback, const secp256k1_scratch* scratch, size_t objects) {
59 if (memcmp(scratch->magic, "scratch", 8) != 0) {
60 secp256k1_callback_call(error_callback, "invalid scratch space");
63 /* Ensure that multiplication will not wrap around */
64 if (ALIGNMENT > 1 && objects > SIZE_MAX/(ALIGNMENT - 1)) {
67 if (scratch->max_size - scratch->alloc_size <= objects * (ALIGNMENT - 1)) {
70 return scratch->max_size - scratch->alloc_size - objects * (ALIGNMENT - 1);
73 static void *secp256k1_scratch_alloc(const secp256k1_callback* error_callback, secp256k1_scratch* scratch, size_t size) {
77 rounded_size = ROUND_TO_ALIGN(size);
78 /* Check that rounding did not wrap around */
79 if (rounded_size < size) {
84 if (memcmp(scratch->magic, "scratch", 8) != 0) {
85 secp256k1_callback_call(error_callback, "invalid scratch space");
89 if (size > scratch->max_size - scratch->alloc_size) {
92 ret = (void *) ((char *) scratch->data + scratch->alloc_size);
94 scratch->alloc_size += size;