Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
2.0 KiB

  1. // Copyright (c) 1999 Microsoft Corporation. All rights reserved.
  2. //
  3. // Misc tiny helper functions.
  4. //
  5. #pragma once
  6. // Releases a COM pointer and then sets it to NULL. No effect if pointer already was NULL.
  7. template<class T>
  8. void SafeRelease(T *&t) { if (t) t->Release(); t = NULL; }
  9. // Returns the number of elements in an array determined at compile time.
  10. // Note: Only works for variables actually declared as arrays. Don't try this with a pointer to an array. There's no way to determine the size at that point.
  11. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(*(array)))
  12. // Zeros memory of struct pointed to.
  13. // Note: This is statically typed. Don't use it with a pointer to void, pointer to an array, or a pointer to a base class because the size will be too small.
  14. template<class T> void Zero(T *pT) { ZeroMemory(pT, sizeof(*pT)); }
  15. // Zeros memory of the struct pointed to and sets its dwSize field.
  16. template<class T> void ZeroAndSize(T *pT) { Zero(pT); pT->dwSize = sizeof(*pT); }
  17. // Copies one dwSize struct to another dwSize struct without reading/writing beyond either struct
  18. template<class T> void CopySizedStruct(T *ptDest, const T *ptSrc)
  19. {
  20. assert(ptDest && ptSrc);
  21. DWORD dwDestSize = ptDest->dwSize;
  22. memcpy(ptDest, ptSrc, std::_cpp_min(ptDest->dwSize, ptSrc->dwSize));
  23. ptDest->dwSize = dwDestSize;
  24. }
  25. // Copy pwszSource to pwszDest where pwszDest is a buffer of size uiBufferSize.
  26. // Returns S_OK if successful or DMUS_S_STRING_TRUNCATED if the string had to be truncated.
  27. // Faster then wcsncpy for short strings because the entire buffer isn't padded with nulls.
  28. inline HRESULT wcsTruncatedCopy(WCHAR *pwszDest, const WCHAR *pwszSource, UINT uiBufferSize)
  29. {
  30. for (UINT i = 0; i < uiBufferSize; ++i)
  31. {
  32. if (!(pwszDest[i] = pwszSource[i])) // assign and check for null
  33. return S_OK; // the whole string copied
  34. }
  35. // string needs to be truncated
  36. pwszDest[uiBufferSize - 1] = L'\0';
  37. return DMUS_S_STRING_TRUNCATED;
  38. }