Home | History | Annotate | Download | only in port
      1 /*
      2  * Copyright 2011 Google Inc. All Rights Reserved.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef SFNTLY_CPP_SRC_SFNTLY_PORT_ATOMIC_H_
     18 #define SFNTLY_CPP_SRC_SFNTLY_PORT_ATOMIC_H_
     19 
     20 #if defined (WIN32)
     21 
     22 #include <windows.h>
     23 
     24 static inline size_t AtomicIncrement(size_t* address) {
     25 #if defined (_WIN64)
     26   return InterlockedIncrement64(reinterpret_cast<LONGLONG*>(address));
     27 #else
     28   return InterlockedIncrement(reinterpret_cast<LONG*>(address));
     29 #endif
     30 }
     31 
     32 static inline size_t AtomicDecrement(size_t* address) {
     33 #if defined (_WIN64)
     34   return InterlockedDecrement64(reinterpret_cast<LONGLONG*>(address));
     35 #else
     36   return InterlockedDecrement(reinterpret_cast<LONG*>(address));
     37 #endif
     38 }
     39 
     40 #elif defined (__APPLE__)
     41 
     42 #include <libkern/OSAtomic.h>
     43 
     44 static inline size_t AtomicIncrement(size_t* address) {
     45   return OSAtomicIncrement32Barrier(reinterpret_cast<int32_t*>(address));
     46 }
     47 
     48 static inline size_t AtomicDecrement(size_t* address) {
     49   return OSAtomicDecrement32Barrier(reinterpret_cast<int32_t*>(address));
     50 }
     51 
     52 // Originally we check __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4, however, there are
     53 // issues that clang not carring over this definition.  Therefore we boldly
     54 // assume it's gcc or gcc-compatible here.  Compilation shall still fail since
     55 // the intrinsics used are GCC-specific.
     56 
     57 #else
     58 
     59 #include <stddef.h>
     60 
     61 static inline size_t AtomicIncrement(size_t* address) {
     62   return __sync_add_and_fetch(address, 1);
     63 }
     64 
     65 static inline size_t AtomicDecrement(size_t* address) {
     66   return __sync_sub_and_fetch(address, 1);
     67 }
     68 
     69 #endif  // WIN32
     70 
     71 #endif  // SFNTLY_CPP_SRC_SFNTLY_PORT_ATOMIC_H_
     72