summaryrefslogtreecommitdiff
path: root/o3tl/inc/o3tl/cow_wrapper.hxx
blob: b7b3c5b9480a8af34e403031f8d1ab1cc3211f4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cow_wrapper.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_O3TL_COW_WRAPPER_HXX
#define INCLUDED_O3TL_COW_WRAPPER_HXX

#include <osl/interlck.h>

#include <algorithm>

#include <boost/utility.hpp>
#include <boost/checked_delete.hpp>

namespace o3tl
{
    /** Thread-unsafe refcounting

        This is the default locking policy for cow_wrapper. No
        locking/guarding against concurrent access is performed
        whatsoever.
     */
    struct UnsafeRefCountingPolicy
    {
        typedef sal_uInt32 ref_count_t;
        static void incrementCount( ref_count_t& rCount ) { ++rCount; }
        static bool decrementCount( ref_count_t& rCount ) { return --rCount != 0; }
    };

    /** Thread-safe refcounting

        Use this to have the cow_wrapper refcounting mechanisms employ
        the thread-safe oslInterlockedCount .
     */
    struct ThreadSafeRefCountingPolicy
    {
        typedef oslInterlockedCount ref_count_t;
        static void incrementCount( ref_count_t& rCount ) { osl_incrementInterlockedCount(&rCount); }
        static bool decrementCount( ref_count_t& rCount )
        {
            if( rCount == 1 ) // caller is already the only/last reference
                return false;
            else
                return osl_decrementInterlockedCount(&rCount) != 0;
        }
    };

    /** Copy-on-write wrapper.

        This template provides copy-on-write semantics for the wrapped
        type: when copying, the operation is performed shallow,
        i.e. different cow_wrapper objects share the same underlying
        instance. Only when accessing the underlying object via
        non-const methods, a unique copy is provided.

        The type parameter <code>T</code> must satisfy the following
        requirements: it must be default-constructible, copyable (it
        need not be assignable), and be of non-reference type. Note
        that, despite the fact that this template provides access to
        the wrapped type via pointer-like methods
        (<code>operator->()</code> and <code>operator*()</code>), it does
        <em>not</em> work like e.g. the boost pointer wrappers
        (shared_ptr, scoped_ptr, etc.). Internally, the cow_wrapper
        holds a by-value instance of the wrapped object. This is to
        avoid one additional heap allocation, and providing access via
        <code>operator->()</code>/<code>operator*()</code> is because
        <code>operator.()</code> cannot be overridden.

        Regarding thread safety: this wrapper is <em>not</em>
        thread-safe per se, because cow_wrapper has no way of
        syncronizing the potentially many different cow_wrapper
        instances, that reference a single shared value_type
        instance. That said, when passing
        <code>ThreadSafeRefCountingPolicy</code> as the
        <code>MTPolicy</code> parameter, accessing a thread-safe
        pointee through multiple cow_wrapper instances might be
        thread-safe, if the individual pointee methods are
        thread-safe, <em>including</em> pointee's copy
        constructor. Any wrapped object that needs external
        synchronisation (e.g. via an external mutex, which arbitrates
        access to object methods, and can be held across multiple
        object method calls) cannot easily be dealt with in a
        thread-safe way, because, as noted, objects are shared behind
        the client's back.

        @attention if one wants to use the pimpl idiom together with
        cow_wrapper (i.e. put an opaque type into the cow_wrapper),
        then <em>all<em> methods in the surrounding class needs to be
        non-inline (<em>including</em> destructor, copy constructor
        and assignment operator).

        @example
        <pre>
class cow_wrapper_client_impl;

class cow_wrapper_client
{
public:
    cow_wrapper_client();
    cow_wrapper_client( const cow_wrapper_client& );
    ~cow_wrapper_client();

    cow_wrapper_client& operator=( const cow_wrapper_client& );

    void modify( int nVal );
    int queryUnmodified() const;

private:
    otl::cow_wrapper< cow_wrapper_client_impl > maImpl;
};
        </pre>
        and the implementation file would look like this:
        <pre>
class cow_wrapper_client_impl
{
public:
    void setValue( int nVal ) { mnValue = nVal; }
    int getValue() const { return mnValue; }

private:
    int mnValue;
}

cow_wrapper_client::cow_wrapper_client() :
    maImpl()
{
}
cow_wrapper_client::cow_wrapper_client( const cow_wrapper_client& rSrc ) :
    maImpl( rSrc.maImpl )
{
}
cow_wrapper_client::~cow_wrapper_client()
{
}
cow_wrapper_client& cow_wrapper_client::operator=( const cow_wrapper_client& rSrc )
{
    maImpl = rSrc.maImpl;
    return *this;
}
void cow_wrapper_client::modify( int nVal )
{
    maImpl->setValue( nVal );
}
void cow_wrapper_client::queryUnmodified() const
{
    return maImpl->getValue();
}
        </pre>
     */
    template<typename T, class MTPolicy=UnsafeRefCountingPolicy> class cow_wrapper
    {
        /** shared value object - gets cloned before cow_wrapper hands
            out a non-const reference to it
         */
        struct impl_t : private boost::noncopyable
        {
            impl_t() :
                m_value(),
                m_ref_count(1)
            {
            }

            explicit impl_t( const T& v ) :
                m_value(v),
                m_ref_count(1)
            {
            }

            T                              m_value;
            typename MTPolicy::ref_count_t m_ref_count;
        };

        void release()
        {
            if( !MTPolicy::decrementCount(m_pimpl->m_ref_count) )
                boost::checked_delete(m_pimpl), m_pimpl=0;
        }

    public:
        typedef T        value_type;
        typedef T*       pointer;
        typedef MTPolicy mt_policy;

        /** Default-construct wrapped type instance
         */
        cow_wrapper() :
            m_pimpl( new impl_t() )
        {
        }

        /** Copy-construct wrapped type instance from given object
         */
        explicit cow_wrapper( const value_type& r ) :
            m_pimpl( new impl_t(r) )
        {
        }

        /** Shallow-copy given cow_wrapper
         */
        explicit cow_wrapper( const cow_wrapper& rSrc ) : // nothrow
            m_pimpl( rSrc.m_pimpl )
        {
            MTPolicy::incrementCount( m_pimpl->m_ref_count );
        }

        ~cow_wrapper() // nothrow, if ~T does not throw
        {
            release();
        }

        /// now sharing rSrc cow_wrapper instance with us
        cow_wrapper& operator=( const cow_wrapper& rSrc ) // nothrow
        {
            // this already guards against self-assignment
            MTPolicy::incrementCount( rSrc.m_pimpl->m_ref_count );

            release();
            m_pimpl = rSrc.m_pimpl;

            return *this;
        }

        /// unshare with any other cow_wrapper instance
        value_type& make_unique()
        {
            if( m_pimpl->m_ref_count > 1 )
            {
                impl_t* pimpl = new impl_t(m_pimpl->m_value);
                release();
                m_pimpl = pimpl;
            }

            return m_pimpl->m_value;
        }

        /// true, if not shared with any other cow_wrapper instance
        bool is_unique() const // nothrow
        {
            return m_pimpl->m_ref_count == 1;
        }

        /// return number of shared instances (1 for unique object)
        typename MTPolicy::ref_count_t use_count() const // nothrow
        {
            return m_pimpl->m_ref_count;
        }

        void swap(cow_wrapper& r) // never throws
        {
            std::swap(m_pimpl, r.m_pimpl);
        }

        pointer           operator->()       { return &make_unique(); }
        value_type&       operator*()        { return make_unique(); }
        const pointer     operator->() const { return &m_pimpl->m_value; }
        const value_type& operator*()  const { return m_pimpl->m_value; }

        pointer           get()       { return &make_unique(); }
        const pointer     get() const { return &m_pimpl->m_value; }

        /// true, if both cow_wrapper internally share the same object
        bool              same_object( const cow_wrapper& rOther ) const
        {
            return rOther.m_pimpl == m_pimpl;
        }

    private:
        impl_t* m_pimpl;
    };


    template<class T, class P> inline bool operator==( const cow_wrapper<T,P>& a,
                                                       const cow_wrapper<T,P>& b )
    {
        return a.same_object(b) ? true : *a == *b;
    }

    template<class T, class P> inline bool operator!=( const cow_wrapper<T,P>& a,
                                                       const cow_wrapper<T,P>& b )
    {
        return a.same_object(b) ? false : *a != *b;
    }

    template<class A, class B, class P> inline bool operator<( const cow_wrapper<A,P>& a,
                                                               const cow_wrapper<B,P>& b )
    {
        return *a < *b;
    }

    template<class T, class P> inline void swap( cow_wrapper<T,P>& a,
                                                 cow_wrapper<T,P>& b )
    {
        a.swap(b);
    }

    // to enable boost::mem_fn on cow_wrapper
    template<class T, class P> inline T * get_pointer( const cow_wrapper<T,P>& r )
    {
        return r.get();
    }

}

#endif /* INCLUDED_O3TL_COW_WRAPPER_HXX */