code:
// -*- C++ -*-

// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 2, or (at your option) any later
// version.

// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING.  If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.

// As a special exception, you may use this file as part of a free
// software library without restriction.  Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License.  This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.

// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.

// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.

/**
 * @file priority_queue.hpp
 * Contains priority_queues.
 */

#ifndef PB_DS_PRIORITY_QUEUE_HPP
#define PB_DS_PRIORITY_QUEUE_HPP

#include <ext/pb_ds/tag_and_trait.hpp>
#include <ext/pb_ds/detail/priority_queue_base_dispatch.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>

namespace pb_ds
{
  // A priority queue.
  template<typename Value_Type,
	   typename Cmp_Fn = std::less<Value_Type>,
	   typename Tag = pairing_heap_tag,
	   typename Allocator = std::allocator<char> >
  class priority_queue
    : public detail::priority_queue_base_dispatch<Value_Type,Cmp_Fn,Tag,Allocator>::type
  {
  private:
    typedef typename detail::priority_queue_base_dispatch<Value_Type,Cmp_Fn,Tag,Allocator>::type base_type;

  public:
    typedef Value_Type 					value_type;
    typedef Cmp_Fn 					cmp_fn;
    typedef Tag 					container_category;
    typedef Allocator 					allocator;
    typedef typename allocator::size_type 		size_type;
    typedef typename allocator::difference_type 	difference_type;

    typedef typename allocator::template rebind<value_type>::other value_rebind;
    typedef typename value_rebind::reference 		reference;
    typedef typename value_rebind::const_reference 	const_reference;
    typedef typename value_rebind::pointer 	   	pointer;
    typedef typename value_rebind::const_pointer 	const_pointer;

    typedef typename base_type::const_point_iterator const_point_iterator;
    typedef typename base_type::point_iterator 		point_iterator;
    typedef typename base_type::const_iterator 		const_iterator;
    typedef typename base_type::iterator 		iterator;

    priority_queue() { }

    // Constructor taking some policy objects. r_cmp_fn will be copied
    // by the Cmp_Fn object of the container object.
    priority_queue(const cmp_fn& r_cmp_fn) : base_type(r_cmp_fn) { }

    // Constructor taking __iterators to a range of value_types. The
    // value_types between first_it and last_it will be inserted into
    // the container object.
    template<typename It>
    priority_queue(It first_it, It last_it)
    { base_type::copy_from_range(first_it, last_it); }

    // Constructor taking __iterators to a range of value_types and
    // some policy objects The value_types between first_it and
    // last_it will be inserted into the container object. r_cmp_fn
    // will be copied by the cmp_fn object of the container object.
    template<typename It>
    priority_queue(It first_it, It last_it, const cmp_fn& r_cmp_fn)
    : base_type(r_cmp_fn)
    { base_type::copy_from_range(first_it, last_it); }

    priority_queue(const priority_queue& other)
    : base_type((const base_type& )other) { }

    virtual
    ~priority_queue() { }

    priority_queue&
    operator=(const priority_queue& other)
    {
      if (this !=& other)
	{
	  priority_queue tmp(other);
	  swap(tmp);
	}
      return *this;
    }

    void
    swap(priority_queue& other)
    { base_type::swap(other); }
  };
} // namespace pb_ds

#endif


code:
// -*- C++ -*-

// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 2, or (at your option) any later
// version.

// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING.  If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.

// As a special exception, you may use this file as part of a free
// software library without restriction.  Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License.  This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.

// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.

// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.

/**
 * @file tag_and_trait.hpp
 * Contains tags and traits, e.g., ones describing underlying
 *    data structures.
 */

#ifndef PB_DS_TAG_AND_TRAIT_HPP
#define PB_DS_TAG_AND_TRAIT_HPP

#include <ext/pb_ds/detail/type_utils.hpp>

namespace pb_ds
{
  // A trivial iterator tag. Signifies that the iterators has none of
  // the STL's movement abilities.
  struct trivial_iterator_tag
  { };

  // Prohibit moving trivial iterators.
  typedef void trivial_iterator_difference_type;

  // Signifies a basic invalidation guarantee that any iterator,
  // pointer, or reference to a container object's mapped value type
  // is valid as long as the container is not modified.
  struct basic_invalidation_guarantee
  { };

  // Signifies an invalidation guarantee that includes all those of
  // its base, and additionally, that any point-type iterator,
  // pointer, or reference to a container object's mapped value type
  // is valid as long as its corresponding entry has not be erased,
  // regardless of modifications to the container object.
  struct point_invalidation_guarantee : public basic_invalidation_guarantee
  { };

  // Signifies an invalidation guarantee that includes all those of
  // its base, and additionally, that any range-type iterator
  // (including the returns of begin() and end()) is in the correct
  // relative positions to other range-type iterators as long as its
  // corresponding entry has not be erased, regardless of
  // modifications to the container object.
  struct range_invalidation_guarantee : public point_invalidation_guarantee
  { };

  // A mapped-policy indicating that an associative container is a set.
  // XXX should this be a trait of the form is_set<T> ??
  struct null_mapped_type { };

  // Base data structure tag.
  struct container_tag
  { };

  // Basic associative-container.
  struct associative_container_tag : public container_tag { };

  // Basic hash.
  struct basic_hash_tag : public associative_container_tag { };

  // Collision-chaining hash.
  struct cc_hash_tag : public basic_hash_tag { };

  // General-probing hash.
  struct gp_hash_tag : public basic_hash_tag { };

  // Basic tree.
  struct basic_tree_tag : public associative_container_tag { };

  // tree.
  struct tree_tag : public basic_tree_tag { };

  // Red-black tree.
  struct rb_tree_tag : public tree_tag { };

  // Splay tree.
  struct splay_tree_tag : public tree_tag { };

  // Ordered-vector tree.
  struct ov_tree_tag : public tree_tag { };

  // trie.
  struct trie_tag : public basic_tree_tag { };

  // PATRICIA trie.
  struct pat_trie_tag : public trie_tag { };

  // List-update.
  struct list_update_tag : public associative_container_tag { };

  // Basic priority-queue.
  struct priority_queue_tag : public container_tag { };

  // Pairing-heap.
  struct pairing_heap_tag : public priority_queue_tag { };

  // Binomial-heap.
  struct binomial_heap_tag : public priority_queue_tag { };

  // Redundant-counter binomial-heap.
  struct rc_binomial_heap_tag : public priority_queue_tag { };

  // Binary-heap (array-based).
  struct binary_heap_tag : public priority_queue_tag { };

  // Thin heap.
  struct thin_heap_tag : public priority_queue_tag { };

  template<typename Tag>
  struct container_traits_base;

  template<>
  struct container_traits_base<cc_hash_tag>
  {
    typedef cc_hash_tag container_category;
    typedef point_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = false,
        erase_can_throw = false,
	split_join_can_throw = false,
	reverse_iteration = false
      };
  };

  template<>
  struct container_traits_base<gp_hash_tag>
  {
    typedef gp_hash_tag container_category;
    typedef basic_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = false,
	erase_can_throw = false,
	split_join_can_throw = false,
	reverse_iteration = false
      };
  };

  template<>
  struct container_traits_base<rb_tree_tag>
  {
    typedef rb_tree_tag container_category;
    typedef range_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = true,
        erase_can_throw = false,
	split_join_can_throw = false,
        reverse_iteration = true
      };
  };

  template<>
  struct container_traits_base<splay_tree_tag>
  {
    typedef splay_tree_tag container_category;
    typedef range_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = true,
        erase_can_throw = false,
        split_join_can_throw = false,
        reverse_iteration = true
      };
  };

  template<>
  struct container_traits_base<ov_tree_tag>
  {
    typedef ov_tree_tag container_category;
    typedef basic_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = true,
        erase_can_throw = true,
        split_join_can_throw = true,
        reverse_iteration = false
      };
  };

  template<>
  struct container_traits_base<pat_trie_tag>
  {
    typedef pat_trie_tag container_category;
    typedef range_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = true,
        erase_can_throw = false,
        split_join_can_throw = true,
        reverse_iteration = true
      };
  };

  template<>
  struct container_traits_base<list_update_tag>
  {
    typedef list_update_tag container_category;
    typedef point_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = false,
        erase_can_throw = false,
	split_join_can_throw = false,
        reverse_iteration = false
      };
  };

  template<>
  struct container_traits_base<pairing_heap_tag>
  {
    typedef pairing_heap_tag container_category;
    typedef point_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = false,
        erase_can_throw = false,
	split_join_can_throw = false,
        reverse_iteration = false
      };
  };

  template<>
  struct container_traits_base<thin_heap_tag>
  {
    typedef thin_heap_tag container_category;
    typedef point_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = false,
        erase_can_throw = false,
	split_join_can_throw = false,
        reverse_iteration = false
      };
  };

  template<>
  struct container_traits_base<binomial_heap_tag>
  {
    typedef binomial_heap_tag container_category;
    typedef point_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = false,
        erase_can_throw = false,
	split_join_can_throw = false,
        reverse_iteration = false
      };
  };

  template<>
  struct container_traits_base<rc_binomial_heap_tag>
  {
    typedef rc_binomial_heap_tag container_category;
    typedef point_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = false,
        erase_can_throw = false,
	split_join_can_throw = false,
        reverse_iteration = false
      };
  };

  template<>
  struct container_traits_base<binary_heap_tag>
  {
    typedef binary_heap_tag container_category;
    typedef basic_invalidation_guarantee invalidation_guarantee;

    enum
      {
        order_preserving = false,
        erase_can_throw = false,
	split_join_can_throw = true,
        reverse_iteration = false
      };
  };

  // See Matt Austern for the name, S. Meyers MEFC++ #2, others.
  template<typename Cntnr>
  struct container_traits
  : public container_traits_base<typename Cntnr::container_category>
  {
    typedef Cntnr container_type;
    typedef typename Cntnr::container_category container_category;
    typedef container_traits_base<container_category> base_type;
    typedef typename base_type::invalidation_guarantee invalidation_guarantee;

    enum
      {
	order_preserving = base_type::order_preserving,
	erase_can_throw = base_type::erase_can_throw,
	split_join_can_throw = base_type::split_join_can_throw,
	reverse_iteration = base_type::reverse_iteration
      };
  };
} // namespace pb_ds

#endif

repo_name: veiledmerc/mira

license: mit


code:
// -*- C++ -*-

// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 2, or (at your option) any later
// version.

// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING.  If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.

// As a special exception, you may use this file as part of a free
// software library without restriction.  Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License.  This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.

// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.

// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.

/**
 * @file tree_policy.hpp
 * Contains tree-related policies.
 */

#ifndef PB_DS_TREE_POLICY_HPP
#define PB_DS_TREE_POLICY_HPP

#include <iterator>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <ext/pb_ds/detail/basic_tree_policy/basic_tree_policy_base.hpp>

namespace pb_ds
{
  // A null node updator, indicating that no node updates are required.
  template<typename Const_Node_Iterator,
	   typename Node_Iterator,
	   typename Cmp_Fn,
	   typename Allocator>
  struct null_tree_node_update
  { };

#define PB_DS_CLASS_T_DEC \
  template<typename Const_Node_Iterator, class Node_Iterator, class Cmp_Fn, class Allocator>

#define PB_DS_CLASS_C_DEC \
  tree_order_statistics_node_update<Const_Node_Iterator, Node_Iterator, Cmp_Fn, Allocator>

#define PB_DS_BASE_C_DEC						\
  detail::basic_tree_policy_base<Const_Node_Iterator, Node_Iterator, Allocator>

  // Functor updating ranks of entrees.
  template<typename Const_Node_Iterator, typename Node_Iterator,
	   typename Cmp_Fn, typename Allocator>
  class tree_order_statistics_node_update : private PB_DS_BASE_C_DEC
  {
  private:
    typedef PB_DS_BASE_C_DEC base_type;

  public:
    typedef Cmp_Fn cmp_fn;
    typedef Allocator allocator;
    typedef typename allocator::size_type size_type;
    typedef typename base_type::key_type key_type;
    typedef typename base_type::const_key_reference const_key_reference;

    typedef size_type metadata_type;
    typedef Const_Node_Iterator const_node_iterator;
    typedef Node_Iterator node_iterator;
    typedef typename const_node_iterator::value_type const_iterator;
    typedef typename node_iterator::value_type iterator;

    // Finds an entry by __order. Returns a const_iterator to the
    // entry with the __order order, or a const_iterator to the
    // container object's end if order is at least the size of the
    // container object.
    inline const_iterator
    find_by_order(size_type order) const;

    // Finds an entry by __order. Returns an iterator to the entry
    // with the __order order, or an iterator to the container
    // object's end if order is at least the size of the container
    // object.
    inline iterator
    find_by_order(size_type order);

    // Returns the order of a key within a sequence. For exapmle, if
    // r_key is the smallest key, this method will return 0; if r_key
    // is a key between the smallest and next key, this method will
    // return 1; if r_key is a key larger than the largest key, this
    // method will return the size of r_c.
    inline size_type
    order_of_key(const_key_reference r_key) const;

  private:
    // Const reference to the container's value-type.
    typedef typename base_type::const_reference const_reference;

    // Const pointer to the container's value-type.
    typedef typename base_type::const_pointer const_pointer;

    typedef typename allocator::template rebind<metadata_type>::other metadata_rebind;
    // Const metadata reference.
    typedef typename metadata_rebind::const_reference const_metadata_reference;

    // Metadata reference.
    typedef typename metadata_rebind::reference metadata_reference;

    // Returns the const_node_iterator associated with the tree's root node.
    virtual const_node_iterator
    node_begin() const = 0;

    // Returns the node_iterator associated with the tree's root node.
    virtual node_iterator
    node_begin() = 0;

    // Returns the const_node_iterator associated with a just-after leaf node.
    virtual const_node_iterator
    node_end() const = 0;

    // Returns the node_iterator associated with a just-after leaf node.
    virtual node_iterator
    node_end() = 0;

    // Access to the cmp_fn object.
    virtual cmp_fn&
    get_cmp_fn() = 0;

  protected:
    // Updates the rank of a node through a node_iterator node_it;
    // end_nd_it is the end node iterator.
    inline void
    operator()(node_iterator node_it, const_node_iterator end_nd_it) const;

    virtual
    ~tree_order_statistics_node_update();
  };

#include <ext/pb_ds/detail/tree_policy/order_statistics_imp.hpp>

#undef PB_DS_CLASS_T_DEC
#undef PB_DS_CLASS_C_DEC
#undef PB_DS_BASE_C_DEC

} // namespace pb_ds

#endif


code:
// -*- C++ -*-

// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 2, or (at your option) any later
// version.

// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING.  If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.

// As a special exception, you may use this file as part of a free
// software library without restriction.  Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License.  This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.

// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.

// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.

/**
 * @file trie_policy.hpp
 * Contains trie-related policies.
 */

#ifndef PB_DS_TRIE_POLICY_HPP
#define PB_DS_TRIE_POLICY_HPP

#include <string>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <ext/pb_ds/detail/trie_policy/trie_policy_base.hpp>

namespace pb_ds
{
  // A null node updator, indicating that no node updates are required.
  template<typename Const_Node_Iterator,
	   typename Node_Iterator,
	   typename E_Access_Traits,
	   typename Allocator>
  struct null_trie_node_update
  { };

#define PB_DS_STATIC_ASSERT(UNIQUE, E)					\
  typedef detail::static_assert_dumclass<sizeof(detail::static_assert<bool(E)>)> UNIQUE##_static_assert_type

#define PB_DS_CLASS_T_DEC						\
  template<typename String, typename String::value_type Min_E_Val, typename String::value_type Max_E_Val, bool Reverse, typename Allocator>

#define PB_DS_CLASS_C_DEC						\
  string_trie_e_access_traits<String, Min_E_Val,Max_E_Val,Reverse,Allocator>

  // Element access traits for string types.
  template<typename String = std::string,
	   typename String::value_type Min_E_Val = detail::__numeric_traits<typename String::value_type>::__min,
	   typename String::value_type Max_E_Val = detail::__numeric_traits<typename String::value_type>::__max,
	   bool Reverse = false,
	   typename Allocator = std::allocator<char> >
  struct string_trie_e_access_traits
  {
  public:
    typedef typename Allocator::size_type size_type;
    typedef String key_type;
    typedef typename Allocator::template rebind<key_type>::other key_rebind;
    typedef typename key_rebind::const_reference const_key_reference;

    enum
      {
	reverse = Reverse
      };

    // Element const iterator type.
    typedef typename detail::__conditional_type<Reverse, typename String::const_reverse_iterator, typename String::const_iterator>::__type const_iterator;

    // Element type.
    typedef typename std::iterator_traits<const_iterator>::value_type e_type;

    enum
      {
	min_e_val = Min_E_Val,
	max_e_val = Max_E_Val,
	max_size = max_e_val - min_e_val + 1
      };
    PB_DS_STATIC_ASSERT(min_max_size, max_size >= 2);

    // Returns a const_iterator to the first element of
    // const_key_reference agumnet.
    inline static const_iterator
    begin(const_key_reference);

    // Returns a const_iterator to the after-last element of
    // const_key_reference argument.
    inline static const_iterator
    end(const_key_reference);

    // Maps an element to a position.
    inline static size_type
    e_pos(e_type e);

  private:

    inline static const_iterator
    begin_imp(const_key_reference, detail::false_type);

    inline static const_iterator
    begin_imp(const_key_reference, detail::true_type);

    inline static const_iterator
    end_imp(const_key_reference, detail::false_type);

    inline static const_iterator
    end_imp(const_key_reference, detail::true_type);

    static detail::integral_constant<int, Reverse> s_rev_ind;
  };

#include <ext/pb_ds/detail/trie_policy/string_trie_e_access_traits_imp.hpp>

#undef PB_DS_CLASS_T_DEC
#undef PB_DS_CLASS_C_DEC

#define PB_DS_CLASS_T_DEC \
  template<typename Const_Node_Iterator,typename Node_Iterator,class E_Access_Traits, typename Allocator>

#define PB_DS_CLASS_C_DEC \
  trie_prefix_search_node_update<Const_Node_Iterator, Node_Iterator, E_Access_Traits,Allocator>

#define PB_DS_BASE_C_DEC \
  detail::trie_policy_base<Const_Node_Iterator,Node_Iterator,E_Access_Traits, Allocator>

  // A node updator that allows tries to be searched for the range of
  // values that match a certain prefix.
  template<typename Const_Node_Iterator,
	   typename Node_Iterator,
	   typename E_Access_Traits,
	   typename Allocator>
  class trie_prefix_search_node_update : private PB_DS_BASE_C_DEC
  {
  private:
    typedef PB_DS_BASE_C_DEC base_type;

  public:
    typedef typename base_type::key_type key_type;
    typedef typename base_type::const_key_reference const_key_reference;

    // Element access traits.
    typedef E_Access_Traits e_access_traits;

    // Const element iterator.
    typedef typename e_access_traits::const_iterator const_e_iterator;

    // Allocator type.
    typedef Allocator allocator;

    // Size type.
    typedef typename allocator::size_type size_type;
    typedef detail::null_node_metadata metadata_type;
    typedef Const_Node_Iterator const_node_iterator;
    typedef Node_Iterator node_iterator;
    typedef typename const_node_iterator::value_type const_iterator;
    typedef typename node_iterator::value_type iterator;

    // Finds the const iterator range corresponding to all values
    // whose prefixes match r_key.
    std::pair<const_iterator, const_iterator>
    prefix_range(const_key_reference) const;

    // Finds the iterator range corresponding to all values whose
    // prefixes match r_key.
    std::pair<iterator, iterator>
    prefix_range(const_key_reference);

    // Finds the const iterator range corresponding to all values
    // whose prefixes match [b, e).
    std::pair<const_iterator, const_iterator>
    prefix_range(const_e_iterator, const_e_iterator) const;

    // Finds the iterator range corresponding to all values whose
    // prefixes match [b, e).
    std::pair<iterator, iterator>
    prefix_range(const_e_iterator, const_e_iterator);

  protected:
    // Called to update a node's metadata.
    inline void
    operator()(node_iterator node_it, const_node_iterator end_nd_it) const;

  private:
    // Returns the const iterator associated with the just-after last element.
    virtual const_iterator
    end() const = 0;

    // Returns the iterator associated with the just-after last element.
    virtual iterator
    end() = 0;

    // Returns the const_node_iterator associated with the trie's root node.
    virtual const_node_iterator
    node_begin() const = 0;

    // Returns the node_iterator associated with the trie's root node.
    virtual node_iterator
    node_begin() = 0;

    // Returns the const_node_iterator associated with a just-after leaf node.
    virtual const_node_iterator
    node_end() const = 0;

    // Returns the node_iterator associated with a just-after leaf node.
    virtual node_iterator
    node_end() = 0;

    // Access to the cmp_fn object.
    virtual const e_access_traits&
    get_e_access_traits() const = 0;

    node_iterator
    next_child(node_iterator, const_e_iterator, const_e_iterator,
	       node_iterator, const e_access_traits&);
  };

#include <ext/pb_ds/detail/trie_policy/prefix_search_node_update_imp.hpp>

#undef PB_DS_CLASS_C_DEC

#define PB_DS_CLASS_C_DEC \
  trie_order_statistics_node_update<Const_Node_Iterator, Node_Iterator,E_Access_Traits, Allocator>

  // Functor updating ranks of entrees.
  template<typename Const_Node_Iterator,
	   typename Node_Iterator,
	   typename E_Access_Traits,
	   typename Allocator>
  class trie_order_statistics_node_update : private PB_DS_BASE_C_DEC
  {
  private:
    typedef PB_DS_BASE_C_DEC base_type;

  public:
    typedef E_Access_Traits e_access_traits;
    typedef typename e_access_traits::const_iterator const_e_iterator;
    typedef Allocator allocator;
    typedef typename allocator::size_type size_type;
    typedef typename base_type::key_type key_type;
    typedef typename base_type::const_key_reference const_key_reference;

    typedef size_type metadata_type;
    typedef Const_Node_Iterator const_node_iterator;
    typedef Node_Iterator node_iterator;
    typedef typename const_node_iterator::value_type const_iterator;
    typedef typename node_iterator::value_type iterator;

    // Finds an entry by __order. Returns a const_iterator to the
    // entry with the __order order, or a const_iterator to the
    // container object's end if order is at least the size of the
    // container object.
    inline const_iterator
    find_by_order(size_type) const;

    // Finds an entry by __order. Returns an iterator to the entry
    // with the __order order, or an iterator to the container
    // object's end if order is at least the size of the container
    // object.
    inline iterator
    find_by_order(size_type);

    // Returns the order of a key within a sequence. For exapmle, if
    // r_key is the smallest key, this method will return 0; if r_key
    // is a key between the smallest and next key, this method will
    // return 1; if r_key is a key larger than the largest key, this
    // method will return the size of r_c.
    inline size_type
    order_of_key(const_key_reference) const;

    // Returns the order of a prefix within a sequence. For exapmle,
    // if [b, e] is the smallest prefix, this method will return 0; if
    // r_key is a key between the smallest and next key, this method
    // will return 1; if r_key is a key larger than the largest key,
    // this method will return the size of r_c.
    inline size_type
    order_of_prefix(const_e_iterator, const_e_iterator) const;

  private:
    typedef typename base_type::const_reference const_reference;
    typedef typename base_type::const_pointer const_pointer;

    typedef typename Allocator::template rebind<metadata_type>::other metadata_rebind;
    typedef typename metadata_rebind::const_reference const_metadata_reference;
    typedef typename metadata_rebind::reference metadata_reference;

    // Returns true if the container is empty.
    virtual bool
    empty() const = 0;

    // Returns the iterator associated with the trie's first element.
    virtual iterator
    begin() = 0;

    // Returns the iterator associated with the trie's
    // just-after-last element.
    virtual iterator
    end() = 0;

    // Returns the const_node_iterator associated with the trie's root node.
    virtual const_node_iterator
    node_begin() const = 0;

    // Returns the node_iterator associated with the trie's root node.
    virtual node_iterator
    node_begin() = 0;

    // Returns the const_node_iterator associated with a just-after
    // leaf node.
    virtual const_node_iterator
    node_end() const = 0;

    // Returns the node_iterator associated with a just-after leaf node.
    virtual node_iterator
    node_end() = 0;

    // Access to the cmp_fn object.
    virtual e_access_traits&
    get_e_access_traits() = 0;

  protected:
    // Updates the rank of a node through a node_iterator node_it;
    // end_nd_it is the end node iterator.
    inline void
    operator()(node_iterator, const_node_iterator) const;

    // Destructor.
    virtual
    ~trie_order_statistics_node_update();
  };

#include <ext/pb_ds/detail/trie_policy/order_statistics_imp.hpp>

#undef PB_DS_CLASS_T_DEC
#undef PB_DS_CLASS_C_DEC
#undef PB_DS_BASE_C_DEC
#undef PB_DS_STATIC_ASSERT

} // namespace pb_ds

#endif


code:
// POD character, std::char_traits specialization -*- C++ -*-

// Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.

// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.

/** @file ext/pod_char_traits.h
 *  This file is a GNU extension to the Standard C++ Library.
 */

// Gabriel Dos Reis <gdr@integrable-solutions.net>
// Benjamin Kosnik <bkoz@redhat.com>

#ifndef _POD_CHAR_TRAITS_H
#define _POD_CHAR_TRAITS_H 1

#include <string>

_GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)

  // POD character abstraction.
  // NB: The char_type parameter is a subset of int_type, as to allow
  // int_type to properly hold the full range of char_type values as
  // well as EOF.
  /// @brief A POD class that serves as a character abstraction class.
  template<typename V, typename I, typename S = mbstate_t>
    struct character
    {
      typedef V				value_type;
      typedef I				int_type;
      typedef S				state_type;
      typedef character<V, I, S>	char_type;

      value_type	value;

      template<typename V2>
        static char_type
        from(const V2& v)
        {
	  char_type ret = { static_cast<value_type>(v) };
	  return ret;
	}

      template<typename V2>
        static V2
        to(const char_type& c)
        {
	  V2 ret = { static_cast<V2>(c.value) };
	  return ret;
	}

    };

  template<typename V, typename I, typename S>
    inline bool
    operator==(const character<V, I, S>& lhs, const character<V, I, S>& rhs)
    { return lhs.value == rhs.value; }

  template<typename V, typename I, typename S>
    inline bool
    operator<(const character<V, I, S>& lhs, const character<V, I, S>& rhs)
    { return lhs.value < rhs.value; }

_GLIBCXX_END_NAMESPACE

_GLIBCXX_BEGIN_NAMESPACE(std)

  /// char_traits<__gnu_cxx::character> specialization.
  template<typename V, typename I, typename S>
    struct char_traits<__gnu_cxx::character<V, I, S> >
    {
      typedef __gnu_cxx::character<V, I, S>	char_type;
      typedef typename char_type::int_type	int_type;
      typedef typename char_type::state_type	state_type;
      typedef fpos<state_type>			pos_type;
      typedef streamoff				off_type;

      static void
      assign(char_type& __c1, const char_type& __c2)
      { __c1 = __c2; }

      static bool
      eq(const char_type& __c1, const char_type& __c2)
      { return __c1 == __c2; }

      static bool
      lt(const char_type& __c1, const char_type& __c2)
      { return __c1 < __c2; }

      static int
      compare(const char_type* __s1, const char_type* __s2, size_t __n)
      {
	for (size_t __i = 0; __i < __n; ++__i)
	  if (!eq(__s1[__i], __s2[__i]))
	    return lt(__s1[__i], __s2[__i]) ? -1 : 1;
	return 0;
      }

      static size_t
      length(const char_type* __s)
      {
	const char_type* __p = __s;
	while (__p->value)
	  ++__p;
	return (__p - __s);
      }

      static const char_type*
      find(const char_type* __s, size_t __n, const char_type& __a)
      {
	for (const char_type* __p = __s; size_t(__p - __s) < __n; ++__p)
	  if (*__p == __a)
	    return __p;
	return 0;
      }

      static char_type*
      move(char_type* __s1, const char_type* __s2, size_t __n)
      {
	return static_cast<char_type*>(std::memmove(__s1, __s2,
						    __n * sizeof(char_type)));
      }

      static char_type*
      copy(char_type* __s1, const char_type* __s2, size_t __n)
      {
	std::copy(__s2, __s2 + __n, __s1);
	return __s1;
      }

      static char_type*
      assign(char_type* __s, size_t __n, char_type __a)
      {
	std::fill_n(__s, __n, __a);
        return __s;
      }

      static char_type
      to_char_type(const int_type& __i)
      { return char_type::template from(__i); }

      static int_type
      to_int_type(const char_type& __c)
      { return char_type::template to<int_type>(__c); }

      static bool
      eq_int_type(const int_type& __c1, const int_type& __c2)
      { return __c1 == __c2; }

      static int_type
      eof()
      {
	int_type __r = { -1 };
	return __r;
      }

      static int_type
      not_eof(const int_type& __c)
      { return eq_int_type(__c, eof()) ? int_type() : __c; }
    };

_GLIBCXX_END_NAMESPACE

#endif


code:
// Allocators -*- C++ -*-

// Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.

// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.

/*
 * Copyright (c) 1996-1997
 * Silicon Graphics Computer Systems, Inc.
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Silicon Graphics makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 */

/** @file ext/pool_allocator.h
 *  This file is a GNU extension to the Standard C++ Library.
 */

#ifndef _POOL_ALLOCATOR_H
#define _POOL_ALLOCATOR_H 1

#include <bits/c++config.h>
#include <cstdlib>
#include <new>
#include <bits/functexcept.h>
#include <ext/atomicity.h>
#include <ext/concurrence.h>

_GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)

  using std::size_t;
  using std::ptrdiff_t;

  /**
   *  @brief  Base class for __pool_alloc.
   *
   *  @if maint
   *  Uses various allocators to fulfill underlying requests (and makes as
   *  few requests as possible when in default high-speed pool mode).
   *
   *  Important implementation properties:
   *  0. If globally mandated, then allocate objects from new
   *  1. If the clients request an object of size > _S_max_bytes, the resulting
   *     object will be obtained directly from new
   *  2. In all other cases, we allocate an object of size exactly
   *     _S_round_up(requested_size).  Thus the client has enough size
   *     information that we can return the object to the proper free list
   *     without permanently losing part of the object.
   *
   *  @endif
   */
    class __pool_alloc_base
    {
    protected:

      enum { _S_align = 8 };
      enum { _S_max_bytes = 128 };
      enum { _S_free_list_size = (size_t)_S_max_bytes / (size_t)_S_align };

      union _Obj
      {
	union _Obj* _M_free_list_link;
	char        _M_client_data[1];    // The client sees this.
      };

      static _Obj* volatile         _S_free_list[_S_free_list_size];

      // Chunk allocation state.
      static char*                  _S_start_free;
      static char*                  _S_end_free;
      static size_t                 _S_heap_size;

      size_t
      _M_round_up(size_t __bytes)
      { return ((__bytes + (size_t)_S_align - 1) & ~((size_t)_S_align - 1)); }

      _Obj* volatile*
      _M_get_free_list(size_t __bytes);

      __mutex&
      _M_get_mutex();

      // Returns an object of size __n, and optionally adds to size __n
      // free list.
      void*
      _M_refill(size_t __n);

      // Allocates a chunk for nobjs of size size.  nobjs may be reduced
      // if it is inconvenient to allocate the requested number.
      char*
      _M_allocate_chunk(size_t __n, int& __nobjs);
    };

  /// @brief  class __pool_alloc.
  template<typename _Tp>
    class __pool_alloc : private __pool_alloc_base
    {
    private:
      static _Atomic_word	    _S_force_new;

    public:
      typedef size_t     size_type;
      typedef ptrdiff_t  difference_type;
      typedef _Tp*       pointer;
      typedef const _Tp* const_pointer;
      typedef _Tp&       reference;
      typedef const _Tp& const_reference;
      typedef _Tp        value_type;

      template<typename _Tp1>
        struct rebind
        { typedef __pool_alloc<_Tp1> other; };

      __pool_alloc() throw() { }

      __pool_alloc(const __pool_alloc&) throw() { }

      template<typename _Tp1>
        __pool_alloc(const __pool_alloc<_Tp1>&) throw() { }

      ~__pool_alloc() throw() { }

      pointer
      address(reference __x) const { return &__x; }

      const_pointer
      address(const_reference __x) const { return &__x; }

      size_type
      max_size() const throw()
      { return size_t(-1) / sizeof(_Tp); }

      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 402. wrong new expression in [some_] allocator::construct
      void
      construct(pointer __p, const _Tp& __val)
      { ::new(__p) _Tp(__val); }

      void
      destroy(pointer __p) { __p->~_Tp(); }

      pointer
      allocate(size_type __n, const void* = 0);

      void
      deallocate(pointer __p, size_type __n);
    };

  template<typename _Tp>
    inline bool
    operator==(const __pool_alloc<_Tp>&, const __pool_alloc<_Tp>&)
    { return true; }

  template<typename _Tp>
    inline bool
    operator!=(const __pool_alloc<_Tp>&, const __pool_alloc<_Tp>&)
    { return false; }

  template<typename _Tp>
    _Atomic_word
    __pool_alloc<_Tp>::_S_force_new;

  template<typename _Tp>
    _Tp*
    __pool_alloc<_Tp>::allocate(size_type __n, const void*)
    {
      pointer __ret = 0;
      if (__builtin_expect(__n != 0, true))
	{
	  if (__builtin_expect(__n > this->max_size(), false))
	    std::__throw_bad_alloc();

	  // If there is a race through here, assume answer from getenv
	  // will resolve in same direction.  Inspired by techniques
	  // to efficiently support threading found in basic_string.h.
	  if (_S_force_new == 0)
	    {
	      if (std::getenv("GLIBCXX_FORCE_NEW"))
		__atomic_add_dispatch(&_S_force_new, 1);
	      else
		__atomic_add_dispatch(&_S_force_new, -1);
	    }

	  const size_t __bytes = __n * sizeof(_Tp);
	  if (__bytes > size_t(_S_max_bytes) || _S_force_new == 1)
	    __ret = static_cast<_Tp*>(::operator new(__bytes));
	  else
	    {
	      _Obj* volatile* __free_list = _M_get_free_list(__bytes);

	      __scoped_lock sentry(_M_get_mutex());
	      _Obj* __restrict__ __result = *__free_list;
	      if (__builtin_expect(__result == 0, 0))
		__ret = static_cast<_Tp*>(_M_refill(_M_round_up(__bytes)));
	      else
		{
		  *__free_list = __result->_M_free_list_link;
		  __ret = reinterpret_cast<_Tp*>(__result);
		}
	      if (__builtin_expect(__ret == 0, 0))
		std::__throw_bad_alloc();
	    }
	}
      return __ret;
    }

  template<typename _Tp>
    void
    __pool_alloc<_Tp>::deallocate(pointer __p, size_type __n)
    {
      if (__builtin_expect(__n != 0 && __p != 0, true))
	{
	  const size_t __bytes = __n * sizeof(_Tp);
	  if (__bytes > static_cast<size_t>(_S_max_bytes) || _S_force_new == 1)
	    ::operator delete(__p);
	  else
	    {
	      _Obj* volatile* __free_list = _M_get_free_list(__bytes);
	      _Obj* __q = reinterpret_cast<_Obj*>(__p);

	      __scoped_lock sentry(_M_get_mutex());
	      __q ->_M_free_list_link = *__free_list;
	      *__free_list = __q;
	    }
	}
    }

_GLIBCXX_END_NAMESPACE

#endif


code:
// rb_tree extension -*- C++ -*-

// Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.

// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.

/*
 *
 * Copyright (c) 1994
 * Hewlett-Packard Company
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Hewlett-Packard Company makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 *
 * Copyright (c) 1996
 * Silicon Graphics Computer Systems, Inc.
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Silicon Graphics makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 */

/** @file ext/rb_tree
 *  This file is a GNU extension to the Standard C++ Library (possibly
 *  containing extensions from the HP/SGI STL subset).
 */

#ifndef _RB_TREE
#define _RB_TREE 1

#pragma GCC system_header

#include <bits/stl_tree.h>

_GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)

  using std::_Rb_tree;
  using std::allocator;

  // Class rb_tree is not part of the C++ standard.  It is provided for
  // compatibility with the HP STL.

  /**
   *  This is an SGI extension.
   *  @ingroup SGIextensions
   *  @doctodo
   */
  template <class _Key, class _Value, class _KeyOfValue, class _Compare,
	    class _Alloc = allocator<_Value> >
    struct rb_tree
    : public _Rb_tree<_Key, _Value, _KeyOfValue, _Compare, _Alloc>
    {
      typedef _Rb_tree<_Key, _Value, _KeyOfValue, _Compare, _Alloc> _Base;
      typedef typename _Base::allocator_type allocator_type;

      rb_tree(const _Compare& __comp = _Compare(),
	      const allocator_type& __a = allocator_type())
      : _Base(__comp, __a) { }

      ~rb_tree() { }
    };

_GLIBCXX_END_NAMESPACE

#endif


code:
// Reference-counted versatile string base -*- C++ -*-

// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.

// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.

/** @file ext/rc_string_base.h
 *  This file is a GNU extension to the Standard C++ Library.
 *  This is an internal header file, included by other library headers.
 *  You should not attempt to use it directly.
 */

#ifndef _RC_STRING_BASE_H
#define _RC_STRING_BASE_H 1

#include <ext/atomicity.h>

_GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)

  /**
   *  @if maint
   *  Documentation?  What's that?
   *  Nathan Myers <ncm@cantrip.org>.
   *
   *  A string looks like this:
   *
   *  @code
   *                                        [_Rep]
   *                                        _M_length
   *   [__rc_string_base<char_type>]        _M_capacity
   *   _M_dataplus                          _M_refcount
   *   _M_p ---------------->               unnamed array of char_type
   *  @endcode
   *
   *  Where the _M_p points to the first character in the string, and
   *  you cast it to a pointer-to-_Rep and subtract 1 to get a
   *  pointer to the header.
   *
   *  This approach has the enormous advantage that a string object
   *  requires only one allocation.  All the ugliness is confined
   *  within a single pair of inline functions, which each compile to
   *  a single "add" instruction: _Rep::_M_refdata(), and
   *  __rc_string_base::_M_rep(); and the allocation function which gets a
   *  block of raw bytes and with room enough and constructs a _Rep
   *  object at the front.
   *
   *  The reason you want _M_data pointing to the character array and
   *  not the _Rep is so that the debugger can see the string
   *  contents. (Probably we should add a non-inline member to get
   *  the _Rep for the debugger to use, so users can check the actual
   *  string length.)
   *
   *  Note that the _Rep object is a POD so that you can have a
   *  static "empty string" _Rep object already "constructed" before
   *  static constructors have run.  The reference-count encoding is
   *  chosen so that a 0 indicates one reference, so you never try to
   *  destroy the empty-string _Rep object.
   *
   *  All but the last paragraph is considered pretty conventional
   *  for a C++ string implementation.
   *  @endif
  */
 template<typename _CharT, typename _Traits, typename _Alloc>
    class __rc_string_base
    : protected __vstring_utility<_CharT, _Traits, _Alloc>
    {
    public:
      typedef _Traits					    traits_type;
      typedef typename _Traits::char_type		    value_type;
      typedef _Alloc					    allocator_type;

      typedef __vstring_utility<_CharT, _Traits, _Alloc>    _Util_Base;
      typedef typename _Util_Base::_CharT_alloc_type        _CharT_alloc_type;
      typedef typename _CharT_alloc_type::size_type	    size_type;

    private:
      // _Rep: string representation
      //   Invariants:
      //   1. String really contains _M_length + 1 characters: due to 21.3.4
      //      must be kept null-terminated.
      //   2. _M_capacity >= _M_length
      //      Allocated memory is always (_M_capacity + 1) * sizeof(_CharT).
      //   3. _M_refcount has three states:
      //      -1: leaked, one reference, no ref-copies allowed, non-const.
      //       0: one reference, non-const.
      //     n>0: n + 1 references, operations require a lock, const.
      //   4. All fields == 0 is an empty string, given the extra storage
      //      beyond-the-end for a null terminator; thus, the shared
      //      empty string representation needs no constructor.
      struct _Rep
      {
	union
	{
	  struct
	  {
	    size_type	    _M_length;
	    size_type	    _M_capacity;
	    _Atomic_word    _M_refcount;
	  }                 _M_info;

	  // Only for alignment purposes.
	  _CharT            _M_align;
	};

	typedef typename _Alloc::template rebind<_Rep>::other _Rep_alloc_type;

 	_CharT*
	_M_refdata() throw()
	{ return reinterpret_cast<_CharT*>(this + 1); }

	_CharT*
	_M_refcopy() throw()
	{
	  __atomic_add_dispatch(&_M_info._M_refcount, 1);
	  return _M_refdata();
	}  // XXX MT

	void
	_M_set_length(size_type __n)
	{
	  _M_info._M_refcount = 0;  // One reference.
	  _M_info._M_length = __n;
	  // grrr. (per 21.3.4)
	  // You cannot leave those LWG people alone for a second.
	  traits_type::assign(_M_refdata()[__n], _CharT());
	}

	// Create & Destroy
	static _Rep*
	_S_create(size_type, size_type, const _Alloc&);

	void
	_M_destroy(const _Alloc&) throw();

	_CharT*
	_M_clone(const _Alloc&, size_type __res = 0);
      };

      struct _Rep_empty
      : public _Rep
      {
	_CharT              _M_terminal;
      };

      static _Rep_empty     _S_empty_rep;

      // The maximum number of individual char_type elements of an
      // individual string is determined by _S_max_size. This is the
      // value that will be returned by max_size().  (Whereas npos
      // is the maximum number of bytes the allocator can allocate.)
      // If one was to divvy up the theoretical largest size string,
      // with a terminating character and m _CharT elements, it'd
      // look like this:
      // npos = sizeof(_Rep) + (m * sizeof(_CharT)) + sizeof(_CharT)
      //        + sizeof(_Rep) - 1
      // (NB: last two terms for rounding reasons, see _M_create below)
      // Solving for m:
      // m = ((npos - 2 * sizeof(_Rep) + 1) / sizeof(_CharT)) - 1
      // In addition, this implementation halfs this amount.
      enum { _S_max_size = (((static_cast<size_type>(-1) - 2 * sizeof(_Rep)
			      + 1) / sizeof(_CharT)) - 1) / 2 };

      // Data Member (private):
      mutable typename _Util_Base::template _Alloc_hider<_Alloc>  _M_dataplus;

      void
      _M_data(_CharT* __p)
      { _M_dataplus._M_p = __p; }

      _Rep*
      _M_rep() const
      { return &((reinterpret_cast<_Rep*>(_M_data()))[-1]); }

      _CharT*
      _M_grab(const _Alloc& __alloc) const
      {
	return (!_M_is_leaked() && _M_get_allocator() == __alloc)
	        ? _M_rep()->_M_refcopy() : _M_rep()->_M_clone(__alloc);
      }

      void
      _M_dispose()
      {
	if (__exchange_and_add_dispatch(&_M_rep()->_M_info._M_refcount,
					-1) <= 0)
	  _M_rep()->_M_destroy(_M_get_allocator());
      }  // XXX MT

      bool
      _M_is_leaked() const
      { return _M_rep()->_M_info._M_refcount < 0; }

      void
      _M_set_sharable()
      { _M_rep()->_M_info._M_refcount = 0; }

      void
      _M_leak_hard();

      // _S_construct_aux is used to implement the 21.3.1 para 15 which
      // requires special behaviour if _InIterator is an integral type
      template<typename _InIterator>
        static _CharT*
        _S_construct_aux(_InIterator __beg, _InIterator __end,
			 const _Alloc& __a, std::__false_type)
	{
          typedef typename iterator_traits<_InIterator>::iterator_category _Tag;
          return _S_construct(__beg, __end, __a, _Tag());
	}

      template<typename _InIterator>
        static _CharT*
        _S_construct_aux(_InIterator __beg, _InIterator __end,
			 const _Alloc& __a, std::__true_type)
	{ return _S_construct(static_cast<size_type>(__beg),
			      static_cast<value_type>(__end), __a); }

      template<typename _InIterator>
        static _CharT*
        _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a)
	{
	  typedef typename std::__is_integer<_InIterator>::__type _Integral;
	  return _S_construct_aux(__beg, __end, __a, _Integral());
        }

      // For Input Iterators, used in istreambuf_iterators, etc.
      template<typename _InIterator>
        static _CharT*
         _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a,
		      std::input_iterator_tag);

      // For forward_iterators up to random_access_iterators, used for
      // string::iterator, _CharT*, etc.
      template<typename _FwdIterator>
        static _CharT*
        _S_construct(_FwdIterator __beg, _FwdIterator __end, const _Alloc& __a,
		     std::forward_iterator_tag);

      static _CharT*
      _S_construct(size_type __req, _CharT __c, const _Alloc& __a);

    public:
      size_type
      _M_max_size() const
      { return size_type(_S_max_size); }

      _CharT*
      _M_data() const
      { return _M_dataplus._M_p; }

      size_type
      _M_length() const
      { return _M_rep()->_M_info._M_length; }

      size_type
      _M_capacity() const
      { return _M_rep()->_M_info._M_capacity; }

      bool
      _M_is_shared() const
      { return _M_rep()->_M_info._M_refcount > 0; }

      void
      _M_set_leaked()
      { _M_rep()->_M_info._M_refcount = -1; }

      void
      _M_leak()    // for use in begin() & non-const op[]
      {
	if (!_M_is_leaked())
	  _M_leak_hard();
      }

      void
      _M_set_length(size_type __n)
      { _M_rep()->_M_set_length(__n); }

      __rc_string_base()
      : _M_dataplus(_Alloc(), _S_empty_rep._M_refcopy()) { }

      __rc_string_base(const _Alloc& __a);

      __rc_string_base(const __rc_string_base& __rcs);

      __rc_string_base(size_type __n, _CharT __c, const _Alloc& __a);

      template<typename _InputIterator>
        __rc_string_base(_InputIterator __beg, _InputIterator __end,
			 const _Alloc& __a);

      ~__rc_string_base()
      { _M_dispose(); }

      allocator_type&
      _M_get_allocator()
      { return _M_dataplus; }

      const allocator_type&
      _M_get_allocator() const
      { return _M_dataplus; }

      void
      _M_swap(__rc_string_base& __rcs);

      void
      _M_assign(const __rc_string_base& __rcs);

      void
      _M_reserve(size_type __res);

      void
      _M_mutate(size_type __pos, size_type __len1, const _CharT* __s,
		size_type __len2);

      void
      _M_erase(size_type __pos, size_type __n);

      void
      _M_clear()
      { _M_erase(size_type(0), _M_length()); }

      bool
      _M_compare(const __rc_string_base&) const
      { return false; }
    };

  template<typename _CharT, typename _Traits, typename _Alloc>
    typename __rc_string_base<_CharT, _Traits, _Alloc>::_Rep_empty
    __rc_string_base<_CharT, _Traits, _Alloc>::_S_empty_rep;

  template<typename _CharT, typename _Traits, typename _Alloc>
    typename __rc_string_base<_CharT, _Traits, _Alloc>::_Rep*
    __rc_string_base<_CharT, _Traits, _Alloc>::_Rep::
    _S_create(size_type __capacity, size_type __old_capacity,
	      const _Alloc& __alloc)
    {
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 83.  String::npos vs. string::max_size()
      if (__capacity > size_type(_S_max_size))
	std::__throw_length_error(__N("__rc_string_base::_Rep::_S_create"));

      // The standard places no restriction on allocating more memory
      // than is strictly needed within this layer at the moment or as
      // requested by an explicit application call to reserve().

      // Many malloc implementations perform quite poorly when an
      // application attempts to allocate memory in a stepwise fashion
      // growing each allocation size by only 1 char.  Additionally,
      // it makes little sense to allocate less linear memory than the
      // natural blocking size of the malloc implementation.
      // Unfortunately, we would need a somewhat low-level calculation
      // with tuned parameters to get this perfect for any particular
      // malloc implementation.  Fortunately, generalizations about
      // common features seen among implementations seems to suffice.

      // __pagesize need not match the actual VM page size for good
      // results in practice, thus we pick a common value on the low
      // side.  __malloc_header_size is an estimate of the amount of
      // overhead per memory allocation (in practice seen N * sizeof
      // (void*) where N is 0, 2 or 4).  According to folklore,
      // picking this value on the high side is better than
      // low-balling it (especially when this algorithm is used with
      // malloc implementations that allocate memory blocks rounded up
      // to a size which is a power of 2).
      const size_type __pagesize = 4096;
      const size_type __malloc_header_size = 4 * sizeof(void*);

      // The below implements an exponential growth policy, necessary to
      // meet amortized linear time requirements of the library: see
      // http://gcc.gnu.org/ml/libstdc++/2001-07/msg00085.html.
      if (__capacity > __old_capacity && __capacity < 2 * __old_capacity)
	{
	  __capacity = 2 * __old_capacity;
	  // Never allocate a string bigger than _S_max_size.
	  if (__capacity > size_type(_S_max_size))
	    __capacity = size_type(_S_max_size);
	}

      // NB: Need an array of char_type[__capacity], plus a terminating
      // null char_type() element, plus enough for the _Rep data structure,
      // plus sizeof(_Rep) - 1 to upper round to a size multiple of
      // sizeof(_Rep).
      // Whew. Seemingly so needy, yet so elemental.
      size_type __size = ((__capacity + 1) * sizeof(_CharT)
			  + 2 * sizeof(_Rep) - 1);

      const size_type __adj_size = __size + __malloc_header_size;
      if (__adj_size > __pagesize && __capacity > __old_capacity)
	{
	  const size_type __extra = __pagesize - __adj_size % __pagesize;
	  __capacity += __extra / sizeof(_CharT);
	  if (__capacity > size_type(_S_max_size))
	    __capacity = size_type(_S_max_size);
	  __size = (__capacity + 1) * sizeof(_CharT) + 2 * sizeof(_Rep) - 1;
	}

      // NB: Might throw, but no worries about a leak, mate: _Rep()
      // does not throw.
      _Rep* __place = _Rep_alloc_type(__alloc).allocate(__size / sizeof(_Rep));
      _Rep* __p = new (__place) _Rep;
      __p->_M_info._M_capacity = __capacity;
      return __p;
    }

  template<typename _CharT, typename _Traits, typename _Alloc>
    void
    __rc_string_base<_CharT, _Traits, _Alloc>::_Rep::
    _M_destroy(const _Alloc& __a) throw ()
    {
      const size_type __size = ((_M_info._M_capacity + 1) * sizeof(_CharT)
				+ 2 * sizeof(_Rep) - 1);
      _Rep_alloc_type(__a).deallocate(this, __size / sizeof(_Rep));
    }

  template<typename _CharT, typename _Traits, typename _Alloc>
    _CharT*
    __rc_string_base<_CharT, _Traits, _Alloc>::_Rep::
    _M_clone(const _Alloc& __alloc, size_type __res)
    {
      // Requested capacity of the clone.
      const size_type __requested_cap = _M_info._M_length + __res;
      _Rep* __r = _Rep::_S_create(__requested_cap, _M_info._M_capacity,
				  __alloc);

      if (_M_info._M_length)
	_S_copy(__r->_M_refdata(), _M_refdata(), _M_info._M_length);

      __r->_M_set_length(_M_info._M_length);
      return __r->_M_refdata();
    }

  template<typename _CharT, typename _Traits, typename _Alloc>
    __rc_string_base<_CharT, _Traits, _Alloc>::
    __rc_string_base(const _Alloc& __a)
    : _M_dataplus(__a, _S_construct(size_type(), _CharT(), __a)) { }

  template<typename _CharT, typename _Traits, typename _Alloc>
    __rc_string_base<_CharT, _Traits, _Alloc>::
    __rc_string_base(const __rc_string_base& __rcs)
    : _M_dataplus(__rcs._M_get_allocator(),
		  __rcs._M_grab(__rcs._M_get_allocator())) { }

  template<typename _CharT, typename _Traits, typename _Alloc>
    __rc_string_base<_CharT, _Traits, _Alloc>::
    __rc_string_base(size_type __n, _CharT __c, const _Alloc& __a)
    : _M_dataplus(__a, _S_construct(__n, __c, __a)) { }

  template<typename _CharT, typename _Traits, typename _Alloc>
    template<typename _InputIterator>
    __rc_string_base<_CharT, _Traits, _Alloc>::
    __rc_string_base(_InputIterator __beg, _InputIterator __end,
		     const _Alloc& __a)
    : _M_dataplus(__a, _S_construct(__beg, __end, __a)) { }

  template<typename _CharT, typename _Traits, typename _Alloc>
    void
    __rc_string_base<_CharT, _Traits, _Alloc>::
    _M_leak_hard()
    {
      if (_M_is_shared())
	_M_erase(0, 0);
      _M_set_leaked();
    }

  // NB: This is the special case for Input Iterators, used in
  // istreambuf_iterators, etc.
  // Input Iterators have a cost structure very different from
  // pointers, calling for a different coding style.
  template<typename _CharT, typename _Traits, typename _Alloc>
    template<typename _InIterator>
      _CharT*
      __rc_string_base<_CharT, _Traits, _Alloc>::
      _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a,
		   std::input_iterator_tag)
      {
	if (__beg == __end && __a == _Alloc())
	  return _S_empty_rep._M_refcopy();

	// Avoid reallocation for common case.
	_CharT __buf[128];
	size_type __len = 0;
	while (__beg != __end && __len < sizeof(__buf) / sizeof(_CharT))
	  {
	    __buf[__len++] = *__beg;
	    ++__beg;
	  }
	_Rep* __r = _Rep::_S_create(__len, size_type(0), __a);
	_S_copy(__r->_M_refdata(), __buf, __len);
	try
	  {
	    while (__beg != __end)
	      {
		if (__len == __r->_M_info._M_capacity)
		  {
		    // Allocate more space.
		    _Rep* __another = _Rep::_S_create(__len + 1, __len, __a);
		    _S_copy(__another->_M_refdata(), __r->_M_refdata(), __len);
		    __r->_M_destroy(__a);
		    __r = __another;
		  }
		__r->_M_refdata()[__len++] = *__beg;
		++__beg;
	      }
	  }
	catch(...)
	  {
	    __r->_M_destroy(__a);
	    __throw_exception_again;
	  }
	__r->_M_set_length(__len);
	return __r->_M_refdata();
      }

  template<typename _CharT, typename _Traits, typename _Alloc>
    template<typename _InIterator>
      _CharT*
      __rc_string_base<_CharT, _Traits, _Alloc>::
      _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a,
		   std::forward_iterator_tag)
      {
	if (__beg == __end && __a == _Alloc())
	  return _S_empty_rep._M_refcopy();

	// NB: Not required, but considered best practice.
	if (__builtin_expect(_S_is_null_pointer(__beg) && __beg != __end, 0))
	  std::__throw_logic_error(__N("__rc_string_base::"
				       "_S_construct NULL not valid"));

	const size_type __dnew = static_cast<size_type>(std::distance(__beg,
								      __end));
	// Check for out_of_range and length_error exceptions.
	_Rep* __r = _Rep::_S_create(__dnew, size_type(0), __a);
	try
	  { _S_copy_chars(__r->_M_refdata(), __beg, __end); }
	catch(...)
	  {
	    __r->_M_destroy(__a);
	    __throw_exception_again;
	  }
	__r->_M_set_length(__dnew);
	return __r->_M_refdata();
      }

  template<typename _CharT, typename _Traits, typename _Alloc>
    _CharT*
    __rc_string_base<_CharT, _Traits, _Alloc>::
    _S_construct(size_type __n, _CharT __c, const _Alloc& __a)
    {
      if (__n == 0 && __a == _Alloc())
	return _S_empty_rep._M_refcopy();

      // Check for out_of_range and length_error exceptions.
      _Rep* __r = _Rep::_S_create(__n, size_type(0), __a);
      if (__n)
	_S_assign(__r->_M_refdata(), __n, __c);

      __r->_M_set_length(__n);
      return __r->_M_refdata();
    }

  template<typename _CharT, typename _Traits, typename _Alloc>
    void
    __rc_string_base<_CharT, _Traits, _Alloc>::
    _M_swap(__rc_string_base& __rcs)
    {
      if (_M_is_leaked())
	_M_set_sharable();
      if (__rcs._M_is_leaked())
	__rcs._M_set_sharable();

      _CharT* __tmp = _M_data();
      _M_data(__rcs._M_data());
      __rcs._M_data(__tmp);

      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 431. Swapping containers with unequal allocators.
      std::__alloc_swap<allocator_type>::_S_do_it(_M_get_allocator(),
						  __rcs._M_get_allocator());
    }

  template<typename _CharT, typename _Traits, typename _Alloc>
    void
    __rc_string_base<_CharT, _Traits, _Alloc>::
    _M_assign(const __rc_string_base& __rcs)
    {
      if (_M_rep() != __rcs._M_rep())
	{
	  _CharT* __tmp = __rcs._M_grab(_M_get_allocator());
	  _M_dispose();
	  _M_data(__tmp);
	}
    }

  template<typename _CharT, typename _Traits, typename _Alloc>
    void
    __rc_string_base<_CharT, _Traits, _Alloc>::
    _M_reserve(size_type __res)
    {
      // Make sure we don't shrink below the current size.
      if (__res < _M_length())
	__res = _M_length();

      if (__res != _M_capacity() || _M_is_shared())
	{
	  _CharT* __tmp = _M_rep()->_M_clone(_M_get_allocator(),
					     __res - _M_length());
	  _M_dispose();
	  _M_data(__tmp);
	}
    }

  template<typename _CharT, typename _Traits, typename _Alloc>
    void
    __rc_string_base<_CharT, _Traits, _Alloc>::
    _M_mutate(size_type __pos, size_type __len1, const _CharT* __s,
	      size_type __len2)
    {
      const size_type __how_much = _M_length() - __pos - __len1;

      _Rep* __r = _Rep::_S_create(_M_length() + __len2 - __len1,
				  _M_capacity(), _M_get_allocator());

      if (__pos)
	_S_copy(__r->_M_refdata(), _M_data(), __pos);
      if (__s && __len2)
	_S_copy(__r->_M_refdata() + __pos, __s, __len2);
      if (__how_much)
	_S_copy(__r->_M_refdata() + __pos + __len2,
		_M_data() + __pos + __len1, __how_much);

      _M_dispose();
      _M_data(__r->_M_refdata());
    }

  template<typename _CharT, typename _Traits, typename _Alloc>
    void
    __rc_string_base<_CharT, _Traits, _Alloc>::
    _M_erase(size_type __pos, size_type __n)
    {
      const size_type __new_size = _M_length() - __n;
      const size_type __how_much = _M_length() - __pos - __n;

      if (_M_is_shared())
	{
	  // Must reallocate.
	  _Rep* __r = _Rep::_S_create(__new_size, _M_capacity(),
				      _M_get_allocator());

	  if (__pos)
	    _S_copy(__r->_M_refdata(), _M_data(), __pos);
	  if (__how_much)
	    _S_copy(__r->_M_refdata() + __pos,
		    _M_data() + __pos + __n, __how_much);

	  _M_dispose();
	  _M_data(__r->_M_refdata());
	}
      else if (__how_much && __n)
	{
	  // Work in-place.
	  _S_move(_M_data() + __pos,
		  _M_data() + __pos + __n, __how_much);
	}

      _M_rep()->_M_set_length(__new_size);
    }

  template<>
    inline bool
    __rc_string_base<char, std::char_traits<char>,
		     std::allocator<char> >::
    _M_compare(const __rc_string_base& __rcs) const
    {
      if (_M_rep() == __rcs._M_rep())
	return true;
      return false;
    }

#ifdef _GLIBCXX_USE_WCHAR_T
  template<>
    inline bool
    __rc_string_base<wchar_t, std::char_traits<wchar_t>,
		     std::allocator<wchar_t> >::
    _M_compare(const __rc_string_base& __rcs) const
    {
      if (_M_rep() == __rcs._M_rep())
	return true;
      return false;
    }
#endif

_GLIBCXX_END_NAMESPACE

#endif /* _RC_STRING_BASE_H */