utils.hpp 14.5 KB
Newer Older
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
/*****************************************************************************
 * utils.hpp: NPAPI utility functions
 *****************************************************************************
 * Copyright (C) 2015 VLC authors and VideoLAN
 * $Id$
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program 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 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifndef UTILS_NPP
#define UTILS_NPP

27 28 29
#include <array>
#include <cassert>
#include <cstring>
30
#include <memory>
31
#include <npruntime.h>
32
#include <string>
33 34
#include <tuple>
#include <type_traits>
35

36 37
using CStr = std::unique_ptr<char, void(*)(void*)>;

38 39 40
namespace npapi
{

41 42 43 44 45 46 47 48 49 50
// We want to handle both NPObject* and NPObject, though
// we don't want const char* to be converted to char.
// char* should be considered as const char*, const int as int...
namespace details
{
    // Remove the first pointer to allow std::remove_cv to process the type
    // instead of the pointer
    template <typename T>
    using PointerLess = typename std::remove_pointer<T>::type;

51
    // Remove const and volatile
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
    template <typename T>
    using Decayed = typename std::remove_cv<PointerLess<T>>::type;
}

template <typename T>
using TraitsType = typename std::conditional<
                        std::is_same<
                            details::Decayed<T>,
                            NPObject
                        >::value,
                        // Keep NPObject as this. The traits is using the raw pointerless type.
                        NPObject,
                        // Re-add the pointer if the type isn't NPObject & T was a pointer type
                        typename std::conditional<
                            std::is_pointer<T>::value,
                            typename std::add_pointer<details::Decayed<T>>::type,
                            details::Decayed<T>
                        >::type
                >::type;

using NPStringPtr = std::unique_ptr<NPUTF8, void(*)(void*)>;

inline bool is_null( const NPVariant& v )
{
    return NPVARIANT_IS_NULL( v );
}

inline bool is_number( const NPVariant& v )
{
    return NPVARIANT_IS_INT32(v)
        || NPVARIANT_IS_DOUBLE(v)
        || NPVARIANT_IS_STRING(v);
}

inline bool is_bool( const NPVariant &v )
{
    return NPVARIANT_IS_BOOLEAN( v ) ||
            is_number( v );
}

inline bool to_bool( const NPVariant& v )
{
    if( NPVARIANT_IS_BOOLEAN(v) )
    {
        return NPVARIANT_TO_BOOLEAN(v);
    }
    else if( NPVARIANT_IS_STRING(v) )
    {
100
        if( !strcmp( NPVARIANT_TO_STRING(v).UTF8Characters, "1" ) )
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
            return true;
    }
    else if ( NPVARIANT_IS_INT32(v) )
    {
        return NPVARIANT_TO_INT32(v) != 0;
    }
    else if ( NPVARIANT_IS_DOUBLE(v) )
    {
        return NPVARIANT_TO_DOUBLE(v) != .0;
    }
    return false;
}

inline bool is_string( const NPVariant& v )
{
    return NPVARIANT_IS_STRING( v );
}

inline NPStringPtr to_string( const NPVariant& v )
{
    auto s = NPVARIANT_TO_STRING( v );
    NPUTF8* buff = (NPUTF8*)NPN_MemAlloc(s.UTF8Length + 1);
    memcpy( buff, s.UTF8Characters, s.UTF8Length + 1 );
    return NPStringPtr( buff, NPN_MemFree );
}

// Returns the raw string, uncopied.
// The pointer becomes invalid as soon as "v" is destroyed
inline const NPUTF8* to_tmp_string( const NPVariant& v )
{
    return NPVARIANT_TO_STRING(v).UTF8Characters;
}

inline int32_t to_int( const NPVariant& v )
{
    if ( NPVARIANT_IS_INT32( v ) )
        return NPVARIANT_TO_INT32( v );
    else if ( NPVARIANT_IS_DOUBLE( v ) )
        return (int32_t)NPVARIANT_TO_DOUBLE( v );
    else if ( NPVARIANT_IS_STRING( v ) )
    {
        auto& s = NPVARIANT_TO_STRING( v );
        return atoi( s.UTF8Characters );
    }
    return 0;
}

inline double to_double( const NPVariant& v )
{
    if ( NPVARIANT_IS_DOUBLE( v ) )
        return NPVARIANT_TO_DOUBLE( v );
    else if ( NPVARIANT_IS_INT32( v ) )
        return (double)NPVARIANT_TO_INT32( v );
    else if ( NPVARIANT_IS_STRING( v ) )
    {
        auto& s = NPVARIANT_TO_STRING( v );
        return atof( s.UTF8Characters );
    }
    return .0;
}

162 163 164 165 166 167 168 169 170 171 172
// We don't want conversion of unknown types to work like any other types.
// This returns void, so if ( traits<std::vector<...>>::is() ) will fail to build.
// This is also true for conversions to & from types we don't support
template <typename T, typename Enable = void>
struct traits;

template <>
struct traits<std::nullptr_t>
{
    static bool is( const NPVariant& v )
    {
173
        return is_null( v );
174 175 176 177 178 179 180 181 182 183 184 185 186
    }

    static void from( std::nullptr_t, NPVariant& v )
    {
        NULL_TO_NPVARIANT( v );
    }
};

template <>
struct traits<bool>
{
    static bool is( const NPVariant& v )
    {
187
        return is_bool( v );
188 189 190 191
    }

    static bool to( const NPVariant& v )
    {
192
        return to_bool( v );
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    }

    static void from( bool b, NPVariant& v )
    {
        BOOLEAN_TO_NPVARIANT( b, v );
    }
};

template <typename T>
struct traits<T, typename std::enable_if<
        std::is_integral<T>::value &&
        !std::is_same<T, bool>::value
    >::type>
{
    static bool is( const NPVariant& v )
    {
209
        return is_number( v );
210 211 212 213
    }

    static int to( const NPVariant& v )
    {
214
        return to_int( v );
215 216 217 218 219 220 221 222 223
    }

    static void from( T i, NPVariant& v )
    {
        INT32_TO_NPVARIANT( (int)i, v );
    }

};
template <>
224
struct traits<NPObject>
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
{
    static bool is( const NPVariant& v )
    {
        return NPVARIANT_IS_OBJECT( v );
    }

    static NPObject* to( const NPVariant& v )
    {
        return NPVARIANT_TO_OBJECT( v );
    }

    static void from( NPObject* o, NPVariant& v )
    {
        NPN_RetainObject( o );
        OBJECT_TO_NPVARIANT( o, v );
    }
};

template <typename T>
struct traits<T, typename std::enable_if<
        std::is_floating_point<T>::value
    >::type>
{
    static bool is( const NPVariant& v )
    {
250
        return is_number( v );
251 252 253 254
    }

    static double to( const NPVariant& v )
    {
255
        return to_double( v );
256 257 258 259 260 261 262 263 264 265 266 267 268
    }

    static void from( T d, NPVariant& v )
    {
        DOUBLE_TO_NPVARIANT( (double)d, v );
    }
};

template <>
struct traits<NPString>
{
    static bool is( const NPVariant& v )
    {
269
        return is_string( v );
270 271 272 273 274 275 276
    }

    static NPString to( const NPVariant& v )
    {
        return NPVARIANT_TO_STRING( v );
    }

277
    static void from( const NPString s, NPVariant& v )
278
    {
279 280 281 282 283
        if ( s.UTF8Characters == nullptr )
        {
            NULL_TO_NPVARIANT( v );
            return;
        }
284 285 286
        auto raw = static_cast<NPUTF8*>( NPN_MemAlloc( s.UTF8Length + 1 ) );
        memcpy( raw, s.UTF8Characters, s.UTF8Length );
        raw[s.UTF8Length] = 0;
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        STRINGZ_TO_NPVARIANT( raw, v );
    }
};

template <>
struct traits<NPUTF8*>
{
    static bool is( const NPVariant& v )
    {
        return is_string( v );
    }

    static const NPUTF8* to( const NPVariant& v )
    {
        return to_tmp_string( v );
    }

304
    static void from( const NPUTF8* str, NPVariant& v )
305
    {
306 307 308 309 310
        if ( str == nullptr )
        {
            NULL_TO_NPVARIANT( v );
            return;
        }
311 312 313
        auto len = strlen(str);
        auto copy = static_cast<NPUTF8*>( NPN_MemAlloc( len + 1 ) );
        strcpy(copy, str);
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        STRINGZ_TO_NPVARIANT( copy, v );
    }
};

template <>
struct traits<std::string>
{
    static bool is( const NPVariant& v )
    {
        return is_string( v );
    }

    static std::string to( const NPVariant& v )
    {
        return std::string( to_tmp_string( v ) );
    }

    static void from( const std::string& str, NPVariant& v )
    {
333
        traits<char*>::from( str.c_str(), v );
334 335 336
    }
};

337
namespace details
338
{
339 340 341 342 343 344 345 346 347 348 349
namespace policy
{
struct Embeded
{
    using VariantType = NPVariant;

    Embeded()
    {
        memset( &v, 0, sizeof( v ) );
    }

350 351 352 353
    Embeded( const Embeded& e )
    {
        copyAndRetain( e.v );
    }
354

355 356 357 358
    Embeded& operator=( const Embeded& e )
    {
        release();
        copyAndRetain( e.v );
359
        return *this;
360
    }
361

362
    Embeded( Embeded&& e ) noexcept
363
    {
364 365
        v = e.v;
        memset( &e.v, 0, sizeof( e.v ) );
366 367
    }

368
    Embeded& operator=(Embeded&& e) noexcept
369
    {
370
        release();
371 372
        v = e.v;
        memset( &e.v, 0, sizeof( e.v ) );
373
        return *this;
374 375 376
    }

    Embeded( const NPVariant& npv )
377
    {
378
        copyAndRetain( npv );
379 380 381 382
    }

    ~Embeded()
    {
383
        release();
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    }

    NPVariant* ptr()
    {
        return &v;
    }

    const NPVariant* ptr() const
    {
        return &v;
    }

    NPVariant& ref()
    {
        return v;
    }

    const NPVariant& ref() const
    {
        return v;
    }

    NPVariant v;
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

private:
    void release()
    {
        NPN_ReleaseVariantValue( &v );
    }

    void copyAndRetain( const NPVariant& npv )
    {
        if ( traits<NPString>::is( npv ) == true )
        {
            traits<NPString>::from( traits<NPString>::to( npv ), v );
        }
        else
        {
            memcpy( &v, &npv, sizeof( v ) );
            if ( traits<NPObject>::is( npv ) == true )
                NPN_RetainObject( traits<NPObject>::to( v ) );
        }
    }
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
};

///
/// \brief This storage policy is meant to wrap an output variant.
/// This means we don't have to release the content upon destruction, and mostly
/// care about storing a pointer upon construction.
///
struct Wrapped
{
    using VariantType = NPVariant*;

    Wrapped() = default;

    Wrapped( NPVariant* vt )
        : v( vt )
    {
        memset( v, 0, sizeof( *v ) );
    }

    // We don't want to release anything, as NPAPI will use the Wrapped NPVariant
    // we are currently writing to.
    ~Wrapped() = default;

    Wrapped( const Wrapped& ) = delete;
    Wrapped& operator=( const Wrapped& ) = delete;

453
    Wrapped(Wrapped&& w) noexcept
454 455 456 457
    {
        *this = std::move( w );
    }

458
    Wrapped& operator=( Wrapped&& w ) noexcept
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    {
        v = w.v;
        w.v = nullptr;
        return *this;
    }

    NPVariant* ptr()
    {
        return v;
    }

    const NPVariant* ptr() const
    {
        return v;
    }

    NPVariant& ref()
    {
        return *v;
    }

    const NPVariant& ref() const
    {
        return *v;
    }

    NPVariant* v;
};

}

template <typename StoragePolicy = details::policy::Embeded>
class Variant
{
public:
    Variant() = default;
    // Let the storage policy handle the resources release.
    ~Variant() = default;

    //FIXME: This results in a reference to pointer for the Wrapped policy.
    // That's an unneeded indirection
    Variant( const typename StoragePolicy::VariantType& v )
501 502 503 504
        : m_variant( v )
    {
    }

505 506
    Variant( const Variant& v ) = default;
    Variant& operator=( const Variant& v ) = default;
507 508

    template <typename T>
509
    explicit Variant(const T& t)
510
    {
511
        traits<TraitsType<T>>::from( t, m_variant.ref() );
512 513 514
    }


515
#ifndef _MSC_VER
516
    Variant(Variant&& v) = default;
517
    Variant& operator=(Variant&& v) = default;
518 519 520 521 522
#else
    Variant(Variant&& v)
        : m_variant( std::move( v.m_variant ) )
    {
    }
523 524 525

    Variant& operator=(Variant&& v)
    {
526 527
        m_variant = std::move( v.m_variant );
        return *this;
528
    }
529
#endif
530

531 532 533
    template <typename T>
    bool is() const
    {
534
        return traits<TraitsType<T>>::is( m_variant.ref() );
535 536 537 538 539 540 541 542
    }

    // /!\ Warning /!\ This does not retain the value for strings & objects
    // If you wish to hold on to this value, build a new Variant so it becomes
    // managed
    template <typename T>
    operator T() const
    {
543 544
        assert(traits<TraitsType<T>>::is( m_variant.ref() ));
        return traits<TraitsType<T>>::to( m_variant.ref() );
545 546
    }

547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    // Enable by value parameter for pointers & fundamental type
    template <typename T>
    typename std::enable_if<
        std::is_fundamental<T>::value ||
        std::is_pointer<T>::value,
    Variant>::type &
    operator=(const T t)
    {
        traits<TraitsType<T>>::from( t, m_variant.ref() );
        return *this;
    }

    // By const-ref parameter passing for bigger & non-pointer types
    template <typename T>
    typename std::enable_if<
        !std::is_fundamental<T>::value &&
        !std::is_pointer<T>::value,
    Variant>::type &
    operator=(const T& t)
    {
        traits<TraitsType<T>>::from( t, m_variant.ref() );
        return *this;
    }

571 572
    operator const NPVariant() const
    {
573
        return m_variant.ref();
574 575 576 577
    }

    operator const NPVariant*() const
    {
578
        return m_variant.ptr();
579 580
    }

581 582
    operator NPVariant*()
    {
583
        return m_variant.ptr();
584 585
    }

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
    template <typename T>
    bool operator<(const T& rhs) const
    {
        return (const T)*this < rhs;
    }

    template <typename T>
    bool operator<=(const T& rhs) const
    {
        return (const T)*this <= rhs;
    }

    template <typename T>
    bool operator>(const T& rhs) const
    {
        return (const T)*this > rhs;
    }

    template <typename T>
    bool operator>=(const T& rhs) const
    {
        return (const T)*this >= rhs;
    }

610
private:
611
    StoragePolicy m_variant;
612 613
};

614 615
}

616 617
using Variant = details::Variant<details::policy::Embeded>;
using OutVariant = details::Variant<details::policy::Wrapped>;
618

619
namespace details
620
{
621 622
    template <size_t... Ns>
    struct Seq
623
    {
624 625
        using type = Seq<Ns..., sizeof...(Ns)>;
    };
626

627 628
    template <size_t N>
    struct GenSeq
629
    {
630 631 632 633 634
        // This will recurse down to Seq<> which yields type = Seq<0>
        // Then, from Seq<0>::type, up to Seq<N-1>::type, which ends
        // up generating Seq<0, 1, ... N>
        using type = typename GenSeq<N - 1>::type::type;
    };
635

636 637
    template <>
    struct GenSeq<0>
638
    {
639 640
        using type = Seq<>;
    };
641

642 643
    template <typename Tuple, size_t... Indices>
    std::array<npapi::Variant, sizeof...(Indices)> wrap( const Tuple& t, Seq<Indices...> )
644
    {
645
        return { npapi::Variant( std::get<Indices>( t ) )... };
646 647 648 649
    }
}

template <typename... Args>
650
std::array<Variant, sizeof...(Args)> wrap( const std::tuple<Args...>& args )
651
{
652
    return details::wrap( args, typename details::GenSeq<sizeof...(Args)>::type{} );
653 654 655 656 657 658
}

}

#endif // UTILS_NPP