1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::{ffi::CString, ptr};

use crate::{check_status, sys};

use super::{FromNapiValue, ToNapiValue, TypeName, ValidateNapiValue};

pub struct Symbol {
  desc: Option<String>,
  #[cfg(feature = "napi9")]
  for_desc: Option<String>,
}

impl TypeName for Symbol {
  fn type_name() -> &'static str {
    "Symbol"
  }

  fn value_type() -> crate::ValueType {
    crate::ValueType::Symbol
  }
}

impl ValidateNapiValue for Symbol {}

impl Symbol {
  pub fn new(desc: String) -> Self {
    Self {
      desc: Some(desc),
      #[cfg(feature = "napi9")]
      for_desc: None,
    }
  }

  pub fn identity() -> Self {
    Self {
      desc: None,
      #[cfg(feature = "napi9")]
      for_desc: None,
    }
  }

  #[cfg(feature = "napi9")]
  pub fn for_desc(desc: String) -> Self {
    Self {
      desc: None,
      for_desc: Some(desc.to_owned()),
    }
  }
}

impl ToNapiValue for Symbol {
  unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> crate::Result<sys::napi_value> {
    let mut symbol_value = ptr::null_mut();
    #[cfg(feature = "napi9")]
    if let Some(desc) = val.for_desc {
      check_status!(
        unsafe {
          sys::node_api_symbol_for(env, desc.as_ptr().cast(), desc.len(), &mut symbol_value)
        },
        "Failed to call node_api_symbol_for"
      )?;
      return Ok(symbol_value);
    }
    check_status!(unsafe {
      sys::napi_create_symbol(
        env,
        match val.desc {
          Some(desc) => {
            let mut desc_string = ptr::null_mut();
            let desc_len = desc.len();
            let desc_c_string = CString::new(desc)?;
            check_status!(sys::napi_create_string_utf8(
              env,
              desc_c_string.as_ptr(),
              desc_len,
              &mut desc_string
            ))?;
            desc_string
          }
          None => ptr::null_mut(),
        },
        &mut symbol_value,
      )
    })?;
    Ok(symbol_value)
  }
}

impl FromNapiValue for Symbol {
  unsafe fn from_napi_value(
    _env: sys::napi_env,
    _napi_val: sys::napi_value,
  ) -> crate::Result<Self> {
    Ok(Self {
      desc: None,
      #[cfg(feature = "napi9")]
      for_desc: None,
    })
  }
}