From f2795aa71c48fac397ae16f0d3b633d252b7bc9f Mon Sep 17 00:00:00 2001 From: William Casarin Date: Sat, 30 Dec 2023 06:30:32 -0800 Subject: [PATCH] nostrdb/blocks: add ndb_blocks_free In some situations we will need to have owned note blocks. For example, when we try to fetch note blocks from the database and it's not there yet. We will need to parse the content on the spot and return an owned copy, since it will not be immediately available in the database. Add a new flag field to note blocks that lets us know if it's owned by malloc or nostrdb. We the add a free function that checks this flag and frees the object if its set. If it is not set then it doesn nothing because it likely came from the database. Signed-off-by: William Casarin --- nostrdb/src/block.c | 7 +++++++ nostrdb/src/block.h | 5 ++++- nostrdb/src/content_parser.c | 1 + nostrdb/src/nostrdb.h | 2 ++ 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/nostrdb/src/block.c b/nostrdb/src/block.c index c2ef49d2..ec06b810 100644 --- a/nostrdb/src/block.c +++ b/nostrdb/src/block.c @@ -201,3 +201,10 @@ struct nostr_bech32 *ndb_bech32_block(struct ndb_block *block) { size_t ndb_blocks_total_size(struct ndb_blocks *blocks) { return blocks->total_size; } + +void ndb_blocks_free(struct ndb_blocks *blocks) { + if ((blocks->flags & NDB_BLOCK_FLAG_OWNED) != NDB_BLOCK_FLAG_OWNED) + return; + + free(blocks); +} diff --git a/nostrdb/src/block.h b/nostrdb/src/block.h index 93c98821..0af32d0b 100644 --- a/nostrdb/src/block.h +++ b/nostrdb/src/block.h @@ -9,11 +9,14 @@ #include "nostrdb.h" #include +#define NDB_BLOCK_FLAG_OWNED 1 + #pragma pack(push, 1) struct ndb_blocks { unsigned char version; - unsigned char padding[3]; + unsigned char flags; + unsigned char padding[2]; uint32_t words; uint32_t num_blocks; diff --git a/nostrdb/src/content_parser.c b/nostrdb/src/content_parser.c index 6c961bb8..a83ba933 100644 --- a/nostrdb/src/content_parser.c +++ b/nostrdb/src/content_parser.c @@ -536,6 +536,7 @@ int ndb_parse_content(unsigned char *buf, int buf_size, parser.blocks->words = 0; parser.blocks->num_blocks = 0; parser.blocks->blocks_size = 0; + parser.blocks->flags = 0; blocks_start = start = parser.content.p; while (parser.content.p < parser.content.end) { diff --git a/nostrdb/src/nostrdb.h b/nostrdb/src/nostrdb.h index 6eae9fee..05039a6d 100644 --- a/nostrdb/src/nostrdb.h +++ b/nostrdb/src/nostrdb.h @@ -471,6 +471,8 @@ int ndb_parse_content(unsigned char *buf, int buf_size, enum ndb_block_type ndb_block_type(struct ndb_blocks *blocks); size_t ndb_blocks_total_size(struct ndb_blocks *blocks); +/// Free blocks if they are owned, safe to call on unowned blocks as well. +void ndb_blocks_free(struct ndb_blocks *blocks); // BLOCK ITERATORS