cmark

My personal build of CMark ✏️

Commit
fc1299a51ede05b3a76ae2f5a3ce882741a43a8b
Parent
27376c2150df53d23995c0360a30152f68af5e7c
Author
Vicent Marti <tanoku@gmail.com>
Date

mem: Add a `realloc` pointer to the memory handler

Diffstat

5 files changed, 19 insertions, 20 deletions

Status File Name N° Changes Insertions Deletions
Modified man/man3/cmark.3 3 2 1
Modified src/blocks.c 13 1 12
Modified src/buffer.c 8 1 7
Modified src/cmark.c 14 14 0
Modified src/cmark.h 1 1 0
diff --git a/man/man3/cmark.3 b/man/man3/cmark.3
@@ -1,4 +1,4 @@
-.TH cmark 3 "June 02, 2016" "LOCAL" "Library Functions Manual"
+.TH cmark 3 "June 06, 2016" "LOCAL" "Library Functions Manual"
 .SH
 NAME
 .PP
@@ -104,6 +104,7 @@ Custom memory allocator support
 .RS 0n
 typedef struct cmark_mem {
 	void *(*calloc)(size_t, size_t);
+	void *(*realloc)(void *, size_t);
 	void (*free)(void *);
 } cmark_mem;
 .RE
diff --git a/src/blocks.c b/src/blocks.c
@@ -106,19 +106,8 @@ cmark_parser *cmark_parser_new2(int options, cmark_mem *mem) {
   return parser;
 }
 
-static void *xcalloc(size_t nmem, size_t size) {
-  void *ptr = calloc(nmem, size);
-  if (!ptr) abort();
-  return ptr;
-}
-
-static void xfree(void *ptr) {
-  free(ptr);
-}
-
-cmark_mem DEFAULT_MEM_ALLOCATOR = { xcalloc, xfree };
-
 cmark_parser *cmark_parser_new(int options) {
+  extern cmark_mem DEFAULT_MEM_ALLOCATOR;
   return cmark_parser_new2(options, &DEFAULT_MEM_ALLOCATOR);
 }
 
diff --git a/src/buffer.c b/src/buffer.c
@@ -50,14 +50,8 @@ void cmark_strbuf_grow(cmark_strbuf *buf, bufsize_t target_size) {
   new_size += 1;
   new_size = (new_size + 7) & ~7;
 
-  unsigned char *new_ptr = buf->mem->calloc(new_size, 1);
-  if (buf->ptr != cmark_strbuf__initbuf) {
-    memcpy(new_ptr, buf->ptr, buf->size);
-    buf->mem->free(buf->ptr);
-  }
-
+  buf->ptr = buf->mem->realloc(buf->asize ? buf->ptr : NULL, new_size);
   buf->asize = new_size;
-  buf->ptr = new_ptr;
 }
 
 bufsize_t cmark_strbuf_len(const cmark_strbuf *buf) { return buf->size; }
diff --git a/src/cmark.c b/src/cmark.c
@@ -10,6 +10,20 @@ int cmark_version() { return CMARK_VERSION; }
 
 const char *cmark_version_string() { return CMARK_VERSION_STRING; }
 
+static void *xcalloc(size_t nmem, size_t size) {
+  void *ptr = calloc(nmem, size);
+  if (!ptr) abort();
+  return ptr;
+}
+
+static void *xrealloc(void *ptr, size_t size) {
+  void *new_ptr = realloc(ptr, size);
+  if (!new_ptr) abort();
+  return new_ptr;
+}
+
+cmark_mem DEFAULT_MEM_ALLOCATOR = { xcalloc, xrealloc, free };
+
 char *cmark_markdown_to_html(const char *text, size_t len, int options) {
   cmark_node *doc;
   char *result;
diff --git a/src/cmark.h b/src/cmark.h
@@ -97,6 +97,7 @@ typedef struct cmark_iter cmark_iter;
  */
 typedef struct cmark_mem {
 	void *(*calloc)(size_t, size_t);
+	void *(*realloc)(void *, size_t);
 	void (*free)(void *);
 } cmark_mem;