use std::{
ffi::{CStr, CString},
marker::PhantomData,
ptr,
};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use singe_core::{LibraryVersion, impl_enum_display};
use singe_cuda_sys::nvtx as sys;
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Color(u32);
impl Color {
#[must_use]
pub const fn argb(value: u32) -> Self {
Self(value)
}
#[must_use]
pub const fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
Self(((alpha as u32) << 24) | ((red as u32) << 16) | ((green as u32) << 8) | blue as u32)
}
#[must_use]
pub const fn as_raw(self) -> u32 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Category(u32);
impl Category {
#[must_use]
pub const fn from_raw(value: u32) -> Self {
Self(value)
}
#[must_use]
pub const fn as_raw(self) -> u32 {
self.0
}
}
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum ColorType: sys::nvtxColorType_t {
Unknown = NVTX_COLOR_UNKNOWN,
Argb = NVTX_COLOR_ARGB,
}
}
impl_enum_display!(ColorType, {
Self::Unknown => "NVTX_COLOR_UNKNOWN",
Self::Argb => "NVTX_COLOR_ARGB",
});
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum MessageType: sys::nvtxMessageType_t {
Unknown = NVTX_MESSAGE_UNKNOWN,
Ascii = NVTX_MESSAGE_TYPE_ASCII,
Unicode = NVTX_MESSAGE_TYPE_UNICODE,
Registered = NVTX_MESSAGE_TYPE_REGISTERED,
}
}
impl_enum_display!(MessageType, {
Self::Unknown => "NVTX_MESSAGE_UNKNOWN",
Self::Ascii => "NVTX_MESSAGE_TYPE_ASCII",
Self::Unicode => "NVTX_MESSAGE_TYPE_UNICODE",
Self::Registered => "NVTX_MESSAGE_TYPE_REGISTERED",
});
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum PayloadType: sys::nvtxPayloadType_t {
Unknown = NVTX_PAYLOAD_UNKNOWN,
UnsignedInt64 = NVTX_PAYLOAD_TYPE_UNSIGNED_INT64,
Int64 = NVTX_PAYLOAD_TYPE_INT64,
Double = NVTX_PAYLOAD_TYPE_DOUBLE,
UnsignedInt32 = NVTX_PAYLOAD_TYPE_UNSIGNED_INT32,
Int32 = NVTX_PAYLOAD_TYPE_INT32,
Float = NVTX_PAYLOAD_TYPE_FLOAT,
}
}
impl_enum_display!(PayloadType, {
Self::Unknown => "NVTX_PAYLOAD_UNKNOWN",
Self::UnsignedInt64 => "NVTX_PAYLOAD_TYPE_UNSIGNED_INT64",
Self::Int64 => "NVTX_PAYLOAD_TYPE_INT64",
Self::Double => "NVTX_PAYLOAD_TYPE_DOUBLE",
Self::UnsignedInt32 => "NVTX_PAYLOAD_TYPE_UNSIGNED_INT32",
Self::Int32 => "NVTX_PAYLOAD_TYPE_INT32",
Self::Float => "NVTX_PAYLOAD_TYPE_FLOAT",
});
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum ResourceGenericType: sys::nvtxResourceGenericType_t {
Unknown = NVTX_RESOURCE_TYPE_UNKNOWN,
GenericPointer = NVTX_RESOURCE_TYPE_GENERIC_POINTER,
GenericHandle = NVTX_RESOURCE_TYPE_GENERIC_HANDLE,
GenericThreadNative = NVTX_RESOURCE_TYPE_GENERIC_THREAD_NATIVE,
GenericThreadPosix = NVTX_RESOURCE_TYPE_GENERIC_THREAD_POSIX,
}
}
impl_enum_display!(ResourceGenericType, {
Self::Unknown => "NVTX_RESOURCE_TYPE_UNKNOWN",
Self::GenericPointer => "NVTX_RESOURCE_TYPE_GENERIC_POINTER",
Self::GenericHandle => "NVTX_RESOURCE_TYPE_GENERIC_HANDLE",
Self::GenericThreadNative => "NVTX_RESOURCE_TYPE_GENERIC_THREAD_NATIVE",
Self::GenericThreadPosix => "NVTX_RESOURCE_TYPE_GENERIC_THREAD_POSIX",
});
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Payload {
I32(i32),
I64(i64),
U32(u32),
U64(u64),
F32(f32),
F64(f64),
}
impl Payload {
fn encode_type(self) -> sys::nvtxPayloadType_t {
match self {
Self::I32(_) => PayloadType::Int32.into(),
Self::I64(_) => PayloadType::Int64.into(),
Self::U32(_) => PayloadType::UnsignedInt32.into(),
Self::U64(_) => PayloadType::UnsignedInt64.into(),
Self::F32(_) => PayloadType::Float.into(),
Self::F64(_) => PayloadType::Double.into(),
}
}
fn encode_value(self) -> sys::nvtxEventAttributes_v2_payload_t {
match self {
Self::I32(value) => sys::nvtxEventAttributes_v2_payload_t { iValue: value },
Self::I64(value) => sys::nvtxEventAttributes_v2_payload_t { llValue: value },
Self::U32(value) => sys::nvtxEventAttributes_v2_payload_t { uiValue: value },
Self::U64(value) => sys::nvtxEventAttributes_v2_payload_t { ullValue: value },
Self::F32(value) => sys::nvtxEventAttributes_v2_payload_t { fValue: value },
Self::F64(value) => sys::nvtxEventAttributes_v2_payload_t { dValue: value },
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct EventAttributes<'a> {
message: Option<&'a CStr>,
category: Option<Category>,
color: Option<Color>,
payload: Option<Payload>,
}
impl<'a> EventAttributes<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
message: None,
category: None,
color: None,
payload: None,
}
}
#[must_use]
pub fn with_message(mut self, message: &'a CStr) -> Self {
self.message = Some(message);
self
}
#[must_use]
pub fn with_category(mut self, category: Category) -> Self {
self.category = Some(category);
self
}
#[must_use]
pub fn with_color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
#[must_use]
pub fn with_payload(mut self, payload: Payload) -> Self {
self.payload = Some(payload);
self
}
#[must_use]
pub const fn message(&self) -> Option<&'a CStr> {
self.message
}
#[must_use]
pub const fn category(&self) -> Option<Category> {
self.category
}
#[must_use]
pub const fn color(&self) -> Option<Color> {
self.color
}
#[must_use]
pub const fn payload(&self) -> Option<Payload> {
self.payload
}
fn encode(self) -> sys::nvtxEventAttributes_t {
let mut raw = sys::nvtxEventAttributes_t {
version: u16::try_from(sys::NVTX_VERSION).expect("the NVTX version fits its ABI field"),
size: u16::try_from(size_of::<sys::nvtxEventAttributes_t>())
.expect("the NVTX event attributes fit their ABI size field"),
..Default::default()
};
if let Some(category) = self.category {
raw.category = category.0;
}
if let Some(color) = self.color {
raw.colorType = sys::nvtxColorType_t::from(ColorType::Argb).0.cast_signed();
raw.color = color.0;
}
if let Some(payload) = self.payload {
raw.payloadType = payload.encode_type().0.cast_signed();
raw.payload = payload.encode_value();
}
if let Some(message) = self.message {
raw.messageType = sys::nvtxMessageType_t::from(MessageType::Ascii)
.0
.cast_signed();
raw.message.ascii = message.as_ptr();
}
raw
}
}
impl Default for EventAttributes<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> From<&'a CStr> for EventAttributes<'a> {
fn from(message: &'a CStr) -> Self {
Self::new().with_message(message)
}
}
impl<'a> From<&'a CString> for EventAttributes<'a> {
fn from(message: &'a CString) -> Self {
Self::new().with_message(message)
}
}
impl<'a> From<&'a Event> for EventAttributes<'a> {
fn from(event: &'a Event) -> Self {
event.attributes()
}
}
#[derive(Debug, Clone)]
pub struct Event {
message: CString,
category: Option<Category>,
color: Option<Color>,
payload: Option<Payload>,
}
impl Event {
pub fn create(message: &str) -> Result<Self> {
Ok(Self::create_from_c_string(CString::new(message)?))
}
#[must_use]
pub fn create_from_c_string(message: CString) -> Self {
Self {
message,
category: None,
color: None,
payload: None,
}
}
#[must_use]
pub fn with_category(mut self, category: Category) -> Self {
self.category = Some(category);
self
}
#[must_use]
pub fn with_color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
#[must_use]
pub fn with_payload(mut self, payload: Payload) -> Self {
self.payload = Some(payload);
self
}
#[must_use]
pub fn attributes(&self) -> EventAttributes<'_> {
EventAttributes {
message: Some(&self.message),
category: self.category,
color: self.color,
payload: self.payload,
}
}
}
#[derive(Debug)]
pub struct Domain {
handle: sys::nvtxDomainHandle_t,
}
unsafe impl Send for Domain {}
unsafe impl Sync for Domain {}
impl Domain {
pub fn create(name: &str) -> Result<Self> {
let name = CString::new(name)?;
Self::create_from_c_str(&name)
}
pub fn create_from_c_str(name: &CStr) -> Result<Self> {
let handle = unsafe { sys::nvtxDomainCreateA(name.as_ptr()) };
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(Self { handle })
}
#[must_use]
pub fn as_raw(&self) -> sys::nvtxDomainHandle_t {
self.handle
}
pub fn mark<'a>(&self, attributes: impl Into<EventAttributes<'a>>) {
let raw = attributes.into().encode();
unsafe { sys::nvtxDomainMarkEx(self.handle, &raw const raw) };
}
#[must_use]
pub fn range<'a>(&self, attributes: impl Into<EventAttributes<'a>>) -> DomainLocalRange<'_> {
let raw = attributes.into().encode();
unsafe { sys::nvtxDomainRangePushEx(self.handle, &raw const raw) };
DomainLocalRange {
domain: self,
_not_send: PhantomData,
}
}
#[must_use]
pub fn start_range<'a>(&self, attributes: impl Into<EventAttributes<'a>>) -> DomainRange<'_> {
let raw = attributes.into().encode();
let id = unsafe { sys::nvtxDomainRangeStartEx(self.handle, &raw const raw) };
DomainRange { domain: self, id }
}
pub fn name_category(&self, category: Category, name: &str) -> Result<()> {
let name = CString::new(name)?;
unsafe { sys::nvtxDomainNameCategoryA(self.handle, category.0, name.as_ptr()) };
Ok(())
}
}
impl Drop for Domain {
fn drop(&mut self) {
unsafe { sys::nvtxDomainDestroy(self.handle) };
}
}
#[derive(Debug)]
pub struct LocalRange {
_not_send: PhantomData<*mut ()>,
}
impl LocalRange {
#[must_use]
pub fn push<'a>(attributes: impl Into<EventAttributes<'a>>) -> Self {
let raw = attributes.into().encode();
unsafe { sys::nvtxRangePushEx(&raw const raw) };
Self {
_not_send: PhantomData,
}
}
}
impl Drop for LocalRange {
fn drop(&mut self) {
unsafe { sys::nvtxRangePop() };
}
}
#[derive(Debug)]
pub struct Range {
id: sys::nvtxRangeId_t,
}
impl Range {
#[must_use]
pub fn start<'a>(attributes: impl Into<EventAttributes<'a>>) -> Self {
let raw = attributes.into().encode();
let id = unsafe { sys::nvtxRangeStartEx(&raw const raw) };
Self { id }
}
}
impl Drop for Range {
fn drop(&mut self) {
unsafe { sys::nvtxRangeEnd(self.id) };
}
}
#[derive(Debug)]
pub struct DomainLocalRange<'a> {
domain: &'a Domain,
_not_send: PhantomData<*mut ()>,
}
impl Drop for DomainLocalRange<'_> {
fn drop(&mut self) {
unsafe { sys::nvtxDomainRangePop(self.domain.handle) };
}
}
#[derive(Debug)]
pub struct DomainRange<'a> {
domain: &'a Domain,
id: sys::nvtxRangeId_t,
}
impl Drop for DomainRange<'_> {
fn drop(&mut self) {
unsafe { sys::nvtxDomainRangeEnd(self.domain.handle, self.id) };
}
}
#[must_use]
pub fn version() -> LibraryVersion {
LibraryVersion::new(sys::NVTX_VERSION, 0, 0)
}
pub fn initialize() {
unsafe { sys::nvtxInitialize(ptr::null()) };
}
pub fn mark<'a>(attributes: impl Into<EventAttributes<'a>>) {
let raw = attributes.into().encode();
unsafe { sys::nvtxMarkEx(&raw const raw) };
}
pub fn name_category(category: Category, name: &str) -> Result<()> {
let name = CString::new(name)?;
unsafe { sys::nvtxNameCategoryA(category.0, name.as_ptr()) };
Ok(())
}
pub fn name_os_thread(thread_id: u32, name: &str) -> Result<()> {
let name = CString::new(name)?;
unsafe { sys::nvtxNameOsThreadA(thread_id, name.as_ptr()) };
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encodes_event_attributes() {
let message = c"work";
let raw = EventAttributes::new()
.with_message(message)
.with_category(Category::from_raw(7))
.with_color(Color::rgba(1, 2, 3, 4))
.with_payload(Payload::I64(-42))
.encode();
assert_eq!(
raw.version,
u16::try_from(sys::NVTX_VERSION).expect("the NVTX version fits its ABI field")
);
assert_eq!(
raw.size,
u16::try_from(size_of::<sys::nvtxEventAttributes_t>())
.expect("the NVTX event attributes fit their ABI size field")
);
assert_eq!(raw.category, 7);
assert_eq!(
raw.colorType,
sys::nvtxColorType_t::NVTX_COLOR_ARGB.0.cast_signed()
);
assert_eq!(raw.color, 0x0401_0203);
assert_eq!(
raw.messageType,
sys::nvtxMessageType_t::NVTX_MESSAGE_TYPE_ASCII
.0
.cast_signed()
);
assert_eq!(unsafe { raw.message.ascii }, message.as_ptr());
assert_eq!(
raw.payloadType,
sys::nvtxPayloadType_t::NVTX_PAYLOAD_TYPE_INT64
.0
.cast_signed()
);
assert_eq!(unsafe { raw.payload.llValue }, -42);
}
#[test]
fn test_owned_event_builds_attributes() {
let event = Event::create("owned")
.unwrap()
.with_category(Category::from_raw(3))
.with_color(Color::argb(0xff00_00ff))
.with_payload(Payload::U32(11));
let attributes = event.attributes();
let raw = attributes.encode();
assert_eq!(attributes.message(), Some(c"owned"));
assert_eq!(attributes.category(), Some(Category::from_raw(3)));
assert_eq!(attributes.color(), Some(Color::argb(0xff00_00ff)));
assert_eq!(attributes.payload(), Some(Payload::U32(11)));
assert_eq!(raw.category, 3);
assert_eq!(raw.color, 0xff00_00ff);
assert_eq!(
raw.payloadType,
sys::nvtxPayloadType_t::NVTX_PAYLOAD_TYPE_UNSIGNED_INT32
.0
.cast_signed()
);
assert_eq!(unsafe { raw.payload.uiValue }, 11);
}
#[test]
fn test_enum_wrappers_convert_and_display() {
assert_eq!(
ColorType::try_from(sys::nvtxColorType_t::NVTX_COLOR_ARGB).unwrap(),
ColorType::Argb
);
assert_eq!(
sys::nvtxMessageType_t::from(MessageType::Ascii),
sys::nvtxMessageType_t::NVTX_MESSAGE_TYPE_ASCII
);
assert_eq!(
PayloadType::UnsignedInt64.to_string(),
"NVTX_PAYLOAD_TYPE_UNSIGNED_INT64"
);
assert_eq!(
ResourceGenericType::GenericThreadPosix.to_string(),
"NVTX_RESOURCE_TYPE_GENERIC_THREAD_POSIX"
);
}
}