Просмотр исходного кода

libdpkg: Add new varbuf_trunc() function

Guillem Jover лет назад: 16
Родитель
Сommit
1433317d2f
4 измененных файлов с 33 добавлено и 0 удалено
  1. 1 0
      lib/dpkg/libdpkg.Versions
  2. 21 0
      lib/dpkg/test/t-varbuf.c
  3. 10 0
      lib/dpkg/varbuf.c
  4. 1 0
      lib/dpkg/varbuf.h

+ 1 - 0
lib/dpkg/libdpkg.Versions

@@ -50,6 +50,7 @@ LIBDPKG_PRIVATE {
 	varbufinit;
 	varbufreset;
 	varbuf_grow;
+	varbuf_trunc;
 	varbufaddc;
 	varbufdupc;
 	varbufsubstc;

+ 21 - 0
lib/dpkg/test/t-varbuf.c

@@ -91,6 +91,26 @@ test_varbuf_grow(void)
 	varbuf_destroy(&vb);
 }
 
+static void
+test_varbuf_trunc(void)
+{
+	struct varbuf vb;
+
+	varbufinit(&vb, 50);
+
+	/* Test that we truncate (grow). */
+	varbuf_trunc(&vb, 20);
+	test_pass(vb.used == 20);
+	test_pass(vb.size >= 50);
+
+	/* Test that we truncate (shrink). */
+	varbuf_trunc(&vb, 10);
+	test_pass(vb.used == 10);
+	test_pass(vb.size >= 50);
+
+	varbuf_destroy(&vb);
+}
+
 static void
 test_varbuf_addbuf(void)
 {
@@ -252,6 +272,7 @@ test(void)
 	test_varbuf_init();
 	test_varbuf_prealloc();
 	test_varbuf_grow();
+	test_varbuf_trunc();
 	test_varbuf_addbuf();
 	test_varbuf_addc();
 	test_varbuf_dupc();

+ 10 - 0
lib/dpkg/varbuf.c

@@ -128,6 +128,16 @@ varbuf_grow(struct varbuf *v, size_t need_size)
   v->buf = m_realloc(v->buf, v->size);
 }
 
+void
+varbuf_trunc(struct varbuf *v, size_t used_size)
+{
+  /* Make sure the caller does not claim more than available. */
+  if (v->size < used_size)
+    internerr("varbuf: claimed used(%zu) > size(%zu)", v->used, v->size);
+
+  v->used = used_size;
+}
+
 char *
 varbuf_detach(struct varbuf *v)
 {

+ 1 - 0
lib/dpkg/varbuf.h

@@ -66,6 +66,7 @@ struct varbuf {
 
 void varbufinit(struct varbuf *v, size_t size);
 void varbuf_grow(struct varbuf *v, size_t need_size);
+void varbuf_trunc(struct varbuf *v, size_t used_size);
 char *varbuf_detach(struct varbuf *v);
 void varbufreset(struct varbuf *v);
 void varbuf_destroy(struct varbuf *v);