Coverage Report

Created: 2025-07-12 07:07

/src/irssi/subprojects/glib-2.74.3/glib/gbytes.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright © 2009, 2010 Codethink Limited
3
 * Copyright © 2011 Collabora Ltd.
4
 *
5
 * SPDX-License-Identifier: LGPL-2.1-or-later
6
 *
7
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19
 *
20
 * Author: Ryan Lortie <desrt@desrt.ca>
21
 *         Stef Walter <stefw@collabora.co.uk>
22
 */
23
24
#include "config.h"
25
26
#include "gbytes.h"
27
28
#include <glib/garray.h>
29
#include <glib/gstrfuncs.h>
30
#include <glib/gatomic.h>
31
#include <glib/gslice.h>
32
#include <glib/gtestutils.h>
33
#include <glib/gmem.h>
34
#include <glib/gmessages.h>
35
#include <glib/grefcount.h>
36
37
#include <string.h>
38
39
/**
40
 * GBytes:
41
 *
42
 * A simple refcounted data type representing an immutable sequence of zero or
43
 * more bytes from an unspecified origin.
44
 *
45
 * The purpose of a #GBytes is to keep the memory region that it holds
46
 * alive for as long as anyone holds a reference to the bytes.  When
47
 * the last reference count is dropped, the memory is released. Multiple
48
 * unrelated callers can use byte data in the #GBytes without coordinating
49
 * their activities, resting assured that the byte data will not change or
50
 * move while they hold a reference.
51
 *
52
 * A #GBytes can come from many different origins that may have
53
 * different procedures for freeing the memory region.  Examples are
54
 * memory from g_malloc(), from memory slices, from a #GMappedFile or
55
 * memory from other allocators.
56
 *
57
 * #GBytes work well as keys in #GHashTable. Use g_bytes_equal() and
58
 * g_bytes_hash() as parameters to g_hash_table_new() or g_hash_table_new_full().
59
 * #GBytes can also be used as keys in a #GTree by passing the g_bytes_compare()
60
 * function to g_tree_new().
61
 *
62
 * The data pointed to by this bytes must not be modified. For a mutable
63
 * array of bytes see #GByteArray. Use g_bytes_unref_to_array() to create a
64
 * mutable array for a #GBytes sequence. To create an immutable #GBytes from
65
 * a mutable #GByteArray, use the g_byte_array_free_to_bytes() function.
66
 *
67
 * Since: 2.32
68
 **/
69
70
/* Keep in sync with glib/tests/bytes.c */
71
struct _GBytes
72
{
73
  gconstpointer data;  /* may be NULL iff (size == 0) */
74
  gsize size;  /* may be 0 */
75
  gatomicrefcount ref_count;
76
  GDestroyNotify free_func;
77
  gpointer user_data;
78
};
79
80
/**
81
 * g_bytes_new:
82
 * @data: (transfer none) (array length=size) (element-type guint8) (nullable):
83
 *        the data to be used for the bytes
84
 * @size: the size of @data
85
 *
86
 * Creates a new #GBytes from @data.
87
 *
88
 * @data is copied. If @size is 0, @data may be %NULL.
89
 *
90
 * Returns: (transfer full): a new #GBytes
91
 *
92
 * Since: 2.32
93
 */
94
GBytes *
95
g_bytes_new (gconstpointer data,
96
             gsize         size)
97
0
{
98
0
  g_return_val_if_fail (data != NULL || size == 0, NULL);
99
100
0
  return g_bytes_new_take (g_memdup2 (data, size), size);
101
0
}
102
103
/**
104
 * g_bytes_new_take:
105
 * @data: (transfer full) (array length=size) (element-type guint8) (nullable):
106
 *        the data to be used for the bytes
107
 * @size: the size of @data
108
 *
109
 * Creates a new #GBytes from @data.
110
 *
111
 * After this call, @data belongs to the bytes and may no longer be
112
 * modified by the caller.  g_free() will be called on @data when the
113
 * bytes is no longer in use. Because of this @data must have been created by
114
 * a call to g_malloc(), g_malloc0() or g_realloc() or by one of the many
115
 * functions that wrap these calls (such as g_new(), g_strdup(), etc).
116
 *
117
 * For creating #GBytes with memory from other allocators, see
118
 * g_bytes_new_with_free_func().
119
 *
120
 * @data may be %NULL if @size is 0.
121
 *
122
 * Returns: (transfer full): a new #GBytes
123
 *
124
 * Since: 2.32
125
 */
126
GBytes *
127
g_bytes_new_take (gpointer data,
128
                  gsize    size)
129
0
{
130
0
  return g_bytes_new_with_free_func (data, size, g_free, data);
131
0
}
132
133
134
/**
135
 * g_bytes_new_static: (skip)
136
 * @data: (transfer full) (array length=size) (element-type guint8) (nullable):
137
 *        the data to be used for the bytes
138
 * @size: the size of @data
139
 *
140
 * Creates a new #GBytes from static data.
141
 *
142
 * @data must be static (ie: never modified or freed). It may be %NULL if @size
143
 * is 0.
144
 *
145
 * Returns: (transfer full): a new #GBytes
146
 *
147
 * Since: 2.32
148
 */
149
GBytes *
150
g_bytes_new_static (gconstpointer data,
151
                    gsize         size)
152
0
{
153
0
  return g_bytes_new_with_free_func (data, size, NULL, NULL);
154
0
}
155
156
/**
157
 * g_bytes_new_with_free_func: (skip)
158
 * @data: (array length=size) (element-type guint8) (nullable):
159
 *        the data to be used for the bytes
160
 * @size: the size of @data
161
 * @free_func: the function to call to release the data
162
 * @user_data: data to pass to @free_func
163
 *
164
 * Creates a #GBytes from @data.
165
 *
166
 * When the last reference is dropped, @free_func will be called with the
167
 * @user_data argument.
168
 *
169
 * @data must not be modified after this call is made until @free_func has
170
 * been called to indicate that the bytes is no longer in use.
171
 *
172
 * @data may be %NULL if @size is 0.
173
 *
174
 * Returns: (transfer full): a new #GBytes
175
 *
176
 * Since: 2.32
177
 */
178
GBytes *
179
g_bytes_new_with_free_func (gconstpointer  data,
180
                            gsize          size,
181
                            GDestroyNotify free_func,
182
                            gpointer       user_data)
183
0
{
184
0
  GBytes *bytes;
185
186
0
  g_return_val_if_fail (data != NULL || size == 0, NULL);
187
188
0
  bytes = g_slice_new (GBytes);
189
0
  bytes->data = data;
190
0
  bytes->size = size;
191
0
  bytes->free_func = free_func;
192
0
  bytes->user_data = user_data;
193
0
  g_atomic_ref_count_init (&bytes->ref_count);
194
195
0
  return (GBytes *)bytes;
196
0
}
197
198
/**
199
 * g_bytes_new_from_bytes:
200
 * @bytes: a #GBytes
201
 * @offset: offset which subsection starts at
202
 * @length: length of subsection
203
 *
204
 * Creates a #GBytes which is a subsection of another #GBytes. The @offset +
205
 * @length may not be longer than the size of @bytes.
206
 *
207
 * A reference to @bytes will be held by the newly created #GBytes until
208
 * the byte data is no longer needed.
209
 *
210
 * Since 2.56, if @offset is 0 and @length matches the size of @bytes, then
211
 * @bytes will be returned with the reference count incremented by 1. If @bytes
212
 * is a slice of another #GBytes, then the resulting #GBytes will reference
213
 * the same #GBytes instead of @bytes. This allows consumers to simplify the
214
 * usage of #GBytes when asynchronously writing to streams.
215
 *
216
 * Returns: (transfer full): a new #GBytes
217
 *
218
 * Since: 2.32
219
 */
220
GBytes *
221
g_bytes_new_from_bytes (GBytes  *bytes,
222
                        gsize    offset,
223
                        gsize    length)
224
0
{
225
0
  gchar *base;
226
227
  /* Note that length may be 0. */
228
0
  g_return_val_if_fail (bytes != NULL, NULL);
229
0
  g_return_val_if_fail (offset <= bytes->size, NULL);
230
0
  g_return_val_if_fail (offset + length <= bytes->size, NULL);
231
232
  /* Avoid an extra GBytes if all bytes were requested */
233
0
  if (offset == 0 && length == bytes->size)
234
0
    return g_bytes_ref (bytes);
235
236
0
  base = (gchar *)bytes->data + offset;
237
238
  /* Avoid referencing intermediate GBytes. In practice, this should
239
   * only loop once.
240
   */
241
0
  while (bytes->free_func == (gpointer)g_bytes_unref)
242
0
    bytes = bytes->user_data;
243
244
0
  g_return_val_if_fail (bytes != NULL, NULL);
245
0
  g_return_val_if_fail (base >= (gchar *)bytes->data, NULL);
246
0
  g_return_val_if_fail (base <= (gchar *)bytes->data + bytes->size, NULL);
247
0
  g_return_val_if_fail (base + length <= (gchar *)bytes->data + bytes->size, NULL);
248
249
0
  return g_bytes_new_with_free_func (base, length,
250
0
                                     (GDestroyNotify)g_bytes_unref, g_bytes_ref (bytes));
251
0
}
252
253
/**
254
 * g_bytes_get_data:
255
 * @bytes: a #GBytes
256
 * @size: (out) (optional): location to return size of byte data
257
 *
258
 * Get the byte data in the #GBytes. This data should not be modified.
259
 *
260
 * This function will always return the same pointer for a given #GBytes.
261
 *
262
 * %NULL may be returned if @size is 0. This is not guaranteed, as the #GBytes
263
 * may represent an empty string with @data non-%NULL and @size as 0. %NULL will
264
 * not be returned if @size is non-zero.
265
 *
266
 * Returns: (transfer none) (array length=size) (element-type guint8) (nullable):
267
 *          a pointer to the byte data, or %NULL
268
 *
269
 * Since: 2.32
270
 */
271
gconstpointer
272
g_bytes_get_data (GBytes *bytes,
273
                  gsize *size)
274
0
{
275
0
  g_return_val_if_fail (bytes != NULL, NULL);
276
0
  if (size)
277
0
    *size = bytes->size;
278
0
  return bytes->data;
279
0
}
280
281
/**
282
 * g_bytes_get_size:
283
 * @bytes: a #GBytes
284
 *
285
 * Get the size of the byte data in the #GBytes.
286
 *
287
 * This function will always return the same value for a given #GBytes.
288
 *
289
 * Returns: the size
290
 *
291
 * Since: 2.32
292
 */
293
gsize
294
g_bytes_get_size (GBytes *bytes)
295
0
{
296
0
  g_return_val_if_fail (bytes != NULL, 0);
297
0
  return bytes->size;
298
0
}
299
300
301
/**
302
 * g_bytes_ref:
303
 * @bytes: a #GBytes
304
 *
305
 * Increase the reference count on @bytes.
306
 *
307
 * Returns: the #GBytes
308
 *
309
 * Since: 2.32
310
 */
311
GBytes *
312
g_bytes_ref (GBytes *bytes)
313
0
{
314
0
  g_return_val_if_fail (bytes != NULL, NULL);
315
316
0
  g_atomic_ref_count_inc (&bytes->ref_count);
317
318
0
  return bytes;
319
0
}
320
321
/**
322
 * g_bytes_unref:
323
 * @bytes: (nullable): a #GBytes
324
 *
325
 * Releases a reference on @bytes.  This may result in the bytes being
326
 * freed. If @bytes is %NULL, it will return immediately.
327
 *
328
 * Since: 2.32
329
 */
330
void
331
g_bytes_unref (GBytes *bytes)
332
0
{
333
0
  if (bytes == NULL)
334
0
    return;
335
336
0
  if (g_atomic_ref_count_dec (&bytes->ref_count))
337
0
    {
338
0
      if (bytes->free_func != NULL)
339
0
        bytes->free_func (bytes->user_data);
340
0
      g_slice_free (GBytes, bytes);
341
0
    }
342
0
}
343
344
/**
345
 * g_bytes_equal:
346
 * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
347
 * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
348
 *
349
 * Compares the two #GBytes values being pointed to and returns
350
 * %TRUE if they are equal.
351
 *
352
 * This function can be passed to g_hash_table_new() as the @key_equal_func
353
 * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
354
 *
355
 * Returns: %TRUE if the two keys match.
356
 *
357
 * Since: 2.32
358
 */
359
gboolean
360
g_bytes_equal (gconstpointer bytes1,
361
               gconstpointer bytes2)
362
0
{
363
0
  const GBytes *b1 = bytes1;
364
0
  const GBytes *b2 = bytes2;
365
366
0
  g_return_val_if_fail (bytes1 != NULL, FALSE);
367
0
  g_return_val_if_fail (bytes2 != NULL, FALSE);
368
369
0
  return b1->size == b2->size &&
370
0
         (b1->size == 0 || memcmp (b1->data, b2->data, b1->size) == 0);
371
0
}
372
373
/**
374
 * g_bytes_hash:
375
 * @bytes: (type GLib.Bytes): a pointer to a #GBytes key
376
 *
377
 * Creates an integer hash code for the byte data in the #GBytes.
378
 *
379
 * This function can be passed to g_hash_table_new() as the @key_hash_func
380
 * parameter, when using non-%NULL #GBytes pointers as keys in a #GHashTable.
381
 *
382
 * Returns: a hash value corresponding to the key.
383
 *
384
 * Since: 2.32
385
 */
386
guint
387
g_bytes_hash (gconstpointer bytes)
388
0
{
389
0
  const GBytes *a = bytes;
390
0
  const signed char *p, *e;
391
0
  guint32 h = 5381;
392
393
0
  g_return_val_if_fail (bytes != NULL, 0);
394
395
0
  for (p = (signed char *)a->data, e = (signed char *)a->data + a->size; p != e; p++)
396
0
    h = (h << 5) + h + *p;
397
398
0
  return h;
399
0
}
400
401
/**
402
 * g_bytes_compare:
403
 * @bytes1: (type GLib.Bytes): a pointer to a #GBytes
404
 * @bytes2: (type GLib.Bytes): a pointer to a #GBytes to compare with @bytes1
405
 *
406
 * Compares the two #GBytes values.
407
 *
408
 * This function can be used to sort GBytes instances in lexicographical order.
409
 *
410
 * If @bytes1 and @bytes2 have different length but the shorter one is a
411
 * prefix of the longer one then the shorter one is considered to be less than
412
 * the longer one. Otherwise the first byte where both differ is used for
413
 * comparison. If @bytes1 has a smaller value at that position it is
414
 * considered less, otherwise greater than @bytes2.
415
 *
416
 * Returns: a negative value if @bytes1 is less than @bytes2, a positive value
417
 *          if @bytes1 is greater than @bytes2, and zero if @bytes1 is equal to
418
 *          @bytes2
419
 *
420
 *
421
 * Since: 2.32
422
 */
423
gint
424
g_bytes_compare (gconstpointer bytes1,
425
                 gconstpointer bytes2)
426
0
{
427
0
  const GBytes *b1 = bytes1;
428
0
  const GBytes *b2 = bytes2;
429
0
  gint ret;
430
431
0
  g_return_val_if_fail (bytes1 != NULL, 0);
432
0
  g_return_val_if_fail (bytes2 != NULL, 0);
433
434
0
  ret = memcmp (b1->data, b2->data, MIN (b1->size, b2->size));
435
0
  if (ret == 0 && b1->size != b2->size)
436
0
      ret = b1->size < b2->size ? -1 : 1;
437
0
  return ret;
438
0
}
439
440
static gpointer
441
try_steal_and_unref (GBytes         *bytes,
442
                     GDestroyNotify  free_func,
443
                     gsize          *size)
444
0
{
445
0
  gpointer result;
446
447
0
  if (bytes->free_func != free_func || bytes->data == NULL ||
448
0
      bytes->user_data != bytes->data)
449
0
    return NULL;
450
451
  /* Are we the only reference? */
452
0
  if (g_atomic_ref_count_compare (&bytes->ref_count, 1))
453
0
    {
454
0
      *size = bytes->size;
455
0
      result = (gpointer)bytes->data;
456
0
      g_slice_free (GBytes, bytes);
457
0
      return result;
458
0
    }
459
460
0
  return NULL;
461
0
}
462
463
464
/**
465
 * g_bytes_unref_to_data:
466
 * @bytes: (transfer full): a #GBytes
467
 * @size: (out): location to place the length of the returned data
468
 *
469
 * Unreferences the bytes, and returns a pointer the same byte data
470
 * contents.
471
 *
472
 * As an optimization, the byte data is returned without copying if this was
473
 * the last reference to bytes and bytes was created with g_bytes_new(),
474
 * g_bytes_new_take() or g_byte_array_free_to_bytes(). In all other cases the
475
 * data is copied.
476
 *
477
 * Returns: (transfer full) (array length=size) (element-type guint8)
478
 *          (not nullable): a pointer to the same byte data, which should be
479
 *          freed with g_free()
480
 *
481
 * Since: 2.32
482
 */
483
gpointer
484
g_bytes_unref_to_data (GBytes *bytes,
485
                       gsize  *size)
486
0
{
487
0
  gpointer result;
488
489
0
  g_return_val_if_fail (bytes != NULL, NULL);
490
0
  g_return_val_if_fail (size != NULL, NULL);
491
492
  /*
493
   * Optimal path: if this is was the last reference, then we can return
494
   * the data from this GBytes without copying.
495
   */
496
497
0
  result = try_steal_and_unref (bytes, g_free, size);
498
0
  if (result == NULL)
499
0
    {
500
      /*
501
       * Copy: Non g_malloc (or compatible) allocator, or static memory,
502
       * so we have to copy, and then unref.
503
       */
504
0
      result = g_memdup2 (bytes->data, bytes->size);
505
0
      *size = bytes->size;
506
0
      g_bytes_unref (bytes);
507
0
    }
508
509
0
  return result;
510
0
}
511
512
/**
513
 * g_bytes_unref_to_array:
514
 * @bytes: (transfer full): a #GBytes
515
 *
516
 * Unreferences the bytes, and returns a new mutable #GByteArray containing
517
 * the same byte data.
518
 *
519
 * As an optimization, the byte data is transferred to the array without copying
520
 * if this was the last reference to bytes and bytes was created with
521
 * g_bytes_new(), g_bytes_new_take() or g_byte_array_free_to_bytes(). In all
522
 * other cases the data is copied.
523
 *
524
 * Do not use it if @bytes contains more than %G_MAXUINT
525
 * bytes. #GByteArray stores the length of its data in #guint, which
526
 * may be shorter than #gsize, that @bytes is using.
527
 *
528
 * Returns: (transfer full): a new mutable #GByteArray containing the same byte data
529
 *
530
 * Since: 2.32
531
 */
532
GByteArray *
533
g_bytes_unref_to_array (GBytes *bytes)
534
0
{
535
0
  gpointer data;
536
0
  gsize size;
537
538
0
  g_return_val_if_fail (bytes != NULL, NULL);
539
540
0
  data = g_bytes_unref_to_data (bytes, &size);
541
0
  return g_byte_array_new_take (data, size);
542
0
}
543
544
/**
545
 * g_bytes_get_region:
546
 * @bytes: a #GBytes
547
 * @element_size: a non-zero element size
548
 * @offset: an offset to the start of the region within the @bytes
549
 * @n_elements: the number of elements in the region
550
 *
551
 * Gets a pointer to a region in @bytes.
552
 *
553
 * The region starts at @offset many bytes from the start of the data
554
 * and contains @n_elements many elements of @element_size size.
555
 *
556
 * @n_elements may be zero, but @element_size must always be non-zero.
557
 * Ideally, @element_size is a static constant (eg: sizeof a struct).
558
 *
559
 * This function does careful bounds checking (including checking for
560
 * arithmetic overflows) and returns a non-%NULL pointer if the
561
 * specified region lies entirely within the @bytes. If the region is
562
 * in some way out of range, or if an overflow has occurred, then %NULL
563
 * is returned.
564
 *
565
 * Note: it is possible to have a valid zero-size region. In this case,
566
 * the returned pointer will be equal to the base pointer of the data of
567
 * @bytes, plus @offset.  This will be non-%NULL except for the case
568
 * where @bytes itself was a zero-sized region.  Since it is unlikely
569
 * that you will be using this function to check for a zero-sized region
570
 * in a zero-sized @bytes, %NULL effectively always means "error".
571
 *
572
 * Returns: (nullable): the requested region, or %NULL in case of an error
573
 *
574
 * Since: 2.70
575
 */
576
gconstpointer
577
g_bytes_get_region (GBytes *bytes,
578
                    gsize   element_size,
579
                    gsize   offset,
580
                    gsize   n_elements)
581
0
{
582
0
  gsize total_size;
583
0
  gsize end_offset;
584
585
0
  g_return_val_if_fail (element_size > 0, NULL);
586
587
  /* No other assertion checks here.  If something is wrong then we will
588
   * simply crash (via NULL dereference or divide-by-zero).
589
   */
590
591
0
  if (!g_size_checked_mul (&total_size, element_size, n_elements))
592
0
    return NULL;
593
594
0
  if (!g_size_checked_add (&end_offset, offset, total_size))
595
0
    return NULL;
596
597
  /* We now have:
598
   *
599
   *   0 <= offset <= end_offset
600
   *
601
   * So we need only check that end_offset is within the range of the
602
   * size of @bytes and we're good to go.
603
   */
604
605
0
  if (end_offset > bytes->size)
606
0
    return NULL;
607
608
  /* We now have:
609
   *
610
   *   0 <= offset <= end_offset <= bytes->size
611
   */
612
613
0
  return ((guchar *) bytes->data) + offset;
614
0
}