Note that there are some explanatory texts on larger screens.

plurals
  1. POConvert PSTR to PWSTR and Escape Certain Characters
    primarykey
    data
    text
    <p>I am trying to put together a function to convert a PSTR to a PWSTR and at the same time, escape certain characters at the same time. I have no control over the input PSTR contains. It can be the contents on any web page.</p> <p>I have the following code already, but I was wondering if there is a better / more effecient way, or if what I have will even work.</p> <pre><code>__inline PCWSTR ToEscape(CHAR c) { switch (c) { case '"': return L"\""; case '\\': return L"\\"; case '\b': return L"\b"; case '\f': return L"\f"; case '\n': return L"\n"; case '\r': return L"\r"; case '\t': return L"\t"; default: return NULL; } } // Helper for mbstowcs_s that does not return NULL terminator included in size __inline DWORD CharToWChar(__out_ecount_opt(cchBuffer) WCHAR* pszBuffer, __in DWORD cchBuffer, __in_ecount(valueLen) PCSTR value, __in DWORD valueLen) { if (valueLen == 0) return 0; size_t dwSize = 0; mbstowcs_s(&amp;dwSize, pszBuffer, cchBuffer, value, valueLen); return dwSize - 1; } // Writes the input value to pszBuffer, or if pszBuffer is NULL, returns the length necessary to write value __inline DWORD WriteJsonValue(__out_ecount_opt(cchBuffer) WCHAR* pszBuffer, __in DWORD cchBuffer, __in PCSTR value) { if (pszBuffer == NULL) { DWORD offset = 2; PCSTR start = value; DWORD index = 0; while (value[index] != '\0') { PCWSTR Escape = ToEscape(value[index]); if (Escape) { offset += CharToWChar(NULL, 0, start, (value + index) - start); start = value + index + 1; offset += 2; } index++; } // Any more left to write? offset += CharToWChar(NULL, 0, start, (value + index) - start); return offset; } else { DWORD offset = 0; if (cchBuffer &lt; 1) return 0; pszBuffer[offset++] = L'"'; PCSTR start = value; DWORD index = 0; while (value[index] != '\0') { PCWSTR Escape = ToEscape(value[index]); if (Escape) { DWORD dwLen = (value + index) - start; offset += CharToWChar(pszBuffer+offset, cchBuffer-offset, start, dwLen); start = value + index + 1; if (cchBuffer &lt; offset + 2) return offset; pszBuffer[offset++] = Escape[0]; pszBuffer[offset++] = Escape[1]; } index++; } // Any more left to write? DWORD dwLen = (value + index) - start; offset += CharToWChar(pszBuffer+offset, cchBuffer-offset, start, dwLen); if (cchBuffer &lt; offset + 1) return offset; pszBuffer[offset++] = L'"'; return offset; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload