How to use rust to implement align_ptr in c++

like this

template<typename _Tp>
static inline _Tp* alignPtr(_Tp* ptr, int n = (int)sizeof(_Tp))
{
    return (_Tp*)(((size_t)ptr + n - 1) & -n);
}

static inline void* fastMalloc(size_t size) {
  unsigned char* udata = (unsigned char*)malloc(size + sizeof(void*) + MALLOC_ALIGN);
  if (!udata)
    return 0;
  unsigned char** adata = alignPtr((unsigned char**)udata + 1, MALLOC_ALIGN);
  adata[-1] = udata;
  return adata;
}

static inline void fastFree(void* ptr) {
  if (ptr) {
    unsigned char* udata = ((unsigned char**)ptr)[-1];
    free(udata);
  }
}

Something like this?

unsafe fn align_ptr<T>(ptr: *mut u8) -> *mut T {
    ptr.add(ptr.align_offset(core::mem::size_of::<T>())).cast()
}
4 Likes

thanks!

anyone else has any ideas? :grinning_face_with_smiling_eyes:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.