utils.hpp 16 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 27 28 29
/*****************************************************************************
 * 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

#include <npruntime.h>
#include <memory>
#include <type_traits>
30
#include <string>
31

32
#include <cstring>
33
#include <cassert>
34

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

37 38 39
namespace npapi
{

40 41 42 43 44 45 46 47 48 49
// 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;

50
    // Remove const and volatile
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
    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) )
    {
99
        if( !strcmp( NPVARIANT_TO_STRING(v).UTF8Characters, "1" ) )
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
            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;
}

161 162 163 164 165 166 167 168 169 170 171
// 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 )
    {
172
        return is_null( v );
173 174 175 176 177 178 179 180 181 182 183 184 185
    }

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

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

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

    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 )
    {
208
        return is_number( v );
209 210 211 212
    }

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

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

};
template <>
223
struct traits<NPObject>
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
{
    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 )
    {
249
        return is_number( v );
250 251 252 253
    }

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

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

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

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

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

303
    static void from( const NPUTF8* str, NPVariant& v )
304
    {
305 306 307 308 309
        if ( str == nullptr )
        {
            NULL_TO_NPVARIANT( v );
            return;
        }
310 311 312
        auto len = strlen(str);
        auto copy = static_cast<NPUTF8*>( NPN_MemAlloc( len + 1 ) );
        strcpy(copy, str);
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        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 )
    {
332
        traits<char*>::from( str.c_str(), v );
333 334 335
    }
};

336
namespace details
337
{
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
namespace policy
{
struct Embeded
{
    using VariantType = NPVariant;

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

    Embeded( const Embeded& ) = default;

    // Allow btiwise copy, assuming that the called has handled releasing
    // previously held resources
    Embeded& operator=( const Embeded& ) = default;

    Embeded( Embeded&& e )
356 357 358 359 360
    {
        *this = std::move(e);
    }

    Embeded& operator=(Embeded&& e)
361 362 363
    {
        v = e.v;
        memset( &e.v, 0, sizeof( e.v ) );
364
        return *this;
365 366 367
    }

    Embeded( const NPVariant& npv )
368
    {
369
        memcpy( &v, &npv, sizeof( npv ) );
370 371
    }

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 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 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    Embeded& operator=( const NPVariant& npv )
    {
        memcpy( &v, &npv, sizeof( npv ) );
        return *this;
    }

    ~Embeded()
    {
        NPN_ReleaseVariantValue( &v );
    }

    NPVariant* ptr()
    {
        return &v;
    }

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

    NPVariant& ref()
    {
        return v;
    }

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

    NPVariant v;
};

///
/// \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;

    Wrapped(Wrapped&& w)
    {
        *this = std::move( w );
    }

    Wrapped& operator=( Wrapped&& w )
    {
        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 )
478 479
        : m_variant( v )
    {
480
        retainOrCopy();
481 482 483
    }

    Variant(const Variant& v)
484
        : m_variant( v.m_variant )
485
    {
486
        retainOrCopy();
487 488 489
    }

    template <typename T>
490
    explicit Variant(const T& t)
491
    {
492
        traits<TraitsType<T>>::from( t, m_variant.ref() );
493 494 495 496 497 498 499
    }

    Variant& operator=(const Variant& v)
    {
        if ( &v == this )
            return *this;
        release();
500

501
        m_variant = v.m_variant;
502 503
        retainOrCopy();

504 505 506
        return *this;
    }

507
#ifndef _MSC_VER
508
    Variant(Variant&& v) = default;
509 510 511 512 513 514
#else
    Variant(Variant&& v)
        : m_variant( std::move( v.m_variant ) )
    {
    }
#endif
515 516 517 518

    Variant& operator=(Variant&& v)
    {
        release();
519 520
        m_variant = std::move( v.m_variant );
        return *this;
521 522
    }

523

524 525 526
    template <typename T>
    bool is() const
    {
527
        return traits<TraitsType<T>>::is( m_variant.ref() );
528 529 530 531 532 533 534 535
    }

    // /!\ 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
    {
536 537
        assert(traits<TraitsType<T>>::is( m_variant.ref() ));
        return traits<TraitsType<T>>::to( m_variant.ref() );
538 539
    }

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    // 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;
    }

564 565
    operator const NPVariant() const
    {
566
        return m_variant.ref();
567 568 569 570
    }

    operator const NPVariant*() const
    {
571
        return m_variant.ptr();
572 573
    }

574 575
    operator NPVariant*()
    {
576
        return m_variant.ptr();
577 578
    }

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
    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;
    }

603
    void release()
604
    {
605
        NPN_ReleaseVariantValue( m_variant.ptr() );
606 607
    }

608 609
private:
    void retainOrCopy()
610
    {
611 612 613 614
        if (is<NPObject>())
            NPN_RetainObject( *this );
        else if (is<NPString>())
            traits<NPString>::from( (NPString)*this, m_variant.ref() );
615 616 617
    }

private:
618
    StoragePolicy m_variant;
619 620
};

621 622
}

623 624
using Variant = details::Variant<details::policy::Embeded>;
using OutVariant = details::Variant<details::policy::Wrapped>;
625

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
class VariantArray
{
    using VPtr = std::unique_ptr<Variant[]>;
public:
    VariantArray()
        : m_variants( nullptr )
        , m_size( 0 )
    {
    }
    VariantArray(unsigned int nbValue)
        : m_variants( VPtr( new Variant[nbValue] ) )
        , m_size( nbValue )
    {
    }

    Variant& operator[](size_t idx)
    {
        return m_variants[idx];
    }

    const Variant& operator[](size_t idx) const
    {
        return m_variants[idx];
    }

    // Warning: this assumes the same binary layout between Variant & NPVariant
    operator NPVariant*()
    {
        return (NPVariant*)m_variants.get();
    }

    operator const NPVariant*() const
    {
        return (const NPVariant*)m_variants.get();
    }

    size_t size() const
    {
        return m_size;
    }

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    VariantArray(const VariantArray&) = delete;
    VariantArray& operator=(const VariantArray&) = delete;
#ifndef _MSC_VER
    VariantArray(VariantArray&&) = default;
    VariantArray& operator=(VariantArray&&) = default;
#else
    VariantArray(VariantArray&& v)
        : m_variants(std::move( v.m_variants ) )
        , m_size( v.m_size )
    {
    }

    VariantArray& operator=(VariantArray&& v)
    {
        if (&v == this)
            return *this;
        m_variants = std::move(v.m_variants);
        m_size = v.m_size;
    }

#endif
688 689 690 691 692 693 694 695
private:
    VPtr m_variants;
    size_t m_size;
};

// Private implementation namespace
namespace details
{
696
    template <size_t Idx, typename T>
697 698
    void wrap( VariantArray& array, T arg )
    {
699
        array[Idx] = Variant<details::policy::Embeded>(arg);
700 701
    }

702
    template <size_t Idx, typename T, typename... Args>
703
    void wrap( VariantArray& array, T arg, Args&&... args )
704 705
    {
        wrap<Idx + 1>( array, std::forward<Args>( args )... );
706 707 708
        // This needs the Variant wrapper to be the exact size of a NPVariant
        // For future proofness, we make this explicit:
        array[Idx] = Variant<details::policy::Embeded>(arg);
709 710 711 712 713 714 715
    }
}

// public entry point. Responsible for allocating the array and initializing
// the template index parameter (to avoid filling to array in reverse order with
// sizeof...()
template <typename... Args>
716
VariantArray wrap(Args&&... args)
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
{
    auto array = VariantArray{sizeof...(args)};
    details::wrap<0>( array, std::forward<Args>( args )... );
    return array;
}

inline VariantArray wrap()
{
    return VariantArray{};
}

}

#endif // UTILS_NPP