1 // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*-
2 //
3 // self_match.h: Rcpp R/C++ interface class library -- self match
4 //
5 // Copyright (C) 2012   Dirk Eddelbuettel and Romain Francois
6 //
7 // This file is part of Rcpp.
8 //
9 // Rcpp is free software: you can redistribute it and/or modify it
10 // under the terms of the GNU General Public License as published by
11 // the Free Software Foundation, either version 2 of the License, or
12 // (at your option) any later version.
13 //
14 // Rcpp is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 // GNU General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with Rcpp.  If not, see <http://www.gnu.org/licenses/>.
21 
22 #ifndef Rcpp__sugar__self_match_h
23 #define Rcpp__sugar__self_match_h
24 
25 namespace Rcpp{
26 namespace sugar{
27 
28 template <typename HASH, typename STORAGE>
29 class SelfInserter {
30 public:
SelfInserter(HASH & hash_)31     SelfInserter( HASH& hash_ ) : hash(hash_), index(0) {}
32 
operator()33     inline R_xlen_t operator()( STORAGE value ){
34         typename HASH::iterator it = hash.find( value ) ;
35         if( it == hash.end() ){
36             hash.insert( std::make_pair(value, ++index) ) ;
37             return index ;
38         } else {
39             return it->second ;
40         }
41     }
42 
43 private:
44     HASH& hash ;
45     R_xlen_t index;
46 } ;
47 
48 template <int RTYPE, typename TABLE_T>
49 class SelfMatch {
50 public:
51     typedef typename Rcpp::traits::storage_type<RTYPE>::type STORAGE ;
52 
SelfMatch(const TABLE_T & table)53     SelfMatch( const TABLE_T& table ): hash(), result(table.size()) {
54         std::transform( table.begin(), table.end(), result.begin(), Inserter(hash) ) ;
55     }
56 
IntegerVector()57     inline operator IntegerVector() const { return result ; }
58 
59 private:
60     typedef RCPP_UNORDERED_MAP<STORAGE, int> HASH ;
61     typedef SelfInserter<HASH,STORAGE> Inserter ;
62     HASH hash ;
63     IntegerVector result ;
64 };
65 
66 } // sugar
67 
68 template <int RTYPE, bool NA, typename T>
self_match(const VectorBase<RTYPE,NA,T> & x)69 inline IntegerVector self_match( const VectorBase<RTYPE,NA,T>& x ){
70     Vector<RTYPE> vec(x) ;
71     return sugar::SelfHash<RTYPE>(vec).fill_and_self_match() ;
72 }
73 
74 
75 } // Rcpp
76 #endif
77 
78