Move atomic method definitions to a separate common source
[openal-soft.git] / Alc / helpers.c
blob77a660d15400497351295092c1bba9ea51062445
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2011 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #ifdef _WIN32
22 #ifdef __MINGW32__
23 #define _WIN32_IE 0x501
24 #else
25 #define _WIN32_IE 0x400
26 #endif
27 #endif
29 #include "config.h"
31 #include <stdlib.h>
32 #include <time.h>
33 #include <errno.h>
34 #include <stdarg.h>
35 #ifdef HAVE_MALLOC_H
36 #include <malloc.h>
37 #endif
39 #ifndef AL_NO_UID_DEFS
40 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
41 #define INITGUID
42 #include <windows.h>
43 #ifdef HAVE_GUIDDEF_H
44 #include <guiddef.h>
45 #else
46 #include <initguid.h>
47 #endif
49 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
50 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
52 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
54 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
55 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
56 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
57 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
59 #ifdef HAVE_MMDEVAPI
60 #include <devpropdef.h>
61 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
62 #endif
63 #endif
64 #endif /* AL_NO_UID_DEFS */
66 #ifdef HAVE_DLFCN_H
67 #include <dlfcn.h>
68 #endif
69 #ifdef HAVE_CPUID_H
70 #include <cpuid.h>
71 #endif
72 #ifdef HAVE_SYS_SYSCONF_H
73 #include <sys/sysconf.h>
74 #endif
75 #ifdef HAVE_FLOAT_H
76 #include <float.h>
77 #endif
78 #ifdef HAVE_IEEEFP_H
79 #include <ieeefp.h>
80 #endif
82 #ifdef _WIN32_IE
83 #include <shlobj.h>
84 #endif
86 #include "alMain.h"
87 #include "alu.h"
88 #include "atomic.h"
89 #include "uintmap.h"
90 #include "vector.h"
91 #include "alstring.h"
92 #include "compat.h"
93 #include "threads.h"
96 extern inline void LockUIntMapRead(UIntMap *map);
97 extern inline void UnlockUIntMapRead(UIntMap *map);
98 extern inline void LockUIntMapWrite(UIntMap *map);
99 extern inline void UnlockUIntMapWrite(UIntMap *map);
101 extern inline ALuint NextPowerOf2(ALuint value);
102 extern inline ALint fastf2i(ALfloat f);
103 extern inline ALuint fastf2u(ALfloat f);
106 ALuint CPUCapFlags = 0;
109 void FillCPUCaps(ALuint capfilter)
111 ALuint caps = 0;
113 /* FIXME: We really should get this for all available CPUs in case different
114 * CPUs have different caps (is that possible on one machine?). */
115 #if defined(HAVE_CPUID_H) && (defined(__i386__) || defined(__x86_64__) || \
116 defined(_M_IX86) || defined(_M_X64))
117 union {
118 unsigned int regs[4];
119 char str[sizeof(unsigned int[4])];
120 } cpuinf[3];
122 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
123 ERR("Failed to get CPUID\n");
124 else
126 unsigned int maxfunc = cpuinf[0].regs[0];
127 unsigned int maxextfunc = 0;
129 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
130 maxextfunc = cpuinf[0].regs[0];
131 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
133 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
134 if(maxextfunc >= 0x80000004 &&
135 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
136 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
137 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
138 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
140 if(maxfunc >= 1 &&
141 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
143 if((cpuinf[0].regs[3]&(1<<25)))
145 caps |= CPU_CAP_SSE;
146 if((cpuinf[0].regs[3]&(1<<26)))
147 caps |= CPU_CAP_SSE2;
151 #elif defined(HAVE_WINDOWS_H)
152 HMODULE k32 = GetModuleHandleA("kernel32.dll");
153 BOOL (WINAPI*IsProcessorFeaturePresent)(DWORD ProcessorFeature);
154 IsProcessorFeaturePresent = (BOOL(WINAPI*)(DWORD))GetProcAddress(k32, "IsProcessorFeaturePresent");
155 if(!IsProcessorFeaturePresent)
156 ERR("IsProcessorFeaturePresent not available; CPU caps not detected\n");
157 else
159 if(IsProcessorFeaturePresent(PF_XMMI_INSTRUCTIONS_AVAILABLE))
161 caps |= CPU_CAP_SSE;
162 if(IsProcessorFeaturePresent(PF_XMMI64_INSTRUCTIONS_AVAILABLE))
163 caps |= CPU_CAP_SSE2;
166 #endif
167 #ifdef HAVE_NEON
168 /* Assume Neon support if compiled with it */
169 caps |= CPU_CAP_NEON;
170 #endif
172 TRACE("Got caps:%s%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
173 ((caps&CPU_CAP_SSE2)?((capfilter&CPU_CAP_SSE2)?" SSE2":" (SSE2)"):""),
174 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
175 ((!caps)?" -none-":""));
176 CPUCapFlags = caps & capfilter;
180 void *al_malloc(size_t alignment, size_t size)
182 #if defined(HAVE_ALIGNED_ALLOC)
183 size = (size+(alignment-1))&~(alignment-1);
184 return aligned_alloc(alignment, size);
185 #elif defined(HAVE_POSIX_MEMALIGN)
186 void *ret;
187 if(posix_memalign(&ret, alignment, size) == 0)
188 return ret;
189 return NULL;
190 #elif defined(HAVE__ALIGNED_MALLOC)
191 return _aligned_malloc(size, alignment);
192 #else
193 char *ret = malloc(size+alignment);
194 if(ret != NULL)
196 *(ret++) = 0x00;
197 while(((ALintptrEXT)ret&(alignment-1)) != 0)
198 *(ret++) = 0x55;
200 return ret;
201 #endif
204 void *al_calloc(size_t alignment, size_t size)
206 void *ret = al_malloc(alignment, size);
207 if(ret) memset(ret, 0, size);
208 return ret;
211 void al_free(void *ptr)
213 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
214 free(ptr);
215 #elif defined(HAVE__ALIGNED_MALLOC)
216 _aligned_free(ptr);
217 #else
218 if(ptr != NULL)
220 char *finder = ptr;
221 do {
222 --finder;
223 } while(*finder == 0x55);
224 free(finder);
226 #endif
230 #if (defined(HAVE___CONTROL87_2) || defined(HAVE__CONTROLFP)) && (defined(__x86_64__) || defined(_M_X64))
231 /* Win64 doesn't allow us to set the precision control. */
232 #undef _MCW_PC
233 #define _MCW_PC 0
234 #endif
236 void SetMixerFPUMode(FPUCtl *ctl)
238 #ifdef HAVE_FENV_H
239 fegetenv(STATIC_CAST(fenv_t, ctl));
240 #if defined(__GNUC__) && defined(HAVE_SSE)
241 if((CPUCapFlags&CPU_CAP_SSE))
242 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
243 #endif
245 #ifdef FE_TOWARDZERO
246 fesetround(FE_TOWARDZERO);
247 #endif
248 #if defined(__GNUC__) && defined(HAVE_SSE)
249 if((CPUCapFlags&CPU_CAP_SSE))
251 int sseState = ctl->sse_state;
252 sseState |= 0x6000; /* set round-to-zero */
253 sseState |= 0x8000; /* set flush-to-zero */
254 if((CPUCapFlags&CPU_CAP_SSE2))
255 sseState |= 0x0040; /* set denormals-are-zero */
256 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
258 #endif
260 #elif defined(HAVE___CONTROL87_2)
262 int mode;
263 __control87_2(0, 0, &ctl->state, NULL);
264 __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
265 #ifdef HAVE_SSE
266 if((CPUCapFlags&CPU_CAP_SSE))
268 __control87_2(0, 0, NULL, &ctl->sse_state);
269 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
271 #endif
273 #elif defined(HAVE__CONTROLFP)
275 ctl->state = _controlfp(0, 0);
276 (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
277 #endif
280 void RestoreFPUMode(const FPUCtl *ctl)
282 #ifdef HAVE_FENV_H
283 fesetenv(STATIC_CAST(fenv_t, ctl));
284 #if defined(__GNUC__) && defined(HAVE_SSE)
285 if((CPUCapFlags&CPU_CAP_SSE))
286 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
287 #endif
289 #elif defined(HAVE___CONTROL87_2)
291 int mode;
292 __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
293 #ifdef HAVE_SSE
294 if((CPUCapFlags&CPU_CAP_SSE))
295 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
296 #endif
298 #elif defined(HAVE__CONTROLFP)
300 _controlfp(ctl->state, _MCW_RC|_MCW_PC);
301 #endif
305 #ifdef _WIN32
307 static WCHAR *FromUTF8(const char *str)
309 WCHAR *out = NULL;
310 int len;
312 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
314 out = calloc(sizeof(WCHAR), len);
315 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
317 return out;
321 void *LoadLib(const char *name)
323 HANDLE hdl = NULL;
324 WCHAR *wname;
326 wname = FromUTF8(name);
327 if(!wname)
328 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
329 else
331 hdl = LoadLibraryW(wname);
332 free(wname);
334 return hdl;
336 void CloseLib(void *handle)
337 { FreeLibrary((HANDLE)handle); }
338 void *GetSymbol(void *handle, const char *name)
340 void *ret;
342 ret = (void*)GetProcAddress((HANDLE)handle, name);
343 if(ret == NULL)
344 ERR("Failed to load %s\n", name);
345 return ret;
348 WCHAR *strdupW(const WCHAR *str)
350 const WCHAR *n;
351 WCHAR *ret;
352 size_t len;
354 n = str;
355 while(*n) n++;
356 len = n - str;
358 ret = calloc(sizeof(WCHAR), len+1);
359 if(ret != NULL)
360 memcpy(ret, str, sizeof(WCHAR)*len);
361 return ret;
364 FILE *al_fopen(const char *fname, const char *mode)
366 WCHAR *wname=NULL, *wmode=NULL;
367 FILE *file = NULL;
369 wname = FromUTF8(fname);
370 wmode = FromUTF8(mode);
371 if(!wname)
372 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
373 else if(!wmode)
374 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
375 else
376 file = _wfopen(wname, wmode);
378 free(wname);
379 free(wmode);
381 return file;
384 #else
386 #ifdef HAVE_DLFCN_H
388 void *LoadLib(const char *name)
390 const char *err;
391 void *handle;
393 dlerror();
394 handle = dlopen(name, RTLD_NOW);
395 if((err=dlerror()) != NULL)
396 handle = NULL;
397 return handle;
399 void CloseLib(void *handle)
400 { dlclose(handle); }
401 void *GetSymbol(void *handle, const char *name)
403 const char *err;
404 void *sym;
406 dlerror();
407 sym = dlsym(handle, name);
408 if((err=dlerror()) != NULL)
410 WARN("Failed to load %s: %s\n", name, err);
411 sym = NULL;
413 return sym;
416 #endif
417 #endif
420 void al_print(const char *type, const char *func, const char *fmt, ...)
422 va_list ap;
424 va_start(ap, fmt);
425 fprintf(LogFile, "AL lib: %s %s: ", type, func);
426 vfprintf(LogFile, fmt, ap);
427 va_end(ap);
429 fflush(LogFile);
432 #ifdef _WIN32
433 static inline int is_slash(int c)
434 { return (c == '\\' || c == '/'); }
436 FILE *OpenDataFile(const char *fname, const char *subdir)
438 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
439 WCHAR *wname=NULL, *wsubdir=NULL;
440 int i;
442 /* If the path is absolute, open it directly. */
443 if(fname[0] != '\0' && fname[1] == ':' && is_slash(fname[2]))
445 FILE *f;
446 if((f=al_fopen(fname, "rb")) != NULL)
448 TRACE("Opened %s\n", fname);
449 return f;
451 WARN("Could not open %s\n", fname);
452 return NULL;
455 wname = FromUTF8(fname);
456 wsubdir = FromUTF8(subdir);
457 if(!wname)
458 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
459 else if(!wsubdir)
460 ERR("Failed to convert UTF-8 subdir: \"%s\"\n", subdir);
461 else for(i = 0;i < 2;i++)
463 WCHAR buffer[PATH_MAX];
464 size_t len;
465 FILE *f;
467 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) == FALSE)
468 continue;
470 len = lstrlenW(buffer);
471 if(len > 0 && is_slash(buffer[len-1]))
472 buffer[--len] = '\0';
473 _snwprintf(buffer+len, PATH_MAX-len, L"/%ls/%ls", wsubdir, wname);
474 len = lstrlenW(buffer);
475 while(len > 0)
477 --len;
478 if(buffer[len] == '/')
479 buffer[len] = '\\';
482 if((f=_wfopen(buffer, L"rb")) != NULL)
484 TRACE("Opened %ls\n", buffer);
485 return f;
487 WARN("Could not open %ls\n", buffer);
489 free(wname);
490 free(wsubdir);
492 return NULL;
494 #else
495 FILE *OpenDataFile(const char *fname, const char *subdir)
497 char buffer[PATH_MAX] = "";
498 const char *str, *next;
499 FILE *f;
501 if(fname[0] == '/')
503 if((f=al_fopen(fname, "rb")) != NULL)
505 TRACE("Opened %s\n", fname);
506 return f;
508 WARN("Could not open %s\n", fname);
509 return NULL;
512 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
513 snprintf(buffer, sizeof(buffer), "%s/%s/%s", str, subdir, fname);
514 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
515 snprintf(buffer, sizeof(buffer), "%s/.local/share/%s/%s", str, subdir, fname);
516 if(buffer[0])
518 if((f=al_fopen(buffer, "rb")) != NULL)
520 TRACE("Opened %s\n", buffer);
521 return f;
523 WARN("Could not open %s\n", buffer);
526 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
527 str = "/usr/local/share/:/usr/share/";
529 next = str;
530 while((str=next) != NULL && str[0] != '\0')
532 size_t len;
533 next = strchr(str, ':');
535 if(!next)
536 len = strlen(str);
537 else
539 len = next - str;
540 next++;
543 if(len > sizeof(buffer)-1)
544 len = sizeof(buffer)-1;
545 strncpy(buffer, str, len);
546 buffer[len] = '\0';
547 snprintf(buffer+len, sizeof(buffer)-len, "/%s/%s", subdir, fname);
549 if((f=al_fopen(buffer, "rb")) != NULL)
551 TRACE("Opened %s\n", buffer);
552 return f;
554 WARN("Could not open %s\n", buffer);
557 return NULL;
559 #endif
562 void SetRTPriority(void)
564 ALboolean failed = AL_FALSE;
566 #ifdef _WIN32
567 if(RTPrioLevel > 0)
568 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
569 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
570 if(RTPrioLevel > 0)
572 struct sched_param param;
573 /* Use the minimum real-time priority possible for now (on Linux this
574 * should be 1 for SCHED_RR) */
575 param.sched_priority = sched_get_priority_min(SCHED_RR);
576 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
578 #else
579 /* Real-time priority not available */
580 failed = (RTPrioLevel>0);
581 #endif
582 if(failed)
583 ERR("Failed to set priority level for thread\n");
587 static void Lock(volatile ALenum *l)
589 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
590 althrd_yield();
593 static void Unlock(volatile ALenum *l)
595 ExchangeInt(l, AL_FALSE);
598 void RWLockInit(RWLock *lock)
600 lock->read_count = 0;
601 lock->write_count = 0;
602 lock->read_lock = AL_FALSE;
603 lock->read_entry_lock = AL_FALSE;
604 lock->write_lock = AL_FALSE;
607 void ReadLock(RWLock *lock)
609 Lock(&lock->read_entry_lock);
610 Lock(&lock->read_lock);
611 if(IncrementRef(&lock->read_count) == 1)
612 Lock(&lock->write_lock);
613 Unlock(&lock->read_lock);
614 Unlock(&lock->read_entry_lock);
617 void ReadUnlock(RWLock *lock)
619 if(DecrementRef(&lock->read_count) == 0)
620 Unlock(&lock->write_lock);
623 void WriteLock(RWLock *lock)
625 if(IncrementRef(&lock->write_count) == 1)
626 Lock(&lock->read_lock);
627 Lock(&lock->write_lock);
630 void WriteUnlock(RWLock *lock)
632 Unlock(&lock->write_lock);
633 if(DecrementRef(&lock->write_count) == 0)
634 Unlock(&lock->read_lock);
638 ALboolean vector_reserve(void *ptr, size_t base_size, size_t obj_count, size_t obj_size, ALboolean exact)
640 vector_ *vecptr = ptr;
641 if((size_t)(*vecptr ? (*vecptr)->Capacity : 0) < obj_count)
643 ALsizei old_size = (*vecptr ? (*vecptr)->Size : 0);
644 void *temp;
646 /* Limit vector sizes to the greatest power-of-two value that an
647 * ALsizei can hold. */
648 if(obj_count > (INT_MAX>>1)+1)
649 return AL_FALSE;
651 /* Use the next power-of-2 size if we don't need to allocate the exact
652 * amount. This is preferred when regularly increasing the vector since
653 * it means fewer reallocations. Though it means it also wastes some
654 * memory. */
655 if(exact == AL_FALSE)
656 obj_count = NextPowerOf2((ALuint)obj_count);
658 /* Need to be explicit with the caller type's base size, because it
659 * could have extra padding before the start of the array (that is,
660 * sizeof(*vector_) may not equal base_size). */
661 temp = realloc(*vecptr, base_size + obj_size*obj_count);
662 if(temp == NULL) return AL_FALSE;
664 *vecptr = temp;
665 (*vecptr)->Capacity = (ALsizei)obj_count;
666 (*vecptr)->Size = old_size;
668 return AL_TRUE;
671 ALboolean vector_resize(void *ptr, size_t base_size, size_t obj_count, size_t obj_size)
673 vector_ *vecptr = ptr;
674 if(*vecptr || obj_count > 0)
676 if(!vector_reserve(vecptr, base_size, obj_count, obj_size, AL_TRUE))
677 return AL_FALSE;
678 (*vecptr)->Size = (ALsizei)obj_count;
680 return AL_TRUE;
683 ALboolean vector_insert(void *ptr, size_t base_size, size_t obj_size, void *ins_pos, const void *datstart, const void *datend)
685 vector_ *vecptr = ptr;
686 if(datstart != datend)
688 ptrdiff_t ins_elem = ((char*)ins_pos - ((char*)(*vecptr) + base_size)) / obj_size;
689 ptrdiff_t numins = ((const char*)datend - (const char*)datstart) / obj_size;
690 if(!vector_reserve(vecptr, base_size, VECTOR_SIZE(*vecptr)+numins, obj_size, AL_TRUE))
691 return AL_FALSE;
692 /* NOTE: ins_pos may have been invalidated if *vecptr moved. Use ins_elem instead. */
693 if(ins_elem < (*vecptr)->Size)
695 memmove((char*)(*vecptr) + base_size + ((ins_elem+numins)*obj_size),
696 (char*)(*vecptr) + base_size + ((ins_elem )*obj_size),
697 ((*vecptr)->Size-ins_elem)*obj_size);
699 memcpy((char*)(*vecptr) + base_size + (ins_elem*obj_size),
700 datstart, numins*obj_size);
701 (*vecptr)->Size += (ALsizei)numins;
703 return AL_TRUE;
707 extern inline ALsizei al_string_length(const_al_string str);
708 extern inline ALboolean al_string_empty(const_al_string str);
709 extern inline const al_string_char_type *al_string_get_cstr(const_al_string str);
711 void al_string_clear(al_string *str)
713 /* Reserve one more character than the total size of the string. This is to
714 * ensure we have space to add a null terminator in the string data so it
715 * can be used as a C-style string. */
716 VECTOR_RESERVE(*str, 1);
717 VECTOR_RESIZE(*str, 0);
718 *VECTOR_ITER_END(*str) = 0;
721 static inline int al_string_compare(const al_string_char_type *str1, ALsizei str1len,
722 const al_string_char_type *str2, ALsizei str2len)
724 ALsizei complen = mini(str1len, str2len);
725 int ret = memcmp(str1, str2, complen);
726 if(ret == 0)
728 if(str1len > str2len) return 1;
729 if(str1len < str2len) return -1;
731 return ret;
733 int al_string_cmp(const_al_string str1, const_al_string str2)
735 return al_string_compare(&VECTOR_FRONT(str1), al_string_length(str1),
736 &VECTOR_FRONT(str2), al_string_length(str2));
738 int al_string_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
740 return al_string_compare(&VECTOR_FRONT(str1), al_string_length(str1),
741 str2, (ALsizei)strlen(str2));
744 void al_string_copy(al_string *str, const_al_string from)
746 ALsizei len = VECTOR_SIZE(from);
747 VECTOR_RESERVE(*str, len+1);
748 VECTOR_RESIZE(*str, 0);
749 VECTOR_INSERT(*str, VECTOR_ITER_END(*str), VECTOR_ITER_BEGIN(from), VECTOR_ITER_BEGIN(from)+len);
750 *VECTOR_ITER_END(*str) = 0;
753 void al_string_copy_cstr(al_string *str, const al_string_char_type *from)
755 size_t len = strlen(from);
756 VECTOR_RESERVE(*str, len+1);
757 VECTOR_RESIZE(*str, 0);
758 VECTOR_INSERT(*str, VECTOR_ITER_END(*str), from, from+len);
759 *VECTOR_ITER_END(*str) = 0;
762 void al_string_append_char(al_string *str, const al_string_char_type c)
764 VECTOR_RESERVE(*str, al_string_length(*str)+2);
765 VECTOR_PUSH_BACK(*str, c);
766 *VECTOR_ITER_END(*str) = 0;
769 void al_string_append_cstr(al_string *str, const al_string_char_type *from)
771 size_t len = strlen(from);
772 if(len != 0)
774 VECTOR_RESERVE(*str, al_string_length(*str)+len+1);
775 VECTOR_INSERT(*str, VECTOR_ITER_END(*str), from, from+len);
776 *VECTOR_ITER_END(*str) = 0;
780 void al_string_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
782 if(to != from)
784 VECTOR_RESERVE(*str, al_string_length(*str)+(to-from)+1);
785 VECTOR_INSERT(*str, VECTOR_ITER_END(*str), from, to);
786 *VECTOR_ITER_END(*str) = 0;
790 #ifdef _WIN32
791 void al_string_copy_wcstr(al_string *str, const wchar_t *from)
793 int len;
794 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
796 VECTOR_RESERVE(*str, len);
797 VECTOR_RESIZE(*str, len-1);
798 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
799 *VECTOR_ITER_END(*str) = 0;
802 #endif
805 void InitUIntMap(UIntMap *map, ALsizei limit)
807 map->array = NULL;
808 map->size = 0;
809 map->maxsize = 0;
810 map->limit = limit;
811 RWLockInit(&map->lock);
814 void ResetUIntMap(UIntMap *map)
816 WriteLock(&map->lock);
817 free(map->array);
818 map->array = NULL;
819 map->size = 0;
820 map->maxsize = 0;
821 WriteUnlock(&map->lock);
824 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
826 ALsizei pos = 0;
828 WriteLock(&map->lock);
829 if(map->size > 0)
831 ALsizei low = 0;
832 ALsizei high = map->size - 1;
833 while(low < high)
835 ALsizei mid = low + (high-low)/2;
836 if(map->array[mid].key < key)
837 low = mid + 1;
838 else
839 high = mid;
841 if(map->array[low].key < key)
842 low++;
843 pos = low;
846 if(pos == map->size || map->array[pos].key != key)
848 if(map->size == map->limit)
850 WriteUnlock(&map->lock);
851 return AL_OUT_OF_MEMORY;
854 if(map->size == map->maxsize)
856 ALvoid *temp = NULL;
857 ALsizei newsize;
859 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
860 if(newsize >= map->maxsize)
861 temp = realloc(map->array, newsize*sizeof(map->array[0]));
862 if(!temp)
864 WriteUnlock(&map->lock);
865 return AL_OUT_OF_MEMORY;
867 map->array = temp;
868 map->maxsize = newsize;
871 if(pos < map->size)
872 memmove(&map->array[pos+1], &map->array[pos],
873 (map->size-pos)*sizeof(map->array[0]));
874 map->size++;
876 map->array[pos].key = key;
877 map->array[pos].value = value;
878 WriteUnlock(&map->lock);
880 return AL_NO_ERROR;
883 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
885 ALvoid *ptr = NULL;
886 WriteLock(&map->lock);
887 if(map->size > 0)
889 ALsizei low = 0;
890 ALsizei high = map->size - 1;
891 while(low < high)
893 ALsizei mid = low + (high-low)/2;
894 if(map->array[mid].key < key)
895 low = mid + 1;
896 else
897 high = mid;
899 if(map->array[low].key == key)
901 ptr = map->array[low].value;
902 if(low < map->size-1)
903 memmove(&map->array[low], &map->array[low+1],
904 (map->size-1-low)*sizeof(map->array[0]));
905 map->size--;
908 WriteUnlock(&map->lock);
909 return ptr;
912 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
914 ALvoid *ptr = NULL;
915 ReadLock(&map->lock);
916 if(map->size > 0)
918 ALsizei low = 0;
919 ALsizei high = map->size - 1;
920 while(low < high)
922 ALsizei mid = low + (high-low)/2;
923 if(map->array[mid].key < key)
924 low = mid + 1;
925 else
926 high = mid;
928 if(map->array[low].key == key)
929 ptr = map->array[low].value;
931 ReadUnlock(&map->lock);
932 return ptr;