1// Licensed to the .NET Foundation under one or more agreements.
2// The .NET Foundation licenses this file to you under the MIT license.
3// See the LICENSE file in the project root for more information.
4// ---------------------------------------------------------------------------
5// SString_COM.cpp
6
7// ---------------------------------------------------------------------------
8
9#include "stdafx.h"
10#include "sstring.h"
11#include "ex.h"
12#include "holder.h"
13
14#define DEFAULT_RESOURCE_STRING_SIZE 255
15
16//----------------------------------------------------------------------------
17// Load the string resource into this string.
18//----------------------------------------------------------------------------
19BOOL SString::LoadResource(CCompRC::ResourceCategory eCategory, int resourceID)
20{
21 return SUCCEEDED(LoadResourceAndReturnHR(eCategory, resourceID));
22}
23
24HRESULT SString::LoadResourceAndReturnHR(CCompRC::ResourceCategory eCategory, int resourceID)
25{
26 WRAPPER_NO_CONTRACT;
27 return LoadResourceAndReturnHR(NULL, eCategory,resourceID);
28}
29
30HRESULT SString::LoadResourceAndReturnHR(CCompRC* pResourceDLL, CCompRC::ResourceCategory eCategory, int resourceID)
31{
32 CONTRACT(BOOL)
33 {
34 INSTANCE_CHECK;
35 NOTHROW;
36 }
37 CONTRACT_END;
38
39 HRESULT hr = E_FAIL;
40
41#ifndef FEATURE_UTILCODE_NO_DEPENDENCIES
42 if (pResourceDLL == NULL)
43 {
44 pResourceDLL = CCompRC::GetDefaultResourceDll();
45 }
46
47 if (pResourceDLL != NULL)
48 {
49
50 int size = 0;
51
52 EX_TRY
53 {
54 if (GetRawCount() == 0)
55 Resize(DEFAULT_RESOURCE_STRING_SIZE, REPRESENTATION_UNICODE);
56
57 while (TRUE)
58 {
59 // First try and load the string in the amount of space that we have.
60 // In fatal error reporting scenarios, we may not have enough memory to
61 // allocate a larger buffer.
62
63 hr = pResourceDLL->LoadString(eCategory, resourceID, GetRawUnicode(), GetRawCount()+1, &size);
64 if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
65 {
66 if (FAILED(hr))
67 {
68 Clear();
69 break;
70 }
71
72 // Although we cannot generally detect truncation, we can tell if we
73 // used up all the space (in which case we will assume truncation.)
74 if (size < (int)GetRawCount())
75 {
76 break;
77 }
78 }
79
80 // Double the size and try again.
81 Resize(size*2, REPRESENTATION_UNICODE);
82
83 }
84
85 if (SUCCEEDED(hr))
86 {
87 Truncate(Begin() + (COUNT_T) wcslen(GetRawUnicode()));
88 }
89
90 Normalize();
91
92 }
93 EX_CATCH
94 {
95 hr = E_FAIL;
96 }
97 EX_END_CATCH(SwallowAllExceptions);
98 }
99#endif //!FEATURE_UTILCODE_NO_DEPENDENCIES
100
101 RETURN hr;
102} // SString::LoadResourceAndReturnHR
103