summaryrefslogtreecommitdiff
path: root/src/classlibnative/bcltype/stringnative.cpp
blob: af6593a6bed8689b80cce254959cee01f4c0ea29 (plain)
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: StringNative.cpp
//

//
// Purpose: The implementation of the String class.
//

//

#include "common.h"

#include "object.h"
#include "utilcode.h"
#include "excep.h"
#include "frames.h"
#include "field.h"
#include "vars.hpp"
#include "stringnative.h"
#include "stringbuffer.h"
#include "comutilnative.h"
#include "metasig.h"
#include "excep.h"

// Compile the string functionality with these pragma flags (equivalent of the command line /Ox flag)
// Compiling this functionality differently gives us significant throughout gain in some cases.
#if defined(_MSC_VER) && defined(_TARGET_X86_)
#pragma optimize("tgy", on)
#endif


#define PROBABILISTICMAP_BLOCK_INDEX_MASK    0X7
#define PROBABILISTICMAP_BLOCK_INDEX_SHIFT   0x3
#define PROBABILISTICMAP_SIZE                0X8

//
//
// FORWARD DECLARATIONS
//
//
int ArrayContains(WCHAR searchChar, __in_ecount(length) const WCHAR *begin, int length);
void InitializeProbabilisticMap(int* charMap, __in_ecount(length) const WCHAR* charArray, int length);
bool ProbablyContains(const int* charMap, WCHAR searchChar);
bool IsBitSet(int value, int bitPos);
void SetBit(int* value, int bitPos);

//
//
//  CONSTRUCTORS
//
//

/*===========================StringInitSBytPtrPartialEx===========================
**Action:  Takes a byte *, startIndex, length, and encoding and turns this into a string.
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/

FCIMPL5(Object *, COMString::StringInitSBytPtrPartialEx, StringObject *thisString,
        I1 *ptr, INT32 startIndex, INT32 length, Object *encoding)
{
    CONTRACTL
    {
        FCALL_CHECK;
        PRECONDITION(thisString == 0);
        PRECONDITION(ptr != NULL);
    } CONTRACTL_END;

    STRINGREF pString = NULL;
    VALIDATEOBJECT(encoding);

    HELPER_METHOD_FRAME_BEGIN_RET_1(encoding);
    MethodDescCallSite createString(METHOD__STRING__CREATE_STRING);

    ARG_SLOT args[] = {
        PtrToArgSlot(ptr),
        startIndex,
        length,
        ObjToArgSlot(ObjectToOBJECTREF(encoding)),
    };

    pString = createString.Call_RetSTRINGREF(args);
    HELPER_METHOD_FRAME_END();
    return OBJECTREFToObject(pString);
}
FCIMPLEND

/*==============================StringInitCharPtr===============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL2(Object *, COMString::StringInitCharPtr, StringObject *stringThis, INT8 *ptr)
{
    FCALL_CONTRACT;

    _ASSERTE(stringThis == 0);      // This is the constructor
    Object *result = NULL;
    HELPER_METHOD_FRAME_BEGIN_RET_0();
    result = OBJECTREFToObject(StringObject::StringInitCharHelper((LPCSTR)ptr, -1));
    HELPER_METHOD_FRAME_END();
    return result;
}
FCIMPLEND

/*===========================StringInitCharPtrPartial===========================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL4(Object *, COMString::StringInitCharPtrPartial, StringObject *stringThis, INT8 *value,
        INT32 startIndex, INT32 length)
{
    CONTRACTL
    {
        FCALL_CHECK;
        PRECONDITION(stringThis ==0);
    } CONTRACTL_END;

    STRINGREF pString = NULL;

    //Verify the args.
    if (startIndex<0) {
        FCThrowArgumentOutOfRange(W("startIndex"), W("ArgumentOutOfRange_StartIndex"));
    }

    if (length<0) {
        FCThrowArgumentOutOfRange(W("length"), W("ArgumentOutOfRange_NegativeLength"));
    }

    // This is called directly now. There is no check in managed code.
    if( value == NULL) {
        FCThrowArgumentNull(W("value"));
    }

    LPCSTR pBase = (LPCSTR)value;
    LPCSTR pFrom = pBase + startIndex;
    if (pFrom < pBase) {
        // Check for overflow of pointer addition
        FCThrowArgumentOutOfRange(W("startIndex"), W("ArgumentOutOfRange_PartialWCHAR"));
    }

    HELPER_METHOD_FRAME_BEGIN_RET_0();
    
    pString = StringObject::StringInitCharHelper(pFrom, length);
    HELPER_METHOD_FRAME_END();

    return OBJECTREFToObject(pString);
}
FCIMPLEND

#ifdef FEATURE_RANDOMIZED_STRING_HASHING

inline COMNlsHashProvider * GetCurrentNlsHashProvider()
{
    LIMITED_METHOD_CONTRACT;
    return &COMNlsHashProvider::s_NlsHashProvider;
}

FCIMPL3(INT32, COMString::Marvin32HashString, StringObject* thisRefUNSAFE, INT32 strLen, INT64 additionalEntropy) {
    FCALL_CONTRACT;

    int iReturnHash = 0;

    if (thisRefUNSAFE == NULL) {
        FCThrow(kNullReferenceException);
    }

    BEGIN_SO_INTOLERANT_CODE_NOTHROW(GetThread(), FCThrow(kStackOverflowException));
    iReturnHash = GetCurrentNlsHashProvider()->HashString(thisRefUNSAFE->GetBuffer(), thisRefUNSAFE->GetStringLength(), TRUE, additionalEntropy);
    END_SO_INTOLERANT_CODE;

    FC_GC_POLL_RET();

    return iReturnHash;
}
FCIMPLEND

BOOL QCALLTYPE COMString::UseRandomizedHashing() {
    QCALL_CONTRACT;

    BOOL bUseRandomizedHashing = FALSE;

    BEGIN_QCALL;

    bUseRandomizedHashing = GetCurrentNlsHashProvider()->GetUseRandomHashing();

    END_QCALL;

    return bUseRandomizedHashing;
}
#endif

/*===============================IsFastSort===============================
**Action: Call the helper to walk the string and see if we have any high chars.
**Returns: void.  The appropriate bits are set on the String.
**Arguments: vThisRef - The string to be checked.
**Exceptions: None.
==============================================================================*/
FCIMPL1(FC_BOOL_RET, COMString::IsFastSort, StringObject* thisRef) {
    FCALL_CONTRACT;

    VALIDATEOBJECT(thisRef);
    _ASSERTE(thisRef!=NULL);
    DWORD state = thisRef->GetHighCharState();
    if (IS_STRING_STATE_UNDETERMINED(state)) {
        state = (STRINGREF(thisRef))->InternalCheckHighChars();
        FC_GC_POLL_RET();
    }
    else {
        FC_GC_POLL_NOT_NEEDED();
    }
    FC_RETURN_BOOL(IS_FAST_SORT(state)); //This can indicate either high chars or special sorting chars.
}
FCIMPLEND

/*===============================IsAscii===============================
**Action: Call the helper to walk the string and see if we have any high chars.
**Returns: void.  The appropriate bits are set on the String.
**Arguments: vThisRef - The string to be checked.
**Exceptions: None.
==============================================================================*/
FCIMPL1(FC_BOOL_RET, COMString::IsAscii, StringObject* thisRef) {
    FCALL_CONTRACT;

    VALIDATEOBJECT(thisRef);
    _ASSERTE(thisRef!=NULL);
    DWORD state = thisRef->GetHighCharState();
    if (IS_STRING_STATE_UNDETERMINED(state)) {
        state = (STRINGREF(thisRef))->InternalCheckHighChars();
        FC_GC_POLL_RET();
    }
    else {
        FC_GC_POLL_NOT_NEEDED();
    }
    FC_RETURN_BOOL(IS_ASCII(state)); //This can indicate either high chars or special sorting chars.
}
FCIMPLEND



//This function relies on the fact that we put a terminating null on the end of
//all managed strings.
FCIMPL2(INT32, COMString::FCCompareOrdinalIgnoreCaseWC, StringObject* strA, __in_z INT8 *strBChars) {
    FCALL_CONTRACT;

    VALIDATEOBJECT(strA);
    WCHAR *strAChars;
    WCHAR *strAStart;
    INT32 aLength;
    INT32 ret;

    _ASSERT(strA != NULL && strBChars != NULL);

    //Get our data.
    strA->RefInterpretGetStringValuesDangerousForGC((WCHAR **) &strAChars, &aLength);

    //Record the start pointer for some comparisons at the end.
    strAStart = strAChars;

    if (!StringObject::CaseInsensitiveCompHelper(strAChars, strBChars, aLength, -1, &ret)) {
        //This will happen if we have characters greater than 0x7F. This indicates that the function failed.
        // We don't throw an exception here. You can look at the success value returned to do something meaningful.
        ret = 1;
    }

    FC_GC_POLL_RET();
    return ret;
}
FCIMPLEND

/*================================CompareOrdinalEx===============================
**Args: typedef struct {STRINGREF thisRef; INT32 options; INT32 length; INT32 valueOffset;\
        STRINGREF value; INT32 thisOffset;} _compareOrdinalArgsEx;
==============================================================================*/

FCIMPL6(INT32, COMString::CompareOrdinalEx, StringObject* strA, INT32 indexA, INT32 countA, StringObject* strB, INT32 indexB, INT32 countB)
{
    FCALL_CONTRACT;

    VALIDATEOBJECT(strA);
    VALIDATEOBJECT(strB);
    DWORD *strAChars, *strBChars;
    int strALength, strBLength;

    // These runtime tests are handled in the managed wrapper.
    _ASSERTE(strA != NULL && strB != NULL);
    _ASSERTE(indexA >= 0 && indexB >= 0);
    _ASSERTE(countA >= 0 && countB >= 0);

    strA->RefInterpretGetStringValuesDangerousForGC((WCHAR **) &strAChars, &strALength);
    strB->RefInterpretGetStringValuesDangerousForGC((WCHAR **) &strBChars, &strBLength);

    _ASSERTE(countA <= strALength - indexA);
    _ASSERTE(countB <= strBLength - indexB);

    // Set up the loop variables.
    strAChars = (DWORD *) ((WCHAR *) strAChars + indexA);
    strBChars = (DWORD *) ((WCHAR *) strBChars + indexB);

    INT32 result = StringObject::FastCompareStringHelper(strAChars, countA, strBChars, countB);

    FC_GC_POLL_RET();
    return result;

}
FCIMPLEND

/*===============================IndexOfCharArray===============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL4(INT32, COMString::IndexOfCharArray, StringObject* thisRef, CHARArray* valueRef, INT32 startIndex, INT32 count )
{
    FCALL_CONTRACT;

    VALIDATEOBJECT(thisRef);
    VALIDATEOBJECT(valueRef);

    if (thisRef == NULL)
        FCThrow(kNullReferenceException);
    if (valueRef == NULL)
        FCThrowArgumentNull(W("anyOf"));

    WCHAR *thisChars;
    WCHAR *valueChars;
    int valueLength;
    int thisLength;

    thisRef->RefInterpretGetStringValuesDangerousForGC(&thisChars, &thisLength);

    if (startIndex < 0 || startIndex > thisLength) {
        FCThrowArgumentOutOfRange(W("startIndex"), W("ArgumentOutOfRange_Index"));
    }

    if (count < 0 || count > thisLength - startIndex) {
        FCThrowArgumentOutOfRange(W("count"), W("ArgumentOutOfRange_Count"));
    }

    int endIndex = startIndex + count;

    valueLength = valueRef->GetNumComponents();
    valueChars = (WCHAR *)valueRef->GetDataPtr();

    // use probabilistic map, see (code:InitializeProbabilisticMap)
    int charMap[PROBABILISTICMAP_SIZE] = {0};

    InitializeProbabilisticMap(charMap, valueChars, valueLength);

    for(int i = startIndex; i < endIndex; i++) {
        WCHAR thisChar = thisChars[i];
        if (ProbablyContains(charMap, thisChar))
            if (ArrayContains(thisChars[i], valueChars, valueLength) >= 0) {
                FC_GC_POLL_RET();
                return i;
            }
    }

    FC_GC_POLL_RET();
    return -1;
}
FCIMPLEND

/*=============================LastIndexOfCharArray=============================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/

FCIMPL4(INT32, COMString::LastIndexOfCharArray, StringObject* thisRef, CHARArray* valueRef, INT32 startIndex, INT32 count )
{
    FCALL_CONTRACT;

    VALIDATEOBJECT(thisRef);
    VALIDATEOBJECT(valueRef);
    WCHAR *thisChars, *valueChars;
    int thisLength, valueLength;

    if (thisRef==NULL) {
        FCThrow(kNullReferenceException);
    }

    if (valueRef == NULL)
        FCThrowArgumentNull(W("anyOf"));

    thisRef->RefInterpretGetStringValuesDangerousForGC(&thisChars, &thisLength);

    if (thisLength == 0) {
        return -1;
    }

    if (startIndex < 0 || startIndex >= thisLength) {
        FCThrowArgumentOutOfRange(W("startIndex"), W("ArgumentOutOfRange_Index"));
    }

    if (count<0 || count - 1 > startIndex) {
        FCThrowArgumentOutOfRange(W("count"), W("ArgumentOutOfRange_Count"));
    }


    valueLength = valueRef->GetNumComponents();
    valueChars = (WCHAR *)valueRef->GetDataPtr();

    int endIndex = startIndex - count + 1;

    // use probabilistic map, see (code:InitializeProbabilisticMap)
    int charMap[PROBABILISTICMAP_SIZE] = {0};

    InitializeProbabilisticMap(charMap, valueChars, valueLength);

    //We search [startIndex..EndIndex]
    for (int i=startIndex; i>=endIndex; i--) {
        WCHAR thisChar = thisChars[i];
        if (ProbablyContains(charMap, thisChar))
            if (ArrayContains(thisChars[i],valueChars, valueLength) >= 0) {
                FC_GC_POLL_RET();
                return i;
            }
    }

    FC_GC_POLL_RET();
    return -1;

}
FCIMPLEND

/*==================================GETCHARAT===================================
**Returns the character at position index.  Thows IndexOutOfRangeException as
**appropriate.
**This method is not actually used. JIT will generate code for indexer method on string class.
**
==============================================================================*/
FCIMPL2(FC_CHAR_RET, COMString::GetCharAt, StringObject* str, INT32 index) {
    FCALL_CONTRACT;

    FC_GC_POLL_NOT_NEEDED();
    VALIDATEOBJECT(str);
    if (str == NULL) {
        FCThrow(kNullReferenceException);
    }
    _ASSERTE(str->GetMethodTable() == g_pStringClass);

    if (index >=0 && index < (INT32)str->GetStringLength()) {
        //Return the appropriate character.
        return str->GetBuffer()[index];
    }

    FCThrow(kIndexOutOfRangeException);
}
FCIMPLEND


/*==================================LENGTH=================================== */

FCIMPL1(INT32, COMString::Length, StringObject* str) {
    FCALL_CONTRACT;

    FC_GC_POLL_NOT_NEEDED();
    if (str == NULL)
        FCThrow(kNullReferenceException);

    FCUnique(0x11);
    return str->GetStringLength();
}
FCIMPLEND


// HELPER METHODS
// 
// 
// A probabilistic map is an optimization that is used in IndexOfAny/
// LastIndexOfAny methods. The idea is to create a bit map of the characters we
// are searching for and use this map as a "cheap" check to decide if the
// current character in the string exists in the array of input characters.
// There are 256 bits in the map, with each character mapped to 2 bits. Every
// character is divided into 2 bytes, and then every byte is mapped to 1 bit.
// The character map is an array of 8 integers acting as map blocks. The 3 lsb
// in each byte in the character is used to index into this map to get the
// right block, the value of the remaining 5 msb are used as the bit position
// inside this block. 
void InitializeProbabilisticMap(int* charMap, __in_ecount(length) const WCHAR* charArray, int length) {
    LIMITED_METHOD_CONTRACT;

    _ASSERTE(charMap != NULL);
    _ASSERTE(charArray != NULL);
    _ASSERTE(length >= 0);

    for(int i = 0; i < length; ++i) {
        int hi,lo;

        WCHAR c = charArray[i];

        hi = (c >> 8) & 0xFF;
        lo = c & 0xFF;

        int* value = &charMap[lo & PROBABILISTICMAP_BLOCK_INDEX_MASK];
        SetBit(value, lo >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT);

        value = &charMap[hi & PROBABILISTICMAP_BLOCK_INDEX_MASK];
        SetBit(value, hi >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT);
    }
}

// Use the probabilistic map to decide if the character value exists in the
// map. When this method return false, we are certain the character doesn't
// exist, however a true return means it *may* exist.
inline bool ProbablyContains(const int* charMap, WCHAR searchValue) {
    LIMITED_METHOD_CONTRACT;

    int lo, hi;

    lo = searchValue & 0xFF;
    int value = charMap[lo & PROBABILISTICMAP_BLOCK_INDEX_MASK];

    if (IsBitSet(value, lo >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT)) {
        hi = (searchValue >> 8) & 0xFF;
        value = charMap[hi & PROBABILISTICMAP_BLOCK_INDEX_MASK];

        return IsBitSet(value, hi >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT);
    }

    return false;
}

inline void SetBit(int* value, int bitPos) {
    LIMITED_METHOD_CONTRACT;

    _ASSERTE(bitPos <= 31);

    *value |= (1 << bitPos);
}

inline bool IsBitSet(int value, int bitPos) {
    LIMITED_METHOD_CONTRACT;

    _ASSERTE(bitPos <= 31);

    return (value & (1 << bitPos)) != 0;
}


/*================================ArrayContains=================================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
int ArrayContains(WCHAR searchChar, __in_ecount(length) const WCHAR *begin, int length) {
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(begin != NULL);
    _ASSERTE(length >= 0);

    for(int i = 0; i < length; i++) {
        if(begin[i] == searchChar) {
            return i;
        }
    }
    return -1;
}


/*================================ReplaceString=================================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
FCIMPL3(Object*, COMString::ReplaceString, StringObject* thisRefUNSAFE, StringObject* oldValueUNSAFE, StringObject* newValueUNSAFE)
{
    FCALL_CONTRACT;

    struct _gc
    {
        STRINGREF     thisRef;
        STRINGREF     oldValue;
        STRINGREF     newValue;
        STRINGREF     retValString;
    } gc;

    gc.thisRef        = ObjectToSTRINGREF(thisRefUNSAFE);
    gc.oldValue       = ObjectToSTRINGREF(oldValueUNSAFE);
    gc.newValue       = ObjectToSTRINGREF(newValueUNSAFE);
    gc.retValString   = NULL;

    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);

    int *replaceIndex;
    int index=0;
    int replaceCount=0;
    int readPos, writePos;
    WCHAR *thisBuffer, *oldBuffer, *newBuffer, *retValBuffer;
    int thisLength, oldLength, newLength;
    int endIndex;
    CQuickBytes replaceIndices;


    if (gc.thisRef==NULL) {
        COMPlusThrow(kNullReferenceException, W("NullReference_This"));
    }

    //Verify all of the arguments.
    if (!gc.oldValue) {
        COMPlusThrowArgumentNull(W("oldValue"), W("ArgumentNull_Generic"));
    }

    //If they asked to replace oldValue with a null, replace all occurances
    //with the empty string.
    if (!gc.newValue) {
        gc.newValue = StringObject::GetEmptyString();
    }

    gc.thisRef->RefInterpretGetStringValuesDangerousForGC(&thisBuffer, &thisLength);
    gc.oldValue->RefInterpretGetStringValuesDangerousForGC(&oldBuffer,  &oldLength);
    gc.newValue->RefInterpretGetStringValuesDangerousForGC(&newBuffer,  &newLength);

    //Record the endIndex so that we don't need to do this calculation all over the place.
    endIndex = thisLength;

    //If our old Length is 0, we won't know what to replace
    if (oldLength==0) {
        COMPlusThrowArgumentException(W("oldValue"), W("Argument_StringZeroLength"));
    }

    //replaceIndex is made large enough to hold the maximum number of replacements possible:
    //The case where every character in the current buffer gets replaced.
    replaceIndex = (int *)replaceIndices.AllocThrows((thisLength/oldLength+1)*sizeof(int));
    index=0;

    _ASSERTE(endIndex - oldLength <= endIndex);
    //Prefix: oldLength validated in mscorlib.dll!String.Replace
    PREFIX_ASSUME(endIndex - oldLength <= endIndex);

    while (((index=StringBufferObject::LocalIndexOfString(thisBuffer,oldBuffer,thisLength,oldLength,index))>-1) && (index<=endIndex-oldLength))
    {
        replaceIndex[replaceCount++] = index;
        index+=oldLength;
    }

    if (replaceCount != 0)
    {
        //Calculate the new length of the string and ensure that we have sufficent room.
        INT64 retValBuffLength = thisLength - ((oldLength - newLength) * (INT64)replaceCount);
        _ASSERTE(retValBuffLength >= 0);
        if (retValBuffLength > 0x7FFFFFFF)
            COMPlusThrowOM();

        gc.retValString = StringObject::NewString((INT32)retValBuffLength);
        retValBuffer = gc.retValString->GetBuffer();

        //Get the update buffers for all the Strings since the allocation could have triggered a GC.
        thisBuffer  = gc.thisRef->GetBuffer();
        newBuffer   = gc.newValue->GetBuffer();
        oldBuffer   = gc.oldValue->GetBuffer();


        //Set replaceHolder to be the upper limit of our array.
        int replaceHolder = replaceCount;
        replaceCount=0;

        //Walk the array forwards copying each character as we go.  If we reach an instance
        //of the string being replaced, replace the old string with the new string.
        readPos = 0;
        writePos = 0;
        while (readPos<thisLength)
        {
            if (replaceCount<replaceHolder&&readPos==replaceIndex[replaceCount])
            {
                replaceCount++;
                readPos+=(oldLength);
                memcpyNoGCRefs(&retValBuffer[writePos], newBuffer, newLength*sizeof(WCHAR));
                writePos+=(newLength);
            }
            else
            {
                retValBuffer[writePos++] = thisBuffer[readPos++];
            }
        }
        retValBuffer[retValBuffLength]='\0';
    }
    else
    {
        gc.retValString = gc.thisRef;
    }

    HELPER_METHOD_FRAME_END();

    return OBJECTREFToObject(gc.retValString);
}
FCIMPLEND



#ifdef FEATURE_COMINTEROP

FCIMPL2(FC_BOOL_RET, COMString::FCTryGetTrailByte, StringObject* thisRefUNSAFE, UINT8 *pbData)
{
    FCALL_CONTRACT;

    STRINGREF thisRef = ObjectToSTRINGREF(thisRefUNSAFE);
    FC_RETURN_BOOL(thisRef->GetTrailByte(pbData));
}
FCIMPLEND

FCIMPL2(VOID, COMString::FCSetTrailByte, StringObject* thisRefUNSAFE, UINT8 bData)
{
    FCALL_CONTRACT;

    STRINGREF thisRef = ObjectToSTRINGREF(thisRefUNSAFE);
    HELPER_METHOD_FRAME_BEGIN_1(thisRef);

    thisRef->SetTrailByte(bData);

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

#endif // FEATURE_COMINTEROP

// Revert to command line compilation flags
#if defined(_MSC_VER) && defined(_TARGET_X86_)
#pragma optimize ("", on)
#endif