rp2040-i2s
All Classes Files Functions Variables Typedefs Modules Pages
buffer.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #ifndef _PICO_UTIL_BUFFER_H
8 #define _PICO_UTIL_BUFFER_H
9 
10 #include "pico/types.h"
11 
18 #ifdef PICO_BUFFER_USB_ALLOC_HACK
19 #include "hardware/address_mapped.h"
20 #endif
21 
22 #ifdef __cplusplus
23 extern "C" {
24 #endif
25 
26 #ifdef DEBUG_MALLOC
27 #include <stdio.h>
28 #endif
29 
30 #include <stdlib.h>
31 
40 typedef struct mem_buffer {
41  size_t size;
42  uint8_t *bytes;
43  uint8_t flags;
44 } mem_buffer_t;
45 
46 #ifdef PICO_BUFFER_USB_ALLOC_HACK
47 #if !defined(USB_DPRAM_MAX) || (USB_DPRAM_MAX > 0)
48 #include "hardware/structs/usb.h"
49 #else
50 #define USB_DPRAM_SIZE 4096
51 #endif
52 #endif
53 
54 inline static bool pico_buffer_alloc_in_place(mem_buffer_t *buffer, size_t size) {
55 #ifdef PICO_BUFFER_USB_ALLOC_HACK
56  extern uint8_t *usb_ram_alloc_ptr;
57  if ((usb_ram_alloc_ptr + size) <= (uint8_t *)USBCTRL_DPRAM_BASE + USB_DPRAM_SIZE) {
58  buffer->bytes = usb_ram_alloc_ptr;
59  buffer->size = size;
60 #ifdef DEBUG_MALLOC
61  printf("balloc %d %p->%p\n", size, buffer->bytes, ((uint8_t *)buffer->bytes) + size);
62 #endif
63  usb_ram_alloc_ptr += size;
64  return true;
65  }
66 #endif // inline for now
67  buffer->bytes = (uint8_t *) calloc(1, size);
68  if (buffer->bytes) {
69  buffer->size = size;
70  return true;
71  }
72  buffer->size = 0;
73  return false;
74 }
75 
76 inline static mem_buffer_t *pico_buffer_wrap(uint8_t *bytes, size_t size) {
77  mem_buffer_t *buffer = (mem_buffer_t *) malloc(sizeof(mem_buffer_t));
78  if (buffer) {
79  buffer->bytes = bytes;
80  buffer->size = size;
81  }
82  return buffer;
83 }
84 
85 inline static mem_buffer_t *pico_buffer_alloc(size_t size) {
86  mem_buffer_t *b = (mem_buffer_t *) malloc(sizeof(mem_buffer_t));
87  if (b) {
88  if (!pico_buffer_alloc_in_place(b, size)) {
89  free(b);
90  b = NULL;
91  }
92  }
93  return b;
94 }
95 
96 #ifdef __cplusplus
97 }
98 #endif
99 #endif
Wrapper structure around a memory buffer.
Definition: buffer.h:40