You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How to efficiently convert to a std::string? #1161
Give how the API looks today is there an efficient way to convert a napi_value into a std::string without doing an extra copy? Currently in order to convert a nap string into a std::string we need to perform 2 copies. Would be nice to be able to at least reduce it to 1 copy. Would be even nicer if one could move/reference ownership i.e. 0 copy.
No, in that case it is not possible. Our unit tests check that must not happen. When we copy data to the buffer the result parameter is optional. If we skip testing error codes and number of copied bytes the code can be reduced to:
Activity
vmoroz commentedon Apr 8, 2022
@ronag, there is no need to do the copy twice. We can just copy the bytes directly to
std::stringafter it is set to the correct size. I have augmented thetest_stringin my personal branch to show it: https://github.com/vmoroz/node/blob/StdStringWithNodeAPI/test/js-native-api/test_string/test_std_string.ccThis is how it is done there for UTF8 strings:
Since
std::stringuses a small string optimization, for small strings this code may not do any heap allocation.ronag commentedon Apr 9, 2022
Thanks!
ronag commentedon Apr 9, 2022
What is
NODE_API_CALL?ronag commentedon Apr 9, 2022
Also is it possible for
copied != str_length?vmoroz commentedon Apr 9, 2022
This is a macro that checks that the function returns
napi_ok.vmoroz commentedon Apr 9, 2022
No, in that case it is not possible. Our unit tests check that must not happen. When we copy data to the buffer the result parameter is optional. If we skip testing error codes and number of copied bytes the code can be reduced to: