libpulse_sys/xmalloc.rs
1// Copyright 2017 Lyndon Brown
2//
3// This file is part of the PulseAudio Rust language linking library.
4//
5// Licensed under the MIT license or the Apache license (version 2.0), at your option. You may not
6// copy, modify, or distribute this file except in compliance with said license. You can find copies
7// of these licenses either in the LICENSE-MIT and LICENSE-APACHE files, or alternatively at
8// <http://opensource.org/licenses/MIT> and <http://www.apache.org/licenses/LICENSE-2.0>
9// respectively.
10//
11// Portions of documentation are copied from the LGPL 2.1+ licensed PulseAudio C headers on a
12// fair-use basis, as discussed in the overall project readme (available in the git repository).
13
14//! Memory allocation functions.
15
16use std::os::raw::{c_char, c_void};
17
18/// Allocates `n` new structures of the specified type.
19#[inline(always)]
20pub unsafe fn pa_xnew(n: usize, k: usize) -> *mut c_void {
21 assert!(n < (std::i32::MAX as usize / k));
22 pa_xmalloc(n * k)
23}
24
25/// Same as [`pa_xnew()`] but sets the memory to zero.
26#[inline(always)]
27pub unsafe fn pa_xnew0(n: usize, k: usize) -> *mut c_void {
28 assert!(n < (std::i32::MAX as usize / k));
29 pa_xmalloc0(n * k)
30}
31
32/// Same as [`pa_xnew()`] but duplicates the specified data.
33#[inline(always)]
34pub unsafe fn pa_xnewdup(p: *const c_void, n: usize, k: usize) -> *mut c_void {
35 assert!(n < (std::i32::MAX as usize / k));
36 pa_xmemdup(p, n * k)
37}
38
39/// Reallocates `n` new structures of the specified type.
40#[inline(always)]
41pub unsafe fn pa_xrenew(p: *mut c_void, n: usize, k: usize) -> *mut c_void {
42 assert!(n < (std::i32::MAX as usize / k));
43 pa_xrealloc(p, n * k)
44}
45
46#[link(name = "pulse")]
47extern "C" {
48 /// Allocates the specified number of bytes, just like `malloc()` does.
49 /// However, in case of OOM, terminate.
50 pub fn pa_xmalloc(l: usize) -> *mut c_void;
51
52 /// Same as [`pa_xmalloc()`] , but initializes allocated memory to 0.
53 pub fn pa_xmalloc0(l: usize) -> *mut c_void;
54
55 /// The combination of [`pa_xmalloc()`] and `realloc()`.
56 pub fn pa_xrealloc(ptr: *mut c_void, size: usize) -> *mut c_void;
57
58 /// Frees allocated memory.
59 pub fn pa_xfree(p: *mut c_void);
60
61 /// Duplicates the specified string, allocating memory with [`pa_xmalloc()`].
62 pub fn pa_xstrdup(s: *const c_char) -> *mut c_char;
63
64 /// Duplicates the specified string, but truncate after `l` characters.
65 pub fn pa_xstrndup(s: *const c_char, l: usize) -> *mut c_char;
66
67 /// Duplicates the specified memory block.
68 pub fn pa_xmemdup(p: *const c_void, l: usize) -> *mut c_void;
69}