xref: /netbsd-src/external/gpl3/gcc.old/dist/libstdc++-v3/include/ext/ropeimpl.h (revision 8feb0f0b7eaff0608f8350bbfa3098827b4bb91b)
1 // SGI's rope class implementation -*- C++ -*-
2 
3 // Copyright (C) 2001-2020 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library.  This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10 
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19 
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
23 // <http://www.gnu.org/licenses/>.
24 
25 /*
26  * Copyright (c) 1997
27  * Silicon Graphics Computer Systems, Inc.
28  *
29  * Permission to use, copy, modify, distribute and sell this software
30  * and its documentation for any purpose is hereby granted without fee,
31  * provided that the above copyright notice appear in all copies and
32  * that both that copyright notice and this permission notice appear
33  * in supporting documentation.  Silicon Graphics makes no
34  * representations about the suitability of this software for any
35  * purpose.  It is provided "as is" without express or implied warranty.
36  */
37 
38 /** @file ropeimpl.h
39  *  This is an internal header file, included by other library headers.
40  *  Do not attempt to use it directly. @headername{ext/rope}
41  */
42 
43 #include <cstdio>
44 #include <ostream>
45 #include <bits/functexcept.h>
46 
47 #include <ext/algorithm> // For copy_n and lexicographical_compare_3way
48 #include <ext/memory> // For uninitialized_copy_n
49 #include <ext/numeric> // For power
50 
_GLIBCXX_VISIBILITY(default)51 namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)
52 {
53 _GLIBCXX_BEGIN_NAMESPACE_VERSION
54 
55   // Set buf_start, buf_end, and buf_ptr appropriately, filling tmp_buf
56   // if necessary.  Assumes _M_path_end[leaf_index] and leaf_pos are correct.
57   // Results in a valid buf_ptr if the iterator can be legitimately
58   // dereferenced.
59   template <class _CharT, class _Alloc>
60     void
61     _Rope_iterator_base<_CharT, _Alloc>::
62     _S_setbuf(_Rope_iterator_base<_CharT, _Alloc>& __x)
63     {
64       using std::size_t;
65       const _RopeRep* __leaf = __x._M_path_end[__x._M_leaf_index];
66       size_t __leaf_pos = __x._M_leaf_pos;
67       size_t __pos = __x._M_current_pos;
68 
69       switch(__leaf->_M_tag)
70 	{
71 	case __detail::_S_leaf:
72 	  __x._M_buf_start = ((_Rope_RopeLeaf<_CharT, _Alloc>*)__leaf)->_M_data;
73 	  __x._M_buf_ptr = __x._M_buf_start + (__pos - __leaf_pos);
74 	  __x._M_buf_end = __x._M_buf_start + __leaf->_M_size;
75 	  break;
76 	case __detail::_S_function:
77 	case __detail::_S_substringfn:
78 	  {
79 	    size_t __len = _S_iterator_buf_len;
80 	    size_t __buf_start_pos = __leaf_pos;
81 	    size_t __leaf_end = __leaf_pos + __leaf->_M_size;
82 	    char_producer<_CharT>* __fn = ((_Rope_RopeFunction<_CharT,
83 					    _Alloc>*)__leaf)->_M_fn;
84 	    if (__buf_start_pos + __len <= __pos)
85 	      {
86 		__buf_start_pos = __pos - __len / 4;
87 		if (__buf_start_pos + __len > __leaf_end)
88 		  __buf_start_pos = __leaf_end - __len;
89 	      }
90 	    if (__buf_start_pos + __len > __leaf_end)
91 	      __len = __leaf_end - __buf_start_pos;
92 	    (*__fn)(__buf_start_pos - __leaf_pos, __len, __x._M_tmp_buf);
93 	    __x._M_buf_ptr = __x._M_tmp_buf + (__pos - __buf_start_pos);
94 	    __x._M_buf_start = __x._M_tmp_buf;
95 	    __x._M_buf_end = __x._M_tmp_buf + __len;
96 	  }
97 	  break;
98 	default:
99 	  break;
100 	}
101     }
102 
103   // Set path and buffer inside a rope iterator.  We assume that
104   // pos and root are already set.
105   template <class _CharT, class _Alloc>
106     void
107     _Rope_iterator_base<_CharT, _Alloc>::
108     _S_setcache(_Rope_iterator_base<_CharT, _Alloc>& __x)
109     {
110       using std::size_t;
111       const _RopeRep* __path[int(__detail::_S_max_rope_depth) + 1];
112       const _RopeRep* __curr_rope;
113       int __curr_depth = -1;  /* index into path    */
114       size_t __curr_start_pos = 0;
115       size_t __pos = __x._M_current_pos;
116       unsigned char __dirns = 0; // Bit vector marking right turns in the path
117 
118       if (__pos >= __x._M_root->_M_size)
119 	{
120 	  __x._M_buf_ptr = 0;
121 	  return;
122 	}
123       __curr_rope = __x._M_root;
124       if (0 != __curr_rope->_M_c_string)
125 	{
126 	  /* Treat the root as a leaf. */
127 	  __x._M_buf_start = __curr_rope->_M_c_string;
128 	  __x._M_buf_end = __curr_rope->_M_c_string + __curr_rope->_M_size;
129 	  __x._M_buf_ptr = __curr_rope->_M_c_string + __pos;
130 	  __x._M_path_end[0] = __curr_rope;
131 	  __x._M_leaf_index = 0;
132 	  __x._M_leaf_pos = 0;
133 	  return;
134 	}
135       for(;;)
136 	{
137 	  ++__curr_depth;
138 	  __path[__curr_depth] = __curr_rope;
139 	  switch(__curr_rope->_M_tag)
140 	    {
141 	    case __detail::_S_leaf:
142 	    case __detail::_S_function:
143 	    case __detail::_S_substringfn:
144 	      __x._M_leaf_pos = __curr_start_pos;
145 	      goto done;
146 	    case __detail::_S_concat:
147 	      {
148 		_Rope_RopeConcatenation<_CharT, _Alloc>* __c =
149 		  (_Rope_RopeConcatenation<_CharT, _Alloc>*)__curr_rope;
150 		_RopeRep* __left = __c->_M_left;
151 		size_t __left_len = __left->_M_size;
152 
153 		__dirns <<= 1;
154 		if (__pos >= __curr_start_pos + __left_len)
155 		  {
156 		    __dirns |= 1;
157 		    __curr_rope = __c->_M_right;
158 		    __curr_start_pos += __left_len;
159 		  }
160 		else
161 		  __curr_rope = __left;
162 	      }
163 	      break;
164 	    }
165 	}
166     done:
167       // Copy last section of path into _M_path_end.
168       {
169 	int __i = -1;
170 	int __j = __curr_depth + 1 - int(_S_path_cache_len);
171 
172 	if (__j < 0) __j = 0;
173 	while (__j <= __curr_depth)
174 	  __x._M_path_end[++__i] = __path[__j++];
175 	__x._M_leaf_index = __i;
176       }
177       __x._M_path_directions = __dirns;
178       _S_setbuf(__x);
179     }
180 
181   // Specialized version of the above.  Assumes that
182   // the path cache is valid for the previous position.
183   template <class _CharT, class _Alloc>
184     void
185     _Rope_iterator_base<_CharT, _Alloc>::
186     _S_setcache_for_incr(_Rope_iterator_base<_CharT, _Alloc>& __x)
187     {
188       using std::size_t;
189       int __current_index = __x._M_leaf_index;
190       const _RopeRep* __current_node = __x._M_path_end[__current_index];
191       size_t __len = __current_node->_M_size;
192       size_t __node_start_pos = __x._M_leaf_pos;
193       unsigned char __dirns = __x._M_path_directions;
194       _Rope_RopeConcatenation<_CharT, _Alloc>* __c;
195 
196       if (__x._M_current_pos - __node_start_pos < __len)
197 	{
198 	  /* More stuff in this leaf, we just didn't cache it. */
199 	  _S_setbuf(__x);
200 	  return;
201 	}
202       //  node_start_pos is starting position of last_node.
203       while (--__current_index >= 0)
204 	{
205 	  if (!(__dirns & 1) /* Path turned left */)
206 	    break;
207 	  __current_node = __x._M_path_end[__current_index];
208 	  __c = (_Rope_RopeConcatenation<_CharT, _Alloc>*)__current_node;
209 	  // Otherwise we were in the right child.  Thus we should pop
210 	  // the concatenation node.
211 	  __node_start_pos -= __c->_M_left->_M_size;
212 	  __dirns >>= 1;
213 	}
214       if (__current_index < 0)
215 	{
216 	  // We underflowed the cache. Punt.
217 	  _S_setcache(__x);
218 	  return;
219 	}
220       __current_node = __x._M_path_end[__current_index];
221       __c = (_Rope_RopeConcatenation<_CharT, _Alloc>*)__current_node;
222       // current_node is a concatenation node.  We are positioned on the first
223       // character in its right child.
224       // node_start_pos is starting position of current_node.
225       __node_start_pos += __c->_M_left->_M_size;
226       __current_node = __c->_M_right;
227       __x._M_path_end[++__current_index] = __current_node;
228       __dirns |= 1;
229       while (__detail::_S_concat == __current_node->_M_tag)
230 	{
231 	  ++__current_index;
232 	  if (int(_S_path_cache_len) == __current_index)
233 	    {
234 	      int __i;
235 	      for (__i = 0; __i < int(_S_path_cache_len) - 1; __i++)
236 		__x._M_path_end[__i] = __x._M_path_end[__i+1];
237 	      --__current_index;
238 	    }
239 	  __current_node =
240 	    ((_Rope_RopeConcatenation<_CharT, _Alloc>*)__current_node)->_M_left;
241 	  __x._M_path_end[__current_index] = __current_node;
242 	  __dirns <<= 1;
243 	  // node_start_pos is unchanged.
244 	}
245       __x._M_leaf_index = __current_index;
246       __x._M_leaf_pos = __node_start_pos;
247       __x._M_path_directions = __dirns;
248       _S_setbuf(__x);
249     }
250 
251   template <class _CharT, class _Alloc>
252     void
253     _Rope_iterator_base<_CharT, _Alloc>::
254     _M_incr(std::size_t __n)
255     {
256       _M_current_pos += __n;
257       if (0 != _M_buf_ptr)
258 	{
259 	  std::size_t __chars_left = _M_buf_end - _M_buf_ptr;
260 	  if (__chars_left > __n)
261 	    _M_buf_ptr += __n;
262 	  else if (__chars_left == __n)
263 	    {
264 	      _M_buf_ptr += __n;
265 	      _S_setcache_for_incr(*this);
266 	    }
267 	  else
268 	    _M_buf_ptr = 0;
269 	}
270     }
271 
272   template <class _CharT, class _Alloc>
273     void
274     _Rope_iterator_base<_CharT, _Alloc>::
275     _M_decr(std::size_t __n)
276     {
277       if (0 != _M_buf_ptr)
278 	{
279 	  std::size_t __chars_left = _M_buf_ptr - _M_buf_start;
280 	  if (__chars_left >= __n)
281 	    _M_buf_ptr -= __n;
282 	  else
283 	    _M_buf_ptr = 0;
284 	}
285       _M_current_pos -= __n;
286     }
287 
288   template <class _CharT, class _Alloc>
289     void
290     _Rope_iterator<_CharT, _Alloc>::
291     _M_check()
292     {
293       if (_M_root_rope->_M_tree_ptr != this->_M_root)
294 	{
295 	  // _Rope was modified.  Get things fixed up.
296 	  _RopeRep::_S_unref(this->_M_root);
297 	  this->_M_root = _M_root_rope->_M_tree_ptr;
298 	  _RopeRep::_S_ref(this->_M_root);
299 	  this->_M_buf_ptr = 0;
300 	}
301     }
302 
303   template <class _CharT, class _Alloc>
304     inline
305     _Rope_const_iterator<_CharT, _Alloc>::
306     _Rope_const_iterator(const _Rope_iterator<_CharT, _Alloc>& __x)
307     : _Rope_iterator_base<_CharT, _Alloc>(__x)
308     { }
309 
310   template <class _CharT, class _Alloc>
311     inline
312     _Rope_iterator<_CharT, _Alloc>::
313     _Rope_iterator(rope<_CharT, _Alloc>& __r, std::size_t __pos)
314     : _Rope_iterator_base<_CharT,_Alloc>(__r._M_tree_ptr, __pos),
315       _M_root_rope(&__r)
316     { _RopeRep::_S_ref(this->_M_root); }
317 
318   template <class _CharT, class _Alloc>
319     inline std::size_t
320     rope<_CharT, _Alloc>::
321     _S_char_ptr_len(const _CharT* __s)
322     {
323       const _CharT* __p = __s;
324 
325       while (!_S_is0(*__p))
326 	++__p;
327       return (__p - __s);
328     }
329 
330 
331 #ifndef __GC
332 
333   template <class _CharT, class _Alloc>
334     inline void
335     _Rope_RopeRep<_CharT, _Alloc>::
336     _M_free_c_string()
337     {
338       _CharT* __cstr = _M_c_string;
339       if (0 != __cstr)
340 	{
341 	  std::size_t __size = this->_M_size + 1;
342 	  std::_Destroy(__cstr, __cstr + __size, _M_get_allocator());
343 	  this->_Data_deallocate(__cstr, __size);
344 	}
345     }
346 
347   template <class _CharT, class _Alloc>
348     inline void
349     _Rope_RopeRep<_CharT, _Alloc>::
350     _S_free_string(_CharT* __s, std::size_t __n, allocator_type& __a)
351     {
352       if (!_S_is_basic_char_type((_CharT*)0))
353 	std::_Destroy(__s, __s + __n, __a);
354 
355       //  This has to be a static member, so this gets a bit messy
356       __a.deallocate(__s,
357 		     _Rope_RopeLeaf<_CharT, _Alloc>::_S_rounded_up_size(__n));
358     }
359 
360   //  There are several reasons for not doing this with virtual destructors
361   //  and a class specific delete operator:
362   //  - A class specific delete operator can't easily get access to
363   //    allocator instances if we need them.
364   //  - Any virtual function would need a 4 or byte vtable pointer;
365   //    this only requires a one byte tag per object.
366   template <class _CharT, class _Alloc>
367     void
368     _Rope_RopeRep<_CharT, _Alloc>::
369     _M_free_tree()
370     {
371       switch(_M_tag)
372 	{
373 	case __detail::_S_leaf:
374 	  {
375 	    _Rope_RopeLeaf<_CharT, _Alloc>* __l
376 	      = (_Rope_RopeLeaf<_CharT, _Alloc>*)this;
377 	    __l->_Rope_RopeLeaf<_CharT, _Alloc>::~_Rope_RopeLeaf();
378 	    this->_L_deallocate(__l, 1);
379 	    break;
380 	  }
381 	case __detail::_S_concat:
382 	  {
383 	    _Rope_RopeConcatenation<_CharT,_Alloc>* __c
384 	      = (_Rope_RopeConcatenation<_CharT, _Alloc>*)this;
385 	    __c->_Rope_RopeConcatenation<_CharT, _Alloc>::
386 	      ~_Rope_RopeConcatenation();
387 	    this->_C_deallocate(__c, 1);
388 	    break;
389 	  }
390 	case __detail::_S_function:
391 	  {
392 	    _Rope_RopeFunction<_CharT, _Alloc>* __f
393 	      = (_Rope_RopeFunction<_CharT, _Alloc>*)this;
394 	    __f->_Rope_RopeFunction<_CharT, _Alloc>::~_Rope_RopeFunction();
395 	    this->_F_deallocate(__f, 1);
396 	    break;
397 	  }
398 	case __detail::_S_substringfn:
399 	  {
400 	    _Rope_RopeSubstring<_CharT, _Alloc>* __ss =
401 	      (_Rope_RopeSubstring<_CharT, _Alloc>*)this;
402 	    __ss->_Rope_RopeSubstring<_CharT, _Alloc>::
403 	      ~_Rope_RopeSubstring();
404 	    this->_S_deallocate(__ss, 1);
405 	    break;
406 	  }
407 	}
408     }
409 #else
410 
411   template <class _CharT, class _Alloc>
412     inline void
413     _Rope_RopeRep<_CharT, _Alloc>::
414     _S_free_string(const _CharT*, std::size_t, allocator_type)
415     { }
416 
417 #endif
418 
419   // Concatenate a C string onto a leaf rope by copying the rope data.
420   // Used for short ropes.
421   template <class _CharT, class _Alloc>
422     typename rope<_CharT, _Alloc>::_RopeLeaf*
423     rope<_CharT, _Alloc>::
424     _S_leaf_concat_char_iter(_RopeLeaf* __r, const _CharT* __iter,
425 			     std::size_t __len)
426     {
427       std::size_t __old_len = __r->_M_size;
428       _CharT* __new_data = (_CharT*)
429 	rope::_Data_allocate(_S_rounded_up_size(__old_len + __len));
430       _RopeLeaf* __result;
431 
432       uninitialized_copy_n(__r->_M_data, __old_len, __new_data);
433       uninitialized_copy_n(__iter, __len, __new_data + __old_len);
434       _S_cond_store_eos(__new_data[__old_len + __len]);
435       __try
436 	{
437 	  __result = _S_new_RopeLeaf(__new_data, __old_len + __len,
438 				     __r->_M_get_allocator());
439 	}
440       __catch(...)
441 	{
442 	  _RopeRep::__STL_FREE_STRING(__new_data, __old_len + __len,
443 				      __r->_M_get_allocator());
444 	  __throw_exception_again;
445 	}
446       return __result;
447     }
448 
449 #ifndef __GC
450   // As above, but it's OK to clobber original if refcount is 1
451   template <class _CharT, class _Alloc>
452     typename rope<_CharT,_Alloc>::_RopeLeaf*
453     rope<_CharT, _Alloc>::
454     _S_destr_leaf_concat_char_iter(_RopeLeaf* __r, const _CharT* __iter,
455 				   std::size_t __len)
456     {
457       if (__r->_M_ref_count > 1)
458 	return _S_leaf_concat_char_iter(__r, __iter, __len);
459       std::size_t __old_len = __r->_M_size;
460       if (_S_allocated_capacity(__old_len) >= __old_len + __len)
461 	{
462 	  // The space has been partially initialized for the standard
463 	  // character types.  But that doesn't matter for those types.
464 	  uninitialized_copy_n(__iter, __len, __r->_M_data + __old_len);
465 	  if (_S_is_basic_char_type((_CharT*)0))
466 	    _S_cond_store_eos(__r->_M_data[__old_len + __len]);
467 	  else if (__r->_M_c_string != __r->_M_data && 0 != __r->_M_c_string)
468 	    {
469 	      __r->_M_free_c_string();
470 	      __r->_M_c_string = 0;
471 	    }
472 	  __r->_M_size = __old_len + __len;
473 	  __r->_M_ref_count = 2;
474 	  return __r;
475 	}
476       else
477 	{
478 	  _RopeLeaf* __result = _S_leaf_concat_char_iter(__r, __iter, __len);
479 	  return __result;
480 	}
481     }
482 #endif
483 
484   // Assumes left and right are not 0.
485   // Does not increment (nor decrement on exception) child reference counts.
486   // Result has ref count 1.
487   template <class _CharT, class _Alloc>
488     typename rope<_CharT, _Alloc>::_RopeRep*
489     rope<_CharT, _Alloc>::
490     _S_tree_concat(_RopeRep* __left, _RopeRep* __right)
491     {
492       using std::size_t;
493       _RopeConcatenation* __result = _S_new_RopeConcatenation(__left, __right,
494 							      __left->
495 							      _M_get_allocator());
496       size_t __depth = __result->_M_depth;
497 
498       if (__depth > 20
499 	  && (__result->_M_size < 1000
500 	      || __depth > size_t(__detail::_S_max_rope_depth)))
501 	{
502 	  _RopeRep* __balanced;
503 
504 	  __try
505 	    {
506 	      __balanced = _S_balance(__result);
507 	      __result->_M_unref_nonnil();
508 	    }
509 	  __catch(...)
510 	    {
511 	      rope::_C_deallocate(__result,1);
512 	      __throw_exception_again;
513 	    }
514 	  // In case of exception, we need to deallocate
515 	  // otherwise dangling result node.  But caller
516 	  // still owns its children.  Thus unref is
517 	  // inappropriate.
518 	  return __balanced;
519 	}
520       else
521 	return __result;
522     }
523 
524   template <class _CharT, class _Alloc>
525     typename rope<_CharT, _Alloc>::_RopeRep*
526     rope<_CharT, _Alloc>::
527     _S_concat_char_iter(_RopeRep* __r, const _CharT*__s, std::size_t __slen)
528     {
529       using std::size_t;
530       _RopeRep* __result;
531       if (0 == __slen)
532 	{
533 	  _S_ref(__r);
534 	  return __r;
535 	}
536       if (0 == __r)
537 	return __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __slen,
538 						__r->_M_get_allocator());
539       if (__r->_M_tag == __detail::_S_leaf
540 	  && __r->_M_size + __slen <= size_t(_S_copy_max))
541 	{
542 	  __result = _S_leaf_concat_char_iter((_RopeLeaf*)__r, __s, __slen);
543 	  return __result;
544 	}
545       if (__detail::_S_concat == __r->_M_tag
546 	  && __detail::_S_leaf == ((_RopeConcatenation*) __r)->_M_right->_M_tag)
547 	{
548 	  _RopeLeaf* __right =
549 	    (_RopeLeaf* )(((_RopeConcatenation* )__r)->_M_right);
550 	  if (__right->_M_size + __slen <= size_t(_S_copy_max))
551 	    {
552 	      _RopeRep* __left = ((_RopeConcatenation*)__r)->_M_left;
553 	      _RopeRep* __nright =
554 		_S_leaf_concat_char_iter((_RopeLeaf*)__right, __s, __slen);
555 	      __left->_M_ref_nonnil();
556 	      __try
557 		{ __result = _S_tree_concat(__left, __nright); }
558 	      __catch(...)
559 		{
560 		  _S_unref(__left);
561 		  _S_unref(__nright);
562 		  __throw_exception_again;
563 		}
564 	      return __result;
565 	    }
566 	}
567       _RopeRep* __nright =
568 	__STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __slen, __r->_M_get_allocator());
569       __try
570 	{
571 	  __r->_M_ref_nonnil();
572 	  __result = _S_tree_concat(__r, __nright);
573 	}
574       __catch(...)
575 	{
576 	  _S_unref(__r);
577 	  _S_unref(__nright);
578 	  __throw_exception_again;
579 	}
580       return __result;
581     }
582 
583 #ifndef __GC
584   template <class _CharT, class _Alloc>
585     typename rope<_CharT,_Alloc>::_RopeRep*
586     rope<_CharT,_Alloc>::
587     _S_destr_concat_char_iter(_RopeRep* __r, const _CharT* __s,
588 			      std::size_t __slen)
589     {
590       using std::size_t;
591       _RopeRep* __result;
592       if (0 == __r)
593 	return __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __slen,
594 						__r->_M_get_allocator());
595       size_t __count = __r->_M_ref_count;
596       size_t __orig_size = __r->_M_size;
597       if (__count > 1)
598 	return _S_concat_char_iter(__r, __s, __slen);
599       if (0 == __slen)
600 	{
601 	  __r->_M_ref_count = 2;      // One more than before
602 	  return __r;
603 	}
604       if (__orig_size + __slen <= size_t(_S_copy_max)
605 	  && __detail::_S_leaf == __r->_M_tag)
606 	{
607 	  __result = _S_destr_leaf_concat_char_iter((_RopeLeaf*)__r, __s,
608 						    __slen);
609 	  return __result;
610 	}
611       if (__detail::_S_concat == __r->_M_tag)
612 	{
613 	  _RopeLeaf* __right = (_RopeLeaf*)(((_RopeConcatenation*)
614 					     __r)->_M_right);
615 	  if (__detail::_S_leaf == __right->_M_tag
616 	      && __right->_M_size + __slen <= size_t(_S_copy_max))
617 	    {
618 	      _RopeRep* __new_right =
619 		_S_destr_leaf_concat_char_iter(__right, __s, __slen);
620 	      if (__right == __new_right)
621 		__new_right->_M_ref_count = 1;
622 	      else
623 		__right->_M_unref_nonnil();
624 	      __r->_M_ref_count = 2;    // One more than before.
625 	      ((_RopeConcatenation*)__r)->_M_right = __new_right;
626 	      __r->_M_size = __orig_size + __slen;
627 	      if (0 != __r->_M_c_string)
628 		{
629 		  __r->_M_free_c_string();
630 		  __r->_M_c_string = 0;
631 		}
632 	      return __r;
633 	    }
634 	}
635       _RopeRep* __right =
636 	__STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __slen, __r->_M_get_allocator());
637       __r->_M_ref_nonnil();
638       __try
639 	{ __result = _S_tree_concat(__r, __right); }
640       __catch(...)
641 	{
642 	  _S_unref(__r);
643 	  _S_unref(__right);
644 	  __throw_exception_again;
645 	}
646       return __result;
647     }
648 #endif /* !__GC */
649 
650   template <class _CharT, class _Alloc>
651     typename rope<_CharT, _Alloc>::_RopeRep*
652     rope<_CharT, _Alloc>::
653     _S_concat(_RopeRep* __left, _RopeRep* __right)
654     {
655       using std::size_t;
656       if (0 == __left)
657 	{
658 	  _S_ref(__right);
659 	  return __right;
660 	}
661       if (0 == __right)
662 	{
663 	  __left->_M_ref_nonnil();
664 	  return __left;
665 	}
666       if (__detail::_S_leaf == __right->_M_tag)
667 	{
668 	  if (__detail::_S_leaf == __left->_M_tag)
669 	    {
670 	      if (__right->_M_size + __left->_M_size <= size_t(_S_copy_max))
671 		return _S_leaf_concat_char_iter((_RopeLeaf*)__left,
672 						((_RopeLeaf*)__right)->_M_data,
673 						__right->_M_size);
674 	    }
675 	  else if (__detail::_S_concat == __left->_M_tag
676 		   && __detail::_S_leaf == ((_RopeConcatenation*)
677 						   __left)->_M_right->_M_tag)
678 	    {
679 	      _RopeLeaf* __leftright =
680 		(_RopeLeaf*)(((_RopeConcatenation*)__left)->_M_right);
681 	      if (__leftright->_M_size
682 		  + __right->_M_size <= size_t(_S_copy_max))
683 		{
684 		  _RopeRep* __leftleft = ((_RopeConcatenation*)__left)->_M_left;
685 		  _RopeRep* __rest = _S_leaf_concat_char_iter(__leftright,
686 							      ((_RopeLeaf*)
687 							       __right)->
688 							      _M_data,
689 							      __right->_M_size);
690 		  __leftleft->_M_ref_nonnil();
691 		  __try
692 		    { return(_S_tree_concat(__leftleft, __rest)); }
693 		  __catch(...)
694 		    {
695 		      _S_unref(__leftleft);
696 		      _S_unref(__rest);
697 		      __throw_exception_again;
698 		    }
699 		}
700 	    }
701 	}
702       __left->_M_ref_nonnil();
703       __right->_M_ref_nonnil();
704       __try
705 	{ return(_S_tree_concat(__left, __right)); }
706       __catch(...)
707 	{
708 	  _S_unref(__left);
709 	  _S_unref(__right);
710 	  __throw_exception_again;
711 	}
712     }
713 
714   template <class _CharT, class _Alloc>
715     typename rope<_CharT, _Alloc>::_RopeRep*
716     rope<_CharT, _Alloc>::
717     _S_substring(_RopeRep* __base, std::size_t __start, std::size_t __endp1)
718     {
719       using std::size_t;
720       if (0 == __base)
721 	return 0;
722       size_t __len = __base->_M_size;
723       size_t __adj_endp1;
724       const size_t __lazy_threshold = 128;
725 
726       if (__endp1 >= __len)
727 	{
728 	  if (0 == __start)
729 	    {
730 	      __base->_M_ref_nonnil();
731 	      return __base;
732 	    }
733 	  else
734 	    __adj_endp1 = __len;
735 
736 	}
737       else
738 	__adj_endp1 = __endp1;
739 
740       switch(__base->_M_tag)
741 	{
742 	case __detail::_S_concat:
743 	    {
744 	      _RopeConcatenation* __c = (_RopeConcatenation*)__base;
745 	      _RopeRep* __left = __c->_M_left;
746 	      _RopeRep* __right = __c->_M_right;
747 	      size_t __left_len = __left->_M_size;
748 	      _RopeRep* __result;
749 
750 	      if (__adj_endp1 <= __left_len)
751 		return _S_substring(__left, __start, __endp1);
752 	      else if (__start >= __left_len)
753 		return _S_substring(__right, __start - __left_len,
754 				    __adj_endp1 - __left_len);
755 	      _Self_destruct_ptr __left_result(_S_substring(__left,
756 							    __start,
757 							    __left_len));
758 	      _Self_destruct_ptr __right_result(_S_substring(__right, 0,
759 							     __endp1
760 							     - __left_len));
761 	      __result = _S_concat(__left_result, __right_result);
762 	      return __result;
763 	    }
764 	case __detail::_S_leaf:
765 	  {
766 	    _RopeLeaf* __l = (_RopeLeaf*)__base;
767 	    _RopeLeaf* __result;
768 	    size_t __result_len;
769 	    if (__start >= __adj_endp1)
770 	      return 0;
771 	    __result_len = __adj_endp1 - __start;
772 	    if (__result_len > __lazy_threshold)
773 	      goto lazy;
774 #ifdef __GC
775 	    const _CharT* __section = __l->_M_data + __start;
776 	    __result = _S_new_RopeLeaf(__section, __result_len,
777 				       __base->_M_get_allocator());
778 	    __result->_M_c_string = 0;  // Not eos terminated.
779 #else
780 	    // We should sometimes create substring node instead.
781 	    __result = __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__l->_M_data + __start,
782 							__result_len,
783 							__base->
784 							_M_get_allocator());
785 #endif
786 	    return __result;
787 	  }
788 	case __detail::_S_substringfn:
789 	  // Avoid introducing multiple layers of substring nodes.
790 	  {
791 	    _RopeSubstring* __old = (_RopeSubstring*)__base;
792 	    size_t __result_len;
793 	    if (__start >= __adj_endp1)
794 	      return 0;
795 	    __result_len = __adj_endp1 - __start;
796 	    if (__result_len > __lazy_threshold)
797 	      {
798 		_RopeSubstring* __result =
799 		  _S_new_RopeSubstring(__old->_M_base,
800 				       __start + __old->_M_start,
801 				       __adj_endp1 - __start,
802 				       __base->_M_get_allocator());
803 		return __result;
804 
805 	      } // *** else fall through: ***
806 	  }
807 	case __detail::_S_function:
808 	  {
809 	    _RopeFunction* __f = (_RopeFunction*)__base;
810 	    _CharT* __section;
811 	    size_t __result_len;
812 	    if (__start >= __adj_endp1)
813 	      return 0;
814 	    __result_len = __adj_endp1 - __start;
815 
816 	    if (__result_len > __lazy_threshold)
817 	      goto lazy;
818 	    __section = (_CharT*)
819 	      rope::_Data_allocate(_S_rounded_up_size(__result_len));
820 	    __try
821 	      {	(*(__f->_M_fn))(__start, __result_len, __section); }
822 	    __catch(...)
823 	      {
824 		_RopeRep::__STL_FREE_STRING(__section, __result_len,
825 					    __base->_M_get_allocator());
826 		__throw_exception_again;
827 	      }
828 	    _S_cond_store_eos(__section[__result_len]);
829 	    return _S_new_RopeLeaf(__section, __result_len,
830 				   __base->_M_get_allocator());
831 	  }
832 	}
833     lazy:
834       {
835 	// Create substring node.
836 	return _S_new_RopeSubstring(__base, __start, __adj_endp1 - __start,
837 				    __base->_M_get_allocator());
838       }
839     }
840 
841   template<class _CharT>
842     class _Rope_flatten_char_consumer
843     : public _Rope_char_consumer<_CharT>
844     {
845     private:
846       _CharT* _M_buf_ptr;
847     public:
848 
849       _Rope_flatten_char_consumer(_CharT* __buffer)
850       { _M_buf_ptr = __buffer; }
851 
852       ~_Rope_flatten_char_consumer() {}
853 
854       bool
855       operator()(const _CharT* __leaf, std::size_t __n)
856       {
857 	uninitialized_copy_n(__leaf, __n, _M_buf_ptr);
858 	_M_buf_ptr += __n;
859 	return true;
860       }
861     };
862 
863   template<class _CharT>
864     class _Rope_find_char_char_consumer
865     : public _Rope_char_consumer<_CharT>
866     {
867     private:
868       _CharT _M_pattern;
869     public:
870       std::size_t _M_count;  // Number of nonmatching characters
871 
872       _Rope_find_char_char_consumer(_CharT __p)
873       : _M_pattern(__p), _M_count(0) {}
874 
875       ~_Rope_find_char_char_consumer() {}
876 
877       bool
878       operator()(const _CharT* __leaf, std::size_t __n)
879       {
880 	std::size_t __i;
881 	for (__i = 0; __i < __n; __i++)
882 	  {
883 	    if (__leaf[__i] == _M_pattern)
884 	      {
885 		_M_count += __i;
886 		return false;
887 	      }
888 	  }
889 	_M_count += __n; return true;
890       }
891     };
892 
893   template<class _CharT, class _Traits>
894   // Here _CharT is both the stream and rope character type.
895     class _Rope_insert_char_consumer
896     : public _Rope_char_consumer<_CharT>
897     {
898     private:
899       typedef std::basic_ostream<_CharT,_Traits> _Insert_ostream;
900       _Insert_ostream& _M_o;
901     public:
902       _Rope_insert_char_consumer(_Insert_ostream& __writer)
903 	: _M_o(__writer) {}
904       ~_Rope_insert_char_consumer() { }
905       // Caller is presumed to own the ostream
906       bool operator() (const _CharT* __leaf, std::size_t __n);
907       // Returns true to continue traversal.
908     };
909 
910   template<class _CharT, class _Traits>
911     bool
912     _Rope_insert_char_consumer<_CharT, _Traits>::
913     operator()(const _CharT* __leaf, std::size_t __n)
914     {
915       std::size_t __i;
916       //  We assume that formatting is set up correctly for each element.
917       for (__i = 0; __i < __n; __i++)
918 	_M_o.put(__leaf[__i]);
919       return true;
920     }
921 
922   template <class _CharT, class _Alloc>
923     bool
924     rope<_CharT, _Alloc>::
925     _S_apply_to_pieces(_Rope_char_consumer<_CharT>& __c, const _RopeRep* __r,
926 		       std::size_t __begin, std::size_t __end)
927     {
928       using std::size_t;
929       if (0 == __r)
930 	return true;
931       switch(__r->_M_tag)
932 	{
933 	case __detail::_S_concat:
934 	  {
935 	    _RopeConcatenation* __conc = (_RopeConcatenation*)__r;
936 	    _RopeRep* __left =  __conc->_M_left;
937 	    size_t __left_len = __left->_M_size;
938 	    if (__begin < __left_len)
939 	      {
940 		size_t __left_end = std::min(__left_len, __end);
941 		if (!_S_apply_to_pieces(__c, __left, __begin, __left_end))
942 		  return false;
943 	      }
944 	    if (__end > __left_len)
945 	      {
946 		_RopeRep* __right =  __conc->_M_right;
947 		size_t __right_start = std::max(__left_len, __begin);
948 		if (!_S_apply_to_pieces(__c, __right,
949 					__right_start - __left_len,
950 					__end - __left_len))
951 		  return false;
952 	      }
953 	  }
954 	  return true;
955 	case __detail::_S_leaf:
956 	  {
957 	    _RopeLeaf* __l = (_RopeLeaf*)__r;
958 	    return __c(__l->_M_data + __begin, __end - __begin);
959 	  }
960 	case __detail::_S_function:
961 	case __detail::_S_substringfn:
962 	    {
963 	      _RopeFunction* __f = (_RopeFunction*)__r;
964 	      size_t __len = __end - __begin;
965 	      bool __result;
966 	      _CharT* __buffer =
967 		(_CharT*)_Alloc().allocate(__len * sizeof(_CharT));
968 	      __try
969 		{
970 		  (*(__f->_M_fn))(__begin, __len, __buffer);
971 		  __result = __c(__buffer, __len);
972                   _Alloc().deallocate(__buffer, __len * sizeof(_CharT));
973                 }
974 	      __catch(...)
975 		{
976 		  _Alloc().deallocate(__buffer, __len * sizeof(_CharT));
977 		  __throw_exception_again;
978 		}
979 	      return __result;
980 	    }
981 	default:
982 	  return false;
983 	}
984     }
985 
986   template<class _CharT, class _Traits>
987     inline void
988     _Rope_fill(std::basic_ostream<_CharT, _Traits>& __o, std::size_t __n)
989     {
990       char __f = __o.fill();
991       std::size_t __i;
992 
993       for (__i = 0; __i < __n; __i++)
994 	__o.put(__f);
995     }
996 
997 
998   template <class _CharT>
999     inline bool
1000     _Rope_is_simple(_CharT*)
1001     { return false; }
1002 
1003   inline bool
1004   _Rope_is_simple(char*)
1005   { return true; }
1006 
1007   inline bool
1008   _Rope_is_simple(wchar_t*)
1009   { return true; }
1010 
1011   template<class _CharT, class _Traits, class _Alloc>
1012     std::basic_ostream<_CharT, _Traits>&
1013     operator<<(std::basic_ostream<_CharT, _Traits>& __o,
1014 	       const rope<_CharT, _Alloc>& __r)
1015     {
1016       using std::size_t;
1017       size_t __w = __o.width();
1018       bool __left = bool(__o.flags() & std::ios::left);
1019       size_t __pad_len;
1020       size_t __rope_len = __r.size();
1021       _Rope_insert_char_consumer<_CharT, _Traits> __c(__o);
1022       bool __is_simple = _Rope_is_simple((_CharT*)0);
1023 
1024       if (__rope_len < __w)
1025 	__pad_len = __w - __rope_len;
1026       else
1027 	__pad_len = 0;
1028 
1029       if (!__is_simple)
1030 	__o.width(__w / __rope_len);
1031       __try
1032 	{
1033 	  if (__is_simple && !__left && __pad_len > 0)
1034 	    _Rope_fill(__o, __pad_len);
1035 	  __r.apply_to_pieces(0, __r.size(), __c);
1036 	  if (__is_simple && __left && __pad_len > 0)
1037 	    _Rope_fill(__o, __pad_len);
1038 	  if (!__is_simple)
1039 	    __o.width(__w);
1040 	}
1041       __catch(...)
1042 	{
1043 	  if (!__is_simple)
1044 	    __o.width(__w);
1045 	  __throw_exception_again;
1046 	}
1047       return __o;
1048     }
1049 
1050   template <class _CharT, class _Alloc>
1051     _CharT*
1052     rope<_CharT, _Alloc>::
1053     _S_flatten(_RopeRep* __r, std::size_t __start, std::size_t __len,
1054 	       _CharT* __buffer)
1055     {
1056       _Rope_flatten_char_consumer<_CharT> __c(__buffer);
1057       _S_apply_to_pieces(__c, __r, __start, __start + __len);
1058       return(__buffer + __len);
1059     }
1060 
1061   template <class _CharT, class _Alloc>
1062     std::size_t
1063     rope<_CharT, _Alloc>::
1064     find(_CharT __pattern, std::size_t __start) const
1065     {
1066       _Rope_find_char_char_consumer<_CharT> __c(__pattern);
1067       _S_apply_to_pieces(__c, this->_M_tree_ptr, __start, size());
1068       size_type __result_pos = __start + __c._M_count;
1069 #ifndef __STL_OLD_ROPE_SEMANTICS
1070       if (__result_pos == size())
1071 	__result_pos = npos;
1072 #endif
1073       return __result_pos;
1074     }
1075 
1076   template <class _CharT, class _Alloc>
1077     _CharT*
1078     rope<_CharT, _Alloc>::
1079     _S_flatten(_RopeRep* __r, _CharT* __buffer)
1080     {
1081       if (0 == __r)
1082 	return __buffer;
1083       switch(__r->_M_tag)
1084 	{
1085 	case __detail::_S_concat:
1086 	  {
1087 	    _RopeConcatenation* __c = (_RopeConcatenation*)__r;
1088 	    _RopeRep* __left = __c->_M_left;
1089 	    _RopeRep* __right = __c->_M_right;
1090 	    _CharT* __rest = _S_flatten(__left, __buffer);
1091 	    return _S_flatten(__right, __rest);
1092 	  }
1093 	case __detail::_S_leaf:
1094 	  {
1095 	    _RopeLeaf* __l = (_RopeLeaf*)__r;
1096 	    return copy_n(__l->_M_data, __l->_M_size, __buffer).second;
1097 	  }
1098 	case __detail::_S_function:
1099 	case __detail::_S_substringfn:
1100 	  // We don't yet do anything with substring nodes.
1101 	  // This needs to be fixed before ropefiles will work well.
1102 	  {
1103 	    _RopeFunction* __f = (_RopeFunction*)__r;
1104 	    (*(__f->_M_fn))(0, __f->_M_size, __buffer);
1105 	    return __buffer + __f->_M_size;
1106 	  }
1107 	default:
1108 	  return 0;
1109 	}
1110     }
1111 
1112   // This needs work for _CharT != char
1113   template <class _CharT, class _Alloc>
1114     void
1115     rope<_CharT, _Alloc>::
1116     _S_dump(_RopeRep* __r, int __indent)
1117     {
1118       using std::printf;
1119       for (int __i = 0; __i < __indent; __i++)
1120 	putchar(' ');
1121       if (0 == __r)
1122 	{
1123 	  printf("NULL\n");
1124 	  return;
1125 	}
1126       if (__detail::_S_concat == __r->_M_tag)
1127 	{
1128 	  _RopeConcatenation* __c = (_RopeConcatenation*)__r;
1129 	  _RopeRep* __left = __c->_M_left;
1130 	  _RopeRep* __right = __c->_M_right;
1131 
1132 #ifdef __GC
1133 	  printf("Concatenation %p (depth = %d, len = %ld, %s balanced)\n",
1134 		 __r, __r->_M_depth, __r->_M_size,
1135 		 __r->_M_is_balanced? "" : "not");
1136 #else
1137 	  printf("Concatenation %p (rc = %ld, depth = %d, "
1138 		 "len = %ld, %s balanced)\n",
1139 		 __r, __r->_M_ref_count, __r->_M_depth, __r->_M_size,
1140 		 __r->_M_is_balanced? "" : "not");
1141 #endif
1142 	  _S_dump(__left, __indent + 2);
1143 	  _S_dump(__right, __indent + 2);
1144 	  return;
1145 	}
1146       else
1147 	{
1148 	  const char* __kind;
1149 
1150 	  switch (__r->_M_tag)
1151 	    {
1152 	    case __detail::_S_leaf:
1153 	      __kind = "Leaf";
1154 	      break;
1155 	    case __detail::_S_function:
1156 	      __kind = "Function";
1157 	      break;
1158 	    case __detail::_S_substringfn:
1159 	      __kind = "Function representing substring";
1160 	      break;
1161 	    default:
1162 	      __kind = "(corrupted kind field!)";
1163 	    }
1164 #ifdef __GC
1165 	  printf("%s %p (depth = %d, len = %ld) ",
1166 		 __kind, __r, __r->_M_depth, __r->_M_size);
1167 #else
1168 	  printf("%s %p (rc = %ld, depth = %d, len = %ld) ",
1169 		 __kind, __r, __r->_M_ref_count, __r->_M_depth, __r->_M_size);
1170 #endif
1171 	  if (_S_is_one_byte_char_type((_CharT*)0))
1172 	    {
1173 	      const int __max_len = 40;
1174 	      _Self_destruct_ptr __prefix(_S_substring(__r, 0, __max_len));
1175 	      _CharT __buffer[__max_len + 1];
1176 	      bool __too_big = __r->_M_size > __prefix->_M_size;
1177 
1178 	      _S_flatten(__prefix, __buffer);
1179 	      __buffer[__prefix->_M_size] = _S_eos((_CharT*)0);
1180 	      printf("%s%s\n", (char*)__buffer,
1181 		     __too_big? "...\n" : "\n");
1182 	    }
1183 	  else
1184 	    printf("\n");
1185 	}
1186     }
1187 
1188   template <class _CharT, class _Alloc>
1189     const unsigned long
1190     rope<_CharT, _Alloc>::
1191     _S_min_len[int(__detail::_S_max_rope_depth) + 1] = {
1192       /* 0 */1, /* 1 */2, /* 2 */3, /* 3 */5, /* 4 */8, /* 5 */13, /* 6 */21,
1193       /* 7 */34, /* 8 */55, /* 9 */89, /* 10 */144, /* 11 */233, /* 12 */377,
1194       /* 13 */610, /* 14 */987, /* 15 */1597, /* 16 */2584, /* 17 */4181,
1195       /* 18 */6765, /* 19 */10946, /* 20 */17711, /* 21 */28657, /* 22 */46368,
1196       /* 23 */75025, /* 24 */121393, /* 25 */196418, /* 26 */317811,
1197       /* 27 */514229, /* 28 */832040, /* 29 */1346269, /* 30 */2178309,
1198       /* 31 */3524578, /* 32 */5702887, /* 33 */9227465, /* 34 */14930352,
1199       /* 35 */24157817, /* 36 */39088169, /* 37 */63245986, /* 38 */102334155,
1200       /* 39 */165580141, /* 40 */267914296, /* 41 */433494437,
1201       /* 42 */701408733, /* 43 */1134903170, /* 44 */1836311903,
1202       /* 45 */2971215073u };
1203   // These are Fibonacci numbers < 2**32.
1204 
1205   template <class _CharT, class _Alloc>
1206     typename rope<_CharT, _Alloc>::_RopeRep*
1207     rope<_CharT, _Alloc>::
1208     _S_balance(_RopeRep* __r)
1209     {
1210       _RopeRep* __forest[int(__detail::_S_max_rope_depth) + 1];
1211       _RopeRep* __result = 0;
1212       int __i;
1213       // Invariant:
1214       // The concatenation of forest in descending order is equal to __r.
1215       // __forest[__i]._M_size >= _S_min_len[__i]
1216       // __forest[__i]._M_depth = __i
1217       // References from forest are included in refcount.
1218 
1219       for (__i = 0; __i <= int(__detail::_S_max_rope_depth); ++__i)
1220 	__forest[__i] = 0;
1221       __try
1222 	{
1223 	  _S_add_to_forest(__r, __forest);
1224 	  for (__i = 0; __i <= int(__detail::_S_max_rope_depth); ++__i)
1225 	    if (0 != __forest[__i])
1226 	      {
1227 #ifndef __GC
1228 		_Self_destruct_ptr __old(__result);
1229 #endif
1230 		__result = _S_concat(__forest[__i], __result);
1231 		__forest[__i]->_M_unref_nonnil();
1232 #if !defined(__GC) && __cpp_exceptions
1233 		__forest[__i] = 0;
1234 #endif
1235 	      }
1236 	}
1237       __catch(...)
1238 	{
1239 	  for(__i = 0; __i <= int(__detail::_S_max_rope_depth); __i++)
1240 	    _S_unref(__forest[__i]);
1241 	  __throw_exception_again;
1242 	}
1243 
1244       if (__result->_M_depth > int(__detail::_S_max_rope_depth))
1245 	std::__throw_length_error(__N("rope::_S_balance"));
1246       return(__result);
1247     }
1248 
1249   template <class _CharT, class _Alloc>
1250     void
1251     rope<_CharT, _Alloc>::
1252     _S_add_to_forest(_RopeRep* __r, _RopeRep** __forest)
1253     {
1254       if (__r->_M_is_balanced)
1255 	{
1256 	  _S_add_leaf_to_forest(__r, __forest);
1257 	  return;
1258 	}
1259 
1260       {
1261 	_RopeConcatenation* __c = (_RopeConcatenation*)__r;
1262 
1263 	_S_add_to_forest(__c->_M_left, __forest);
1264 	_S_add_to_forest(__c->_M_right, __forest);
1265       }
1266     }
1267 
1268 
1269   template <class _CharT, class _Alloc>
1270     void
1271     rope<_CharT, _Alloc>::
1272     _S_add_leaf_to_forest(_RopeRep* __r, _RopeRep** __forest)
1273     {
1274       _RopeRep* __insertee;		// included in refcount
1275       _RopeRep* __too_tiny = 0;		// included in refcount
1276       int __i;				// forest[0..__i-1] is empty
1277       std::size_t __s = __r->_M_size;
1278 
1279       for (__i = 0; __s >= _S_min_len[__i+1]/* not this bucket */; ++__i)
1280 	{
1281 	  if (0 != __forest[__i])
1282 	    {
1283 #ifndef __GC
1284 	      _Self_destruct_ptr __old(__too_tiny);
1285 #endif
1286 	      __too_tiny = _S_concat_and_set_balanced(__forest[__i],
1287 						      __too_tiny);
1288 	      __forest[__i]->_M_unref_nonnil();
1289 	      __forest[__i] = 0;
1290 	    }
1291 	}
1292       {
1293 #ifndef __GC
1294 	_Self_destruct_ptr __old(__too_tiny);
1295 #endif
1296 	__insertee = _S_concat_and_set_balanced(__too_tiny, __r);
1297       }
1298       // Too_tiny dead, and no longer included in refcount.
1299       // Insertee is live and included.
1300       for (;; ++__i)
1301 	{
1302 	  if (0 != __forest[__i])
1303 	    {
1304 #ifndef __GC
1305 	      _Self_destruct_ptr __old(__insertee);
1306 #endif
1307 	      __insertee = _S_concat_and_set_balanced(__forest[__i],
1308 						      __insertee);
1309 	      __forest[__i]->_M_unref_nonnil();
1310 	      __forest[__i] = 0;
1311 	    }
1312 	  if (__i == int(__detail::_S_max_rope_depth)
1313 	      || __insertee->_M_size < _S_min_len[__i+1])
1314 	    {
1315 	      __forest[__i] = __insertee;
1316 	      // refcount is OK since __insertee is now dead.
1317 	      return;
1318 	    }
1319 	}
1320     }
1321 
1322   template <class _CharT, class _Alloc>
1323     _CharT
1324     rope<_CharT, _Alloc>::
1325     _S_fetch(_RopeRep* __r, size_type __i)
1326     {
1327       __GC_CONST _CharT* __cstr = __r->_M_c_string;
1328 
1329       if (0 != __cstr)
1330 	return __cstr[__i];
1331       for(;;)
1332 	{
1333 	  switch(__r->_M_tag)
1334 	    {
1335 	    case __detail::_S_concat:
1336 	      {
1337 		_RopeConcatenation* __c = (_RopeConcatenation*)__r;
1338 		_RopeRep* __left = __c->_M_left;
1339 		std::size_t __left_len = __left->_M_size;
1340 
1341 		if (__i >= __left_len)
1342 		  {
1343 		    __i -= __left_len;
1344 		    __r = __c->_M_right;
1345 		  }
1346 		else
1347 		  __r = __left;
1348 	      }
1349 	      break;
1350 	    case __detail::_S_leaf:
1351 	      {
1352 		_RopeLeaf* __l = (_RopeLeaf*)__r;
1353 		return __l->_M_data[__i];
1354 	      }
1355 	    case __detail::_S_function:
1356 	    case __detail::_S_substringfn:
1357 	      {
1358 		_RopeFunction* __f = (_RopeFunction*)__r;
1359 		_CharT __result;
1360 
1361 		(*(__f->_M_fn))(__i, 1, &__result);
1362 		return __result;
1363 	      }
1364 	    }
1365 	}
1366     }
1367 
1368 #ifndef __GC
1369   // Return a uniquely referenced character slot for the given
1370   // position, or 0 if that's not possible.
1371   template <class _CharT, class _Alloc>
1372     _CharT*
1373     rope<_CharT, _Alloc>::
1374     _S_fetch_ptr(_RopeRep* __r, size_type __i)
1375     {
1376       _RopeRep* __clrstack[__detail::_S_max_rope_depth];
1377       std::size_t __csptr = 0;
1378 
1379       for(;;)
1380 	{
1381 	  if (__r->_M_ref_count > 1)
1382 	    return 0;
1383 	  switch(__r->_M_tag)
1384 	    {
1385 	    case __detail::_S_concat:
1386 	      {
1387 		_RopeConcatenation* __c = (_RopeConcatenation*)__r;
1388 		_RopeRep* __left = __c->_M_left;
1389 		std::size_t __left_len = __left->_M_size;
1390 
1391 		if (__c->_M_c_string != 0)
1392 		  __clrstack[__csptr++] = __c;
1393 		if (__i >= __left_len)
1394 		  {
1395 		    __i -= __left_len;
1396 		    __r = __c->_M_right;
1397 		  }
1398 		else
1399 		  __r = __left;
1400 	      }
1401 	      break;
1402 	    case __detail::_S_leaf:
1403 	      {
1404 		_RopeLeaf* __l = (_RopeLeaf*)__r;
1405 		if (__l->_M_c_string != __l->_M_data && __l->_M_c_string != 0)
1406 		  __clrstack[__csptr++] = __l;
1407 		while (__csptr > 0)
1408 		  {
1409 		    -- __csptr;
1410 		    _RopeRep* __d = __clrstack[__csptr];
1411 		    __d->_M_free_c_string();
1412 		    __d->_M_c_string = 0;
1413 		  }
1414 		return __l->_M_data + __i;
1415 	      }
1416 	    case __detail::_S_function:
1417 	    case __detail::_S_substringfn:
1418 	      return 0;
1419 	    }
1420 	}
1421     }
1422 #endif /* __GC */
1423 
1424   // The following could be implemented trivially using
1425   // lexicographical_compare_3way.
1426   // We do a little more work to avoid dealing with rope iterators for
1427   // flat strings.
1428   template <class _CharT, class _Alloc>
1429     int
1430     rope<_CharT, _Alloc>::
1431     _S_compare (const _RopeRep* __left, const _RopeRep* __right)
1432     {
1433       std::size_t __left_len;
1434       std::size_t __right_len;
1435 
1436       if (0 == __right)
1437 	return 0 != __left;
1438       if (0 == __left)
1439 	return -1;
1440       __left_len = __left->_M_size;
1441       __right_len = __right->_M_size;
1442       if (__detail::_S_leaf == __left->_M_tag)
1443 	{
1444 	  _RopeLeaf* __l = (_RopeLeaf*) __left;
1445 	  if (__detail::_S_leaf == __right->_M_tag)
1446 	    {
1447 	      _RopeLeaf* __r = (_RopeLeaf*) __right;
1448 	      return lexicographical_compare_3way(__l->_M_data,
1449 						  __l->_M_data + __left_len,
1450 						  __r->_M_data, __r->_M_data
1451 						  + __right_len);
1452 	    }
1453 	  else
1454 	    {
1455 	      const_iterator __rstart(__right, 0);
1456 	      const_iterator __rend(__right, __right_len);
1457 	      return lexicographical_compare_3way(__l->_M_data, __l->_M_data
1458 						  + __left_len,
1459 						  __rstart, __rend);
1460 	    }
1461 	}
1462       else
1463 	{
1464 	  const_iterator __lstart(__left, 0);
1465 	  const_iterator __lend(__left, __left_len);
1466 	  if (__detail::_S_leaf == __right->_M_tag)
1467 	    {
1468 	      _RopeLeaf* __r = (_RopeLeaf*) __right;
1469 	      return lexicographical_compare_3way(__lstart, __lend,
1470 						  __r->_M_data, __r->_M_data
1471 						  + __right_len);
1472 	    }
1473 	  else
1474 	    {
1475 	      const_iterator __rstart(__right, 0);
1476 	      const_iterator __rend(__right, __right_len);
1477 	      return lexicographical_compare_3way(__lstart, __lend,
1478 						  __rstart, __rend);
1479 	    }
1480 	}
1481     }
1482 
1483   // Assignment to reference proxies.
1484   template <class _CharT, class _Alloc>
1485     _Rope_char_ref_proxy<_CharT, _Alloc>&
1486     _Rope_char_ref_proxy<_CharT, _Alloc>::
1487     operator=(_CharT __c)
1488     {
1489       _RopeRep* __old = _M_root->_M_tree_ptr;
1490 #ifndef __GC
1491       // First check for the case in which everything is uniquely
1492       // referenced.  In that case we can do this destructively.
1493       _CharT* __ptr = _My_rope::_S_fetch_ptr(__old, _M_pos);
1494       if (0 != __ptr)
1495 	{
1496 	  *__ptr = __c;
1497 	  return *this;
1498 	}
1499 #endif
1500       _Self_destruct_ptr __left(_My_rope::_S_substring(__old, 0, _M_pos));
1501       _Self_destruct_ptr __right(_My_rope::_S_substring(__old, _M_pos + 1,
1502 							__old->_M_size));
1503       _Self_destruct_ptr __result_left(_My_rope::
1504 				       _S_destr_concat_char_iter(__left,
1505 								 &__c, 1));
1506 
1507       _RopeRep* __result = _My_rope::_S_concat(__result_left, __right);
1508 #ifndef __GC
1509       _RopeRep::_S_unref(__old);
1510 #endif
1511       _M_root->_M_tree_ptr = __result;
1512       return *this;
1513     }
1514 
1515   template <class _CharT, class _Alloc>
1516     inline _Rope_char_ref_proxy<_CharT, _Alloc>::
1517     operator _CharT() const
1518     {
1519       if (_M_current_valid)
1520 	return _M_current;
1521       else
1522 	return _My_rope::_S_fetch(_M_root->_M_tree_ptr, _M_pos);
1523     }
1524 
1525   template <class _CharT, class _Alloc>
1526     _Rope_char_ptr_proxy<_CharT, _Alloc>
1527     _Rope_char_ref_proxy<_CharT, _Alloc>::
1528     operator&() const
1529     { return _Rope_char_ptr_proxy<_CharT, _Alloc>(*this); }
1530 
1531   template <class _CharT, class _Alloc>
1532     rope<_CharT, _Alloc>::
1533     rope(std::size_t __n, _CharT __c, const allocator_type& __a)
1534     : _Base(__a)
1535     {
1536       using std::__uninitialized_fill_n_a;
1537 
1538       rope<_CharT,_Alloc> __result;
1539       const std::size_t __exponentiate_threshold = 32;
1540       std::size_t __exponent;
1541       std::size_t __rest;
1542       _CharT* __rest_buffer;
1543       _RopeRep* __remainder;
1544       rope<_CharT, _Alloc> __remainder_rope;
1545 
1546       if (0 == __n)
1547 	return;
1548 
1549       __exponent = __n / __exponentiate_threshold;
1550       __rest = __n % __exponentiate_threshold;
1551       if (0 == __rest)
1552 	__remainder = 0;
1553       else
1554 	{
1555 	  __rest_buffer = this->_Data_allocate(_S_rounded_up_size(__rest));
1556 	  __uninitialized_fill_n_a(__rest_buffer, __rest, __c,
1557 				   _M_get_allocator());
1558 	  _S_cond_store_eos(__rest_buffer[__rest]);
1559 	  __try
1560 	    { __remainder = _S_new_RopeLeaf(__rest_buffer, __rest,
1561 					    _M_get_allocator()); }
1562 	  __catch(...)
1563 	    {
1564 	      _RopeRep::__STL_FREE_STRING(__rest_buffer, __rest,
1565 					  _M_get_allocator());
1566 	      __throw_exception_again;
1567 	    }
1568 	}
1569       __remainder_rope._M_tree_ptr = __remainder;
1570       if (__exponent != 0)
1571 	{
1572 	  _CharT* __base_buffer =
1573 	    this->_Data_allocate(_S_rounded_up_size(__exponentiate_threshold));
1574 	  _RopeLeaf* __base_leaf;
1575 	  rope __base_rope;
1576 	  __uninitialized_fill_n_a(__base_buffer, __exponentiate_threshold, __c,
1577 				   _M_get_allocator());
1578 	  _S_cond_store_eos(__base_buffer[__exponentiate_threshold]);
1579 	  __try
1580 	    {
1581 	      __base_leaf = _S_new_RopeLeaf(__base_buffer,
1582 					    __exponentiate_threshold,
1583 					    _M_get_allocator());
1584 	    }
1585 	  __catch(...)
1586 	    {
1587 	      _RopeRep::__STL_FREE_STRING(__base_buffer,
1588 					  __exponentiate_threshold,
1589 					  _M_get_allocator());
1590 	      __throw_exception_again;
1591 	    }
1592 	  __base_rope._M_tree_ptr = __base_leaf;
1593 	  if (1 == __exponent)
1594 	    __result = __base_rope;
1595 	  else
1596 	    __result = power(__base_rope, __exponent,
1597 			     _Rope_Concat_fn<_CharT, _Alloc>());
1598 
1599 	  if (0 != __remainder)
1600 	    __result += __remainder_rope;
1601 	}
1602       else
1603 	__result = __remainder_rope;
1604 
1605       this->_M_tree_ptr = __result._M_tree_ptr;
1606       this->_M_tree_ptr->_M_ref_nonnil();
1607     }
1608 
1609   template<class _CharT, class _Alloc>
1610     _CharT
1611     rope<_CharT, _Alloc>::_S_empty_c_str[1];
1612 
1613   template<class _CharT, class _Alloc>
1614     const _CharT*
1615     rope<_CharT, _Alloc>::
1616     c_str() const
1617     {
1618       if (0 == this->_M_tree_ptr)
1619 	{
1620 	  _S_empty_c_str[0] = _S_eos((_CharT*)0);  // Possibly redundant,
1621 	                                           // but probably fast.
1622 	  return _S_empty_c_str;
1623 	}
1624       __gthread_mutex_lock (&this->_M_tree_ptr->_M_c_string_lock);
1625       __GC_CONST _CharT* __result = this->_M_tree_ptr->_M_c_string;
1626       if (0 == __result)
1627 	{
1628 	  std::size_t __s = size();
1629 	  __result = this->_Data_allocate(__s + 1);
1630 	  _S_flatten(this->_M_tree_ptr, __result);
1631 	  __result[__s] = _S_eos((_CharT*)0);
1632 	  this->_M_tree_ptr->_M_c_string = __result;
1633 	}
1634       __gthread_mutex_unlock (&this->_M_tree_ptr->_M_c_string_lock);
1635       return(__result);
1636     }
1637 
1638   template<class _CharT, class _Alloc>
1639     const _CharT* rope<_CharT, _Alloc>::
1640     replace_with_c_str()
1641     {
1642       if (0 == this->_M_tree_ptr)
1643 	{
1644 	  _S_empty_c_str[0] = _S_eos((_CharT*)0);
1645 	  return _S_empty_c_str;
1646 	}
1647       __GC_CONST _CharT* __old_c_string = this->_M_tree_ptr->_M_c_string;
1648       if (__detail::_S_leaf == this->_M_tree_ptr->_M_tag
1649 	  && 0 != __old_c_string)
1650 	return(__old_c_string);
1651       std::size_t __s = size();
1652       _CharT* __result = this->_Data_allocate(_S_rounded_up_size(__s));
1653       _S_flatten(this->_M_tree_ptr, __result);
1654       __result[__s] = _S_eos((_CharT*)0);
1655       this->_M_tree_ptr->_M_unref_nonnil();
1656       this->_M_tree_ptr = _S_new_RopeLeaf(__result, __s,
1657 					  this->_M_get_allocator());
1658       return(__result);
1659     }
1660 
1661   // Algorithm specializations.  More should be added.
1662 
1663   template<class _Rope_iterator>  // was templated on CharT and Alloc
1664     void		          // VC++ workaround
1665     _Rope_rotate(_Rope_iterator __first,
1666 		 _Rope_iterator __middle,
1667 		 _Rope_iterator __last)
1668     {
1669       typedef typename _Rope_iterator::value_type _CharT;
1670       typedef typename _Rope_iterator::_allocator_type _Alloc;
1671 
1672       rope<_CharT, _Alloc>& __r(__first.container());
1673       rope<_CharT, _Alloc> __prefix = __r.substr(0, __first.index());
1674       rope<_CharT, _Alloc> __suffix =
1675 	__r.substr(__last.index(), __r.size() - __last.index());
1676       rope<_CharT, _Alloc> __part1 =
1677 	__r.substr(__middle.index(), __last.index() - __middle.index());
1678       rope<_CharT, _Alloc> __part2 =
1679 	__r.substr(__first.index(), __middle.index() - __first.index());
1680       __r = __prefix;
1681       __r += __part1;
1682       __r += __part2;
1683       __r += __suffix;
1684     }
1685 
1686 #if !defined(__GNUC__)
1687   // Appears to confuse g++
1688   inline void
1689   rotate(_Rope_iterator<char, __STL_DEFAULT_ALLOCATOR(char)> __first,
1690 	 _Rope_iterator<char, __STL_DEFAULT_ALLOCATOR(char)> __middle,
1691 	 _Rope_iterator<char, __STL_DEFAULT_ALLOCATOR(char)> __last)
1692   { _Rope_rotate(__first, __middle, __last); }
1693 #endif
1694 
1695 # if 0
1696   // Probably not useful for several reasons:
1697   // - for SGIs 7.1 compiler and probably some others,
1698   //   this forces lots of rope<wchar_t, ...> instantiations, creating a
1699   //   code bloat and compile time problem.  (Fixed in 7.2.)
1700   // - wchar_t is 4 bytes wide on most UNIX platforms, making it
1701   //   unattractive for unicode strings.  Unsigned short may be a better
1702   //   character type.
1703   inline void
1704   rotate(_Rope_iterator<wchar_t, __STL_DEFAULT_ALLOCATOR(char)> __first,
1705 	 _Rope_iterator<wchar_t, __STL_DEFAULT_ALLOCATOR(char)> __middle,
1706 	 _Rope_iterator<wchar_t, __STL_DEFAULT_ALLOCATOR(char)> __last)
1707   { _Rope_rotate(__first, __middle, __last); }
1708 # endif
1709 
1710 _GLIBCXX_END_NAMESPACE_VERSION
1711 } // namespace
1712