DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (5350524bb654)

VCS Links

Line Code
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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 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 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 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 564 565 566 567 568 569 570 571 572 573 574 575 576 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 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 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 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *
 * This Original Code has been modified by IBM Corporation.
 * Modifications made by IBM described herein are
 * Copyright (c) International Business Machines
 * Corporation, 2000
 *
 * Modifications to Mozilla code or documentation
 * identified per MPL Section 3.3
 *
 * Date         Modified by     Description of modification
 * 03/27/2000   IBM Corp.       Added PR_CALLBACK for Optlink
 *                               use in OS2
 */

/*

  This file provides the implementation for the RDF service manager.

  TO DO
  -----

  1) Implement the CreateDataBase() methods.

  2) Cache date and int literals.

 */

#include "nsRDFService.h"
#include "nsCOMPtr.h"
#include "nsAutoPtr.h"
#include "nsMemory.h"
#include "nsIAtom.h"
#include "nsIComponentManager.h"
#include "nsIRDFDataSource.h"
#include "nsIRDFNode.h"
#include "nsIRDFRemoteDataSource.h"
#include "nsIServiceManager.h"
#include "nsIFactory.h"
#include "nsRDFCID.h"
#include "nsString.h"
#include "nsXPIDLString.h"
#include "nsNetUtil.h"
#include "nsIURI.h"
#include "PLDHashTable.h"
#include "plhash.h"
#include "plstr.h"
#include "mozilla/Logging.h"
#include "prprf.h"
#include "prmem.h"
#include "rdf.h"
#include "nsCRT.h"
#include "nsCRTGlue.h"
#include "mozilla/HashFunctions.h"

using namespace mozilla;

////////////////////////////////////////////////////////////////////////

static NS_DEFINE_CID(kRDFXMLDataSourceCID,    NS_RDFXMLDATASOURCE_CID);
static NS_DEFINE_CID(kRDFDefaultResourceCID,  NS_RDFDEFAULTRESOURCE_CID);

static NS_DEFINE_IID(kIRDFLiteralIID,         NS_IRDFLITERAL_IID);
static NS_DEFINE_IID(kIRDFDateIID,         NS_IRDFDATE_IID);
static NS_DEFINE_IID(kIRDFIntIID,         NS_IRDFINT_IID);
static NS_DEFINE_IID(kIRDFNodeIID,            NS_IRDFNODE_IID);
static NS_DEFINE_IID(kISupportsIID,           NS_ISUPPORTS_IID);

static LazyLogModule gLog("nsRDFService");

class BlobImpl;

// These functions are copied from nsprpub/lib/ds/plhash.c, with one
// change to free the key in DataSourceFreeEntry.
// XXX sigh, why were DefaultAllocTable et. al. declared static, anyway?

static void *
DataSourceAllocTable(void *pool, size_t size)
{
    return PR_MALLOC(size);
}

static void
DataSourceFreeTable(void *pool, void *item)
{
    PR_Free(item);
}

static PLHashEntry *
DataSourceAllocEntry(void *pool, const void *key)
{
    return PR_NEW(PLHashEntry);
}

static void
DataSourceFreeEntry(void *pool, PLHashEntry *he, unsigned flag)
{
    if (flag == HT_FREE_ENTRY) {
        PL_strfree((char*) he->key);
        PR_Free(he);
    }
}

static PLHashAllocOps dataSourceHashAllocOps = {
    DataSourceAllocTable, DataSourceFreeTable,
    DataSourceAllocEntry, DataSourceFreeEntry
};

//----------------------------------------------------------------------
//
// For the mResources hashtable.
//

struct ResourceHashEntry : public PLDHashEntryHdr {
    const char *mKey;
    nsIRDFResource *mResource;

    static PLDHashNumber
    HashKey(const void *key)
    {
        return HashString(static_cast<const char *>(key));
    }

    static bool
    MatchEntry(const PLDHashEntryHdr *hdr, const void *key)
    {
        const ResourceHashEntry *entry =
            static_cast<const ResourceHashEntry *>(hdr);

        return 0 == nsCRT::strcmp(static_cast<const char *>(key),
                                  entry->mKey);
    }
};

static const PLDHashTableOps gResourceTableOps = {
    ResourceHashEntry::HashKey,
    ResourceHashEntry::MatchEntry,
    PLDHashTable::MoveEntryStub,
    PLDHashTable::ClearEntryStub,
    nullptr
};

// ----------------------------------------------------------------------
//
// For the mLiterals hashtable.
//

struct LiteralHashEntry : public PLDHashEntryHdr {
    nsIRDFLiteral *mLiteral;
    const char16_t *mKey;

    static PLDHashNumber
    HashKey(const void *key)
    {
        return HashString(static_cast<const char16_t *>(key));
    }

    static bool
    MatchEntry(const PLDHashEntryHdr *hdr, const void *key)
    {
        const LiteralHashEntry *entry =
            static_cast<const LiteralHashEntry *>(hdr);

        return 0 == nsCRT::strcmp(static_cast<const char16_t *>(key),
                                  entry->mKey);
    }
};

static const PLDHashTableOps gLiteralTableOps = {
    LiteralHashEntry::HashKey,
    LiteralHashEntry::MatchEntry,
    PLDHashTable::MoveEntryStub,
    PLDHashTable::ClearEntryStub,
    nullptr
};

// ----------------------------------------------------------------------
//
// For the mInts hashtable.
//

struct IntHashEntry : public PLDHashEntryHdr {
    nsIRDFInt *mInt;
    int32_t    mKey;

    static PLDHashNumber
    HashKey(const void *key)
    {
        return PLDHashNumber(*static_cast<const int32_t *>(key));
    }

    static bool
    MatchEntry(const PLDHashEntryHdr *hdr, const void *key)
    {
        const IntHashEntry *entry =
            static_cast<const IntHashEntry *>(hdr);

        return *static_cast<const int32_t *>(key) == entry->mKey;
    }
};

static const PLDHashTableOps gIntTableOps = {
    IntHashEntry::HashKey,
    IntHashEntry::MatchEntry,
    PLDHashTable::MoveEntryStub,
    PLDHashTable::ClearEntryStub,
    nullptr
};

// ----------------------------------------------------------------------
//
// For the mDates hashtable.
//

struct DateHashEntry : public PLDHashEntryHdr {
    nsIRDFDate *mDate;
    PRTime      mKey;

    static PLDHashNumber
    HashKey(const void *key)
    {
        // xor the low 32 bits with the high 32 bits.
        PRTime t = *static_cast<const PRTime *>(key);
        int32_t h32 = int32_t(t >> 32);
        int32_t l32 = int32_t(0xffffffff & t);
        return PLDHashNumber(l32 ^ h32);
    }

    static bool
    MatchEntry(const PLDHashEntryHdr *hdr, const void *key)
    {
        const DateHashEntry *entry =
            static_cast<const DateHashEntry *>(hdr);

        return *static_cast<const PRTime *>(key) == entry->mKey;
    }
};

static const PLDHashTableOps gDateTableOps = {
    DateHashEntry::HashKey,
    DateHashEntry::MatchEntry,
    PLDHashTable::MoveEntryStub,
    PLDHashTable::ClearEntryStub,
    nullptr
};

class BlobImpl : public nsIRDFBlob
{
public:
    struct Data {
        int32_t  mLength;
        uint8_t *mBytes;
    };

    BlobImpl(const uint8_t *aBytes, int32_t aLength)
    {
        mData.mLength = aLength;
        mData.mBytes = new uint8_t[aLength];
        memcpy(mData.mBytes, aBytes, aLength);
        NS_ADDREF(RDFServiceImpl::gRDFService);
        RDFServiceImpl::gRDFService->RegisterBlob(this);
    }

protected:
    virtual ~BlobImpl()
    {
        RDFServiceImpl::gRDFService->UnregisterBlob(this);
        // Use NS_RELEASE2() here, because we want to decrease the
        // refcount, but not null out the gRDFService pointer (which is
        // what a vanilla NS_RELEASE() would do).
        nsrefcnt refcnt;
        NS_RELEASE2(RDFServiceImpl::gRDFService, refcnt);
        delete[] mData.mBytes;
    }

public:
    NS_DECL_ISUPPORTS
    NS_DECL_NSIRDFNODE
    NS_DECL_NSIRDFBLOB

    Data mData;
};

NS_IMPL_ISUPPORTS(BlobImpl, nsIRDFNode, nsIRDFBlob)

NS_IMETHODIMP
BlobImpl::EqualsNode(nsIRDFNode *aNode, bool *aEquals)
{
    nsCOMPtr<nsIRDFBlob> blob = do_QueryInterface(aNode);
    if (blob) {
        int32_t length;
        blob->GetLength(&length);

        if (length == mData.mLength) {
            const uint8_t *bytes;
            blob->GetValue(&bytes);

            if (0 == memcmp(bytes, mData.mBytes, length)) {
                *aEquals = true;
                return NS_OK;
            }
        }
    }

    *aEquals = false;
    return NS_OK;
}

NS_IMETHODIMP
BlobImpl::GetValue(const uint8_t **aResult)
{
    *aResult = mData.mBytes;
    return NS_OK;
}

NS_IMETHODIMP
BlobImpl::GetLength(int32_t *aResult)
{
    *aResult = mData.mLength;
    return NS_OK;
}

// ----------------------------------------------------------------------
//
// For the mBlobs hashtable.
//

struct BlobHashEntry : public PLDHashEntryHdr {
    BlobImpl *mBlob;

    static PLDHashNumber
    HashKey(const void *key)
    {
        const BlobImpl::Data *data =
            static_cast<const BlobImpl::Data *>(key);
        return HashBytes(data->mBytes, data->mLength);
    }

    static bool
    MatchEntry(const PLDHashEntryHdr *hdr, const void *key)
    {
        const BlobHashEntry *entry =
            static_cast<const BlobHashEntry *>(hdr);

        const BlobImpl::Data *left = &entry->mBlob->mData;

        const BlobImpl::Data *right =
            static_cast<const BlobImpl::Data *>(key);

        return (left->mLength == right->mLength)
            && 0 == memcmp(left->mBytes, right->mBytes, right->mLength);
    }
};

static const PLDHashTableOps gBlobTableOps = {
    BlobHashEntry::HashKey,
    BlobHashEntry::MatchEntry,
    PLDHashTable::MoveEntryStub,
    PLDHashTable::ClearEntryStub,
    nullptr
};

////////////////////////////////////////////////////////////////////////
// LiteralImpl
//
//   Currently, all literals are implemented exactly the same way;
//   i.e., there is are no resource factories to allow you to generate
//   customer resources. I doubt that makes sense, anyway.
//
class LiteralImpl : public nsIRDFLiteral {
public:
    static nsresult
    Create(const char16_t* aValue, nsIRDFLiteral** aResult);

    // nsISupports
    NS_DECL_THREADSAFE_ISUPPORTS

    // nsIRDFNode
    NS_DECL_NSIRDFNODE

    // nsIRDFLiteral
    NS_DECL_NSIRDFLITERAL

protected:
    explicit LiteralImpl(const char16_t* s);
    virtual ~LiteralImpl();

    const char16_t* GetValue() const {
        size_t objectSize = ((sizeof(LiteralImpl) + sizeof(char16_t) - 1) / sizeof(char16_t)) * sizeof(char16_t);
        return reinterpret_cast<const char16_t*>(reinterpret_cast<const unsigned char*>(this) + objectSize);
    }
};


nsresult
LiteralImpl::Create(const char16_t* aValue, nsIRDFLiteral** aResult)
{
    // Goofy math to get alignment right. Copied from nsSharedString.h.
    size_t objectSize = ((sizeof(LiteralImpl) + sizeof(char16_t) - 1) / sizeof(char16_t)) * sizeof(char16_t);
    size_t stringLen = nsCharTraits<char16_t>::length(aValue);
    size_t stringSize = (stringLen + 1) * sizeof(char16_t);

    void* objectPtr = operator new(objectSize + stringSize);
    if (! objectPtr)
        return NS_ERROR_NULL_POINTER;

    char16_t* buf = reinterpret_cast<char16_t*>(static_cast<unsigned char*>(objectPtr) + objectSize);
    nsCharTraits<char16_t>::copy(buf, aValue, stringLen + 1);

    NS_ADDREF(*aResult = new (objectPtr) LiteralImpl(buf));
    return NS_OK;
}


LiteralImpl::LiteralImpl(const char16_t* s)
{
    RDFServiceImpl::gRDFService->RegisterLiteral(this);
    NS_ADDREF(RDFServiceImpl::gRDFService);
}

LiteralImpl::~LiteralImpl()
{
    RDFServiceImpl::gRDFService->UnregisterLiteral(this);

    // Use NS_RELEASE2() here, because we want to decrease the
    // refcount, but not null out the gRDFService pointer (which is
    // what a vanilla NS_RELEASE() would do).
    nsrefcnt refcnt;
    NS_RELEASE2(RDFServiceImpl::gRDFService, refcnt);
}

NS_IMPL_ADDREF(LiteralImpl)
NS_IMPL_RELEASE(LiteralImpl)

nsresult
LiteralImpl::QueryInterface(REFNSIID iid, void** result)
{
    if (! result)
        return NS_ERROR_NULL_POINTER;

    *result = nullptr;
    if (iid.Equals(kIRDFLiteralIID) ||
        iid.Equals(kIRDFNodeIID) ||
        iid.Equals(kISupportsIID)) {
        *result = static_cast<nsIRDFLiteral*>(this);
        AddRef();
        return NS_OK;
    }
    return NS_NOINTERFACE;
}

NS_IMETHODIMP
LiteralImpl::EqualsNode(nsIRDFNode* aNode, bool* aResult)
{
    nsresult rv;
    nsIRDFLiteral* literal;
    rv = aNode->QueryInterface(kIRDFLiteralIID, (void**) &literal);
    if (NS_SUCCEEDED(rv)) {
        *aResult = (static_cast<nsIRDFLiteral*>(this) == literal);
        NS_RELEASE(literal);
        return NS_OK;
    }
    else if (rv == NS_NOINTERFACE) {
        *aResult = false;
        return NS_OK;
    }
    else {
        return rv;
    }
}

NS_IMETHODIMP
LiteralImpl::GetValue(char16_t* *value)
{
    NS_ASSERTION(value, "null ptr");
    if (! value)
        return NS_ERROR_NULL_POINTER;

    const char16_t *temp = GetValue();
    *value = temp? NS_strdup(temp) : 0;
    return NS_OK;
}


NS_IMETHODIMP
LiteralImpl::GetValueConst(const char16_t** aValue)
{
    *aValue = GetValue();
    return NS_OK;
}

////////////////////////////////////////////////////////////////////////
// DateImpl
//

class DateImpl : public nsIRDFDate {
public:
    explicit DateImpl(const PRTime s);

    // nsISupports
    NS_DECL_ISUPPORTS

    // nsIRDFNode
    NS_DECL_NSIRDFNODE

    // nsIRDFDate
    NS_IMETHOD GetValue(PRTime *value) override;

private:
    virtual ~DateImpl();

    nsresult EqualsDate(nsIRDFDate* date, bool* result);
    PRTime mValue;
};


DateImpl::DateImpl(const PRTime s)
    : mValue(s)
{
    RDFServiceImpl::gRDFService->RegisterDate(this);
    NS_ADDREF(RDFServiceImpl::gRDFService);
}

DateImpl::~DateImpl()
{
    RDFServiceImpl::gRDFService->UnregisterDate(this);

    // Use NS_RELEASE2() here, because we want to decrease the
    // refcount, but not null out the gRDFService pointer (which is
    // what a vanilla NS_RELEASE() would do).
    nsrefcnt refcnt;
    NS_RELEASE2(RDFServiceImpl::gRDFService, refcnt);
}

NS_IMPL_ADDREF(DateImpl)
NS_IMPL_RELEASE(DateImpl)

nsresult
DateImpl::QueryInterface(REFNSIID iid, void** result)
{
    if (! result)
        return NS_ERROR_NULL_POINTER;

    *result = nullptr;
    if (iid.Equals(kIRDFDateIID) ||
        iid.Equals(kIRDFNodeIID) ||
        iid.Equals(kISupportsIID)) {
        *result = static_cast<nsIRDFDate*>(this);
        AddRef();
        return NS_OK;
    }
    return NS_NOINTERFACE;
}

NS_IMETHODIMP
DateImpl::EqualsNode(nsIRDFNode* node, bool* result)
{
    nsresult rv;
    nsIRDFDate* date;
    if (NS_SUCCEEDED(node->QueryInterface(kIRDFDateIID, (void**) &date))) {
        rv = EqualsDate(date, result);
        NS_RELEASE(date);
    }
    else {
        *result = false;
        rv = NS_OK;
    }
    return rv;
}

NS_IMETHODIMP
DateImpl::GetValue(PRTime *value)
{
    NS_ASSERTION(value, "null ptr");
    if (! value)
        return NS_ERROR_NULL_POINTER;

    *value = mValue;
    return NS_OK;
}


nsresult
DateImpl::EqualsDate(nsIRDFDate* date, bool* result)
{
    NS_ASSERTION(date && result, "null ptr");
    if (!date || !result)
        return NS_ERROR_NULL_POINTER;

    nsresult rv;
    PRTime p;
    if (NS_FAILED(rv = date->GetValue(&p)))
        return rv;

    *result = p == mValue;
    return NS_OK;
}

////////////////////////////////////////////////////////////////////////
// IntImpl
//

class IntImpl : public nsIRDFInt {
public:
    explicit IntImpl(int32_t s);

    // nsISupports
    NS_DECL_ISUPPORTS

    // nsIRDFNode
    NS_DECL_NSIRDFNODE

    // nsIRDFInt
    NS_IMETHOD GetValue(int32_t *value) override;

private:
    virtual ~IntImpl();

    nsresult EqualsInt(nsIRDFInt* value, bool* result);
    int32_t mValue;
};


IntImpl::IntImpl(int32_t s)
    : mValue(s)
{
    RDFServiceImpl::gRDFService->RegisterInt(this);
    NS_ADDREF(RDFServiceImpl::gRDFService);
}

IntImpl::~IntImpl()
{
    RDFServiceImpl::gRDFService->UnregisterInt(this);

    // Use NS_RELEASE2() here, because we want to decrease the
    // refcount, but not null out the gRDFService pointer (which is
    // what a vanilla NS_RELEASE() would do).
    nsrefcnt refcnt;
    NS_RELEASE2(RDFServiceImpl::gRDFService, refcnt);
}

NS_IMPL_ADDREF(IntImpl)
NS_IMPL_RELEASE(IntImpl)

nsresult
IntImpl::QueryInterface(REFNSIID iid, void** result)
{
    if (! result)
        return NS_ERROR_NULL_POINTER;

    *result = nullptr;
    if (iid.Equals(kIRDFIntIID) ||
        iid.Equals(kIRDFNodeIID) ||
        iid.Equals(kISupportsIID)) {
        *result = static_cast<nsIRDFInt*>(this);
        AddRef();
        return NS_OK;
    }
    return NS_NOINTERFACE;
}

NS_IMETHODIMP
IntImpl::EqualsNode(nsIRDFNode* node, bool* result)
{
    nsresult rv;
    nsIRDFInt* intValue;
    if (NS_SUCCEEDED(node->QueryInterface(kIRDFIntIID, (void**) &intValue))) {
        rv = EqualsInt(intValue, result);
        NS_RELEASE(intValue);
    }
    else {
        *result = false;
        rv = NS_OK;
    }
    return rv;
}

NS_IMETHODIMP
IntImpl::GetValue(int32_t *value)
{
    NS_ASSERTION(value, "null ptr");
    if (! value)
        return NS_ERROR_NULL_POINTER;

    *value = mValue;
    return NS_OK;
}


nsresult
IntImpl::EqualsInt(nsIRDFInt* intValue, bool* result)
{
    NS_ASSERTION(intValue && result, "null ptr");
    if (!intValue || !result)
        return NS_ERROR_NULL_POINTER;

    nsresult rv;
    int32_t p;
    if (NS_FAILED(rv = intValue->GetValue(&p)))
        return rv;

    *result = (p == mValue);
    return NS_OK;
}

////////////////////////////////////////////////////////////////////////
// RDFServiceImpl

RDFServiceImpl*
RDFServiceImpl::gRDFService;

RDFServiceImpl::RDFServiceImpl()
    : mNamedDataSources(nullptr)
    , mResources(&gResourceTableOps, sizeof(ResourceHashEntry))
    , mLiterals(&gLiteralTableOps, sizeof(LiteralHashEntry))
    , mInts(&gIntTableOps, sizeof(IntHashEntry))
    , mDates(&gDateTableOps, sizeof(DateHashEntry))
    , mBlobs(&gBlobTableOps, sizeof(BlobHashEntry))
{
    gRDFService = this;
}

nsresult
RDFServiceImpl::Init()
{
    nsresult rv;

    mNamedDataSources = PL_NewHashTable(23,
                                        PL_HashString,
                                        PL_CompareStrings,
                                        PL_CompareValues,
                                        &dataSourceHashAllocOps, nullptr);

    if (! mNamedDataSources)
        return NS_ERROR_OUT_OF_MEMORY;

    mDefaultResourceFactory = do_GetClassObject(kRDFDefaultResourceCID, &rv);
    NS_ASSERTION(NS_SUCCEEDED(rv), "unable to get default resource factory");
    if (NS_FAILED(rv)) return rv;

    return NS_OK;
}


RDFServiceImpl::~RDFServiceImpl()
{
    if (mNamedDataSources) {
        PL_HashTableDestroy(mNamedDataSources);
        mNamedDataSources = nullptr;
    }
    gRDFService = nullptr;
}


// static
nsresult
RDFServiceImpl::CreateSingleton(nsISupports* aOuter,
                                const nsIID& aIID, void **aResult)
{
    NS_ENSURE_NO_AGGREGATION(aOuter);

    if (gRDFService) {
        NS_ERROR("Trying to create RDF serviec twice.");
        return gRDFService->QueryInterface(aIID, aResult);
    }

    RefPtr<RDFServiceImpl> serv = new RDFServiceImpl();
    nsresult rv = serv->Init();
    if (NS_FAILED(rv))
        return rv;

    return serv->QueryInterface(aIID, aResult);
}

NS_IMPL_ISUPPORTS(RDFServiceImpl, nsIRDFService, nsISupportsWeakReference)

// Per RFC2396.
static const uint8_t
kLegalSchemeChars[] = {
          //        ASCII    Bits     Ordered  Hex
          //                 01234567 76543210
    0x00, // 00-07
    0x00, // 08-0F
    0x00, // 10-17
    0x00, // 18-1F
    0x00, // 20-27   !"#$%&' 00000000 00000000
    0x28, // 28-2F  ()*+,-./ 00010100 00101000 0x28
    0xff, // 30-37  01234567 11111111 11111111 0xFF
    0x03, // 38-3F  89:;<=>? 11000000 00000011 0x03
    0xfe, // 40-47  @ABCDEFG 01111111 11111110 0xFE
    0xff, // 48-4F  HIJKLMNO 11111111 11111111 0xFF
    0xff, // 50-57  PQRSTUVW 11111111 11111111 0xFF
    0x87, // 58-5F  XYZ[\]^_ 11100001 10000111 0x87
    0xfe, // 60-67  `abcdefg 01111111 11111110 0xFE
    0xff, // 68-6F  hijklmno 11111111 11111111 0xFF
    0xff, // 70-77  pqrstuvw 11111111 11111111 0xFF
    0x07, // 78-7F  xyz{|}~  11100000 00000111 0x07
    0x00, 0x00, 0x00, 0x00, // >= 80
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00
};

static inline bool
IsLegalSchemeCharacter(const char aChar)
{
    uint8_t mask = kLegalSchemeChars[aChar >> 3];
    uint8_t bit = 1u << (aChar & 0x7);
    return bool((mask & bit) != 0);
}


NS_IMETHODIMP
RDFServiceImpl::GetResource(const nsACString& aURI, nsIRDFResource** aResource)
{
    // Sanity checks
    NS_PRECONDITION(aResource != nullptr, "null ptr");
    NS_PRECONDITION(!aURI.IsEmpty(), "URI is empty");
    if (! aResource)
        return NS_ERROR_NULL_POINTER;
    if (aURI.IsEmpty())
        return NS_ERROR_INVALID_ARG;

    const nsAFlatCString& flatURI = PromiseFlatCString(aURI);
    MOZ_LOG(gLog, LogLevel::Debug, ("rdfserv get-resource %s", flatURI.get()));

    // First, check the cache to see if we've already created and
    // registered this thing.
    PLDHashEntryHdr *hdr = mResources.Search(flatURI.get());
    if (hdr) {
        ResourceHashEntry *entry = static_cast<ResourceHashEntry *>(hdr);
        NS_ADDREF(*aResource = entry->mResource);
        return NS_OK;
    }

    // Nope. So go to the repository to create it.

    // Compute the scheme of the URI. Scan forward until we either:
    //
    // 1. Reach the end of the string
    // 2. Encounter a non-alpha character
    // 3. Encouter a colon.
    //
    // If we encounter a colon _before_ encountering a non-alpha
    // character, then assume it's the scheme.
    //
    // XXX Although it's really not correct, we'll allow underscore
    // characters ('_'), too.
    nsACString::const_iterator p, end;
    aURI.BeginReading(p);
    aURI.EndReading(end);
    while (p != end && IsLegalSchemeCharacter(*p))
        ++p;

    nsresult rv;
    nsCOMPtr<nsIFactory> factory;

    nsACString::const_iterator begin;
    aURI.BeginReading(begin);
    if (*p == ':') {
        // There _was_ a scheme. First see if it's the same scheme
        // that we just tried to use...
        if (mLastFactory && mLastURIPrefix.Equals(Substring(begin, p)))
            factory = mLastFactory;
        else {
            // Try to find a factory using the component manager.
            nsACString::const_iterator begin;
            aURI.BeginReading(begin);
            nsAutoCString contractID;
            contractID = NS_LITERAL_CSTRING(NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX) +
                         Substring(begin, p);

            factory = do_GetClassObject(contractID.get());
            if (factory) {
                // Store the factory in our one-element cache.
                if (p != begin) {
                    mLastFactory = factory;
                    mLastURIPrefix = Substring(begin, p);
                }
            }
        }
    }

    if (! factory) {
        // fall through to using the "default" resource factory if either:
        //
        // 1. The URI didn't have a scheme, or
        // 2. There was no resource factory registered for the scheme.
        factory = mDefaultResourceFactory;

        // Store the factory in our one-element cache.
        if (p != begin) {
            mLastFactory = factory;
            mLastURIPrefix = Substring(begin, p);
        }
    }

    nsIRDFResource *result;
    rv = factory->CreateInstance(nullptr, NS_GET_IID(nsIRDFResource), (void**) &result);
    if (NS_FAILED(rv)) return rv;

    // Now initialize it with its URI. At this point, the resource
    // implementation should register itself with the RDF service.
    rv = result->Init(flatURI.get());
    if (NS_FAILED(rv)) {
        NS_ERROR("unable to initialize resource");
        NS_RELEASE(result);
        return rv;
    }

    *aResource = result; // already refcounted from repository
    return rv;
}

NS_IMETHODIMP
RDFServiceImpl::GetUnicodeResource(const nsAString& aURI, nsIRDFResource** aResource)
{
    return GetResource(NS_ConvertUTF16toUTF8(aURI), aResource);
}


NS_IMETHODIMP
RDFServiceImpl::GetAnonymousResource(nsIRDFResource** aResult)
{
static uint32_t gCounter = 0;
static char gChars[] = "0123456789abcdef"
                       "ghijklmnopqrstuv"
                       "wxyzABCDEFGHIJKL"
                       "MNOPQRSTUVWXYZ.+";

static int32_t kMask  = 0x003f;
static int32_t kShift = 6;

    if (! gCounter) {
        // Start it at a semi-unique value, just to minimize the
        // chance that we get into a situation where
        //
        // 1. An anonymous resource gets serialized out in a graph
        // 2. Reboot
        // 3. The same anonymous resource gets requested, and refers
        //    to something completely different.
        // 4. The serialization is read back in.
        gCounter = uint32_t(PR_Now());
    }

    nsresult rv;
    nsAutoCString s;

    do {
        // Ugh, this is a really sloppy way to do this; I copied the
        // implementation from the days when it lived outside the RDF
        // service. Now that it's a member we can be more cleverer.

        s.Truncate();
        s.AppendLiteral("rdf:#$");

        uint32_t id = ++gCounter;
        while (id) {
            char ch = gChars[(id & kMask)];
            s.Append(ch);
            id >>= kShift;
        }

        nsIRDFResource* resource;
        rv = GetResource(s, &resource);
        if (NS_FAILED(rv)) return rv;

        // XXX an ugly but effective way to make sure that this
        // resource is really unique in the world.
        resource->AddRef();
        nsrefcnt refcnt = resource->Release();

        if (refcnt == 1) {
            *aResult = resource;
            break;
        }

        NS_RELEASE(resource);
    } while (1);

    return NS_OK;
}


NS_IMETHODIMP
RDFServiceImpl::GetLiteral(const char16_t* aValue, nsIRDFLiteral** aLiteral)
{
    NS_PRECONDITION(aValue != nullptr, "null ptr");
    if (! aValue)
        return NS_ERROR_NULL_POINTER;

    NS_PRECONDITION(aLiteral != nullptr, "null ptr");
    if (! aLiteral)
        return NS_ERROR_NULL_POINTER;

    // See if we have one already cached
    PLDHashEntryHdr *hdr = mLiterals.Search(aValue);
    if (hdr) {
        LiteralHashEntry *entry = static_cast<LiteralHashEntry *>(hdr);
        NS_ADDREF(*aLiteral = entry->mLiteral);
        return NS_OK;
    }

    // Nope. Create a new one
    return LiteralImpl::Create(aValue, aLiteral);
}

NS_IMETHODIMP
RDFServiceImpl::GetDateLiteral(PRTime aTime, nsIRDFDate** aResult)
{
    // See if we have one already cached
    PLDHashEntryHdr *hdr = mDates.Search(&aTime);
    if (hdr) {
        DateHashEntry *entry = static_cast<DateHashEntry *>(hdr);
        NS_ADDREF(*aResult = entry->mDate);
        return NS_OK;
    }

    DateImpl* result = new DateImpl(aTime);
    if (! result)
        return NS_ERROR_OUT_OF_MEMORY;

    NS_ADDREF(*aResult = result);
    return NS_OK;
}

NS_IMETHODIMP
RDFServiceImpl::GetIntLiteral(int32_t aInt, nsIRDFInt** aResult)
{
    // See if we have one already cached
    PLDHashEntryHdr *hdr = mInts.Search(&aInt);
    if (hdr) {
        IntHashEntry *entry = static_cast<IntHashEntry *>(hdr);
        NS_ADDREF(*aResult = entry->mInt);
        return NS_OK;
    }

    IntImpl* result = new IntImpl(aInt);
    if (! result)
        return NS_ERROR_OUT_OF_MEMORY;

    NS_ADDREF(*aResult = result);
    return NS_OK;
}

NS_IMETHODIMP
RDFServiceImpl::GetBlobLiteral(const uint8_t *aBytes, int32_t aLength,
                               nsIRDFBlob **aResult)
{
    BlobImpl::Data key = { aLength, const_cast<uint8_t *>(aBytes) };

    PLDHashEntryHdr *hdr = mBlobs.Search(&key);
    if (hdr) {
        BlobHashEntry *entry = static_cast<BlobHashEntry *>(hdr);
        NS_ADDREF(*aResult = entry->mBlob);
        return NS_OK;
    }

    BlobImpl *result = new BlobImpl(aBytes, aLength);
    if (! result)
        return NS_ERROR_OUT_OF_MEMORY;

    NS_ADDREF(*aResult = result);
    return NS_OK;
}

NS_IMETHODIMP
RDFServiceImpl::IsAnonymousResource(nsIRDFResource* aResource, bool* _result)
{
    NS_PRECONDITION(aResource != nullptr, "null ptr");
    if (! aResource)
        return NS_ERROR_NULL_POINTER;

    nsresult rv;

    const char* uri;
    rv = aResource->GetValueConst(&uri);
    if (NS_FAILED(rv)) return rv;

    if ((uri[0] == 'r') &&
        (uri[1] == 'd') &&
        (uri[2] == 'f') &&
        (uri[3] == ':') &&
        (uri[4] == '#') &&
        (uri[5] == '$')) {
        *_result = true;
    }
    else {
        *_result = false;
    }

    return NS_OK;
}

NS_IMETHODIMP
RDFServiceImpl::RegisterResource(nsIRDFResource* aResource, bool aReplace)
{
    NS_PRECONDITION(aResource != nullptr, "null ptr");
    if (! aResource)
        return NS_ERROR_NULL_POINTER;

    nsresult rv;

    const char* uri;
    rv = aResource->GetValueConst(&uri);
    NS_ASSERTION(NS_SUCCEEDED(rv), "unable to get URI from resource");
    if (NS_FAILED(rv)) return rv;

    NS_ASSERTION(uri != nullptr, "resource has no URI");
    if (! uri)
        return NS_ERROR_NULL_POINTER;

    PLDHashEntryHdr *hdr = mResources.Search(uri);
    if (hdr) {
        if (!aReplace) {
            NS_WARNING("resource already registered, and replace not specified");
            return NS_ERROR_FAILURE;    // already registered
        }

        // N.B., we do _not_ release the original resource because we
        // only ever held a weak reference to it. We simply replace
        // it.

        MOZ_LOG(gLog, LogLevel::Debug,
               ("rdfserv   replace-resource [%p] <-- [%p] %s",
                static_cast<ResourceHashEntry *>(hdr)->mResource,
                aResource, (const char*) uri));
    }
    else {
        hdr = mResources.Add(uri, fallible);
        if (! hdr)
            return NS_ERROR_OUT_OF_MEMORY;

        MOZ_LOG(gLog, LogLevel::Debug,
               ("rdfserv   register-resource [%p] %s",
                aResource, (const char*) uri));
    }

    // N.B., we only hold a weak reference to the resource: that way,
    // the resource can be destroyed when the last refcount goes
    // away. The single addref that the CreateResource() call made
    // will be owned by the callee.
    ResourceHashEntry *entry = static_cast<ResourceHashEntry *>(hdr);
    entry->mResource = aResource;
    entry->mKey = uri;

    return NS_OK;
}

NS_IMETHODIMP
RDFServiceImpl::UnregisterResource(nsIRDFResource* aResource)
{
    NS_PRECONDITION(aResource != nullptr, "null ptr");
    if (! aResource)
        return NS_ERROR_NULL_POINTER;

    nsresult rv;

    const char* uri;
    rv = aResource->GetValueConst(&uri);
    if (NS_FAILED(rv)) return rv;

    NS_ASSERTION(uri != nullptr, "resource has no URI");
    if (! uri)
        return NS_ERROR_UNEXPECTED;

    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv unregister-resource [%p] %s",
            aResource, (const char*) uri));

#ifdef DEBUG
    if (!mResources.Search(uri))
        NS_WARNING("resource was never registered");
#endif

    mResources.Remove(uri);
    return NS_OK;
}

NS_IMETHODIMP
RDFServiceImpl::RegisterDataSource(nsIRDFDataSource* aDataSource, bool aReplace)
{
    NS_PRECONDITION(aDataSource != nullptr, "null ptr");
    if (! aDataSource)
        return NS_ERROR_NULL_POINTER;

    nsresult rv;

    nsXPIDLCString uri;
    rv = aDataSource->GetURI(getter_Copies(uri));
    if (NS_FAILED(rv)) return rv;

    PLHashEntry** hep =
        PL_HashTableRawLookup(mNamedDataSources, (*mNamedDataSources->keyHash)(uri), uri);

    if (*hep) {
        if (! aReplace)
            return NS_ERROR_FAILURE; // already registered

        // N.B., we only hold a weak reference to the datasource, so
        // just replace the old with the new and don't touch any
        // refcounts.
        MOZ_LOG(gLog, LogLevel::Debug,
               ("rdfserv    replace-datasource [%p] <-- [%p] %s",
                (*hep)->value, aDataSource, (const char*) uri));

        (*hep)->value = aDataSource;
    }
    else {
        const char* key = PL_strdup(uri);
        if (! key)
            return NS_ERROR_OUT_OF_MEMORY;

        PL_HashTableAdd(mNamedDataSources, key, aDataSource);

        MOZ_LOG(gLog, LogLevel::Debug,
               ("rdfserv   register-datasource [%p] %s",
                aDataSource, (const char*) uri));

        // N.B., we only hold a weak reference to the datasource, so don't
        // addref.
    }

    return NS_OK;
}

NS_IMETHODIMP
RDFServiceImpl::UnregisterDataSource(nsIRDFDataSource* aDataSource)
{
    NS_PRECONDITION(aDataSource != nullptr, "null ptr");
    if (! aDataSource)
        return NS_ERROR_NULL_POINTER;

    nsresult rv;

    nsXPIDLCString uri;
    rv = aDataSource->GetURI(getter_Copies(uri));
    if (NS_FAILED(rv)) return rv;

    //NS_ASSERTION(uri != nullptr, "datasource has no URI");
    if (! uri)
        return NS_ERROR_UNEXPECTED;

    PLHashEntry** hep =
        PL_HashTableRawLookup(mNamedDataSources, (*mNamedDataSources->keyHash)(uri), uri);

    // It may well be that this datasource was never registered. If
    // so, don't unregister it.
    if (! *hep || ((*hep)->value != aDataSource))
        return NS_OK;

    // N.B., we only held a weak reference to the datasource, so we
    // don't release here.
    PL_HashTableRawRemove(mNamedDataSources, hep, *hep);

    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv unregister-datasource [%p] %s",
            aDataSource, (const char*) uri));

    return NS_OK;
}

NS_IMETHODIMP
RDFServiceImpl::GetDataSource(const char* aURI, nsIRDFDataSource** aDataSource)
{
    // Use the other GetDataSource and ask for a non-blocking Refresh.
    // If you wanted it loaded synchronously, then you should've tried to do it
    // yourself, or used GetDataSourceBlocking.
    return GetDataSource( aURI, false, aDataSource );
}

NS_IMETHODIMP
RDFServiceImpl::GetDataSourceBlocking(const char* aURI, nsIRDFDataSource** aDataSource)
{
    // Use GetDataSource and ask for a blocking Refresh.
    return GetDataSource( aURI, true, aDataSource );
}

nsresult
RDFServiceImpl::GetDataSource(const char* aURI, bool aBlock, nsIRDFDataSource** aDataSource)
{
    NS_PRECONDITION(aURI != nullptr, "null ptr");
    if (! aURI)
        return NS_ERROR_NULL_POINTER;

    nsresult rv;

    // Attempt to canonify the URI before we look for it in the
    // cache. We won't bother doing this on `rdf:' URIs to avoid
    // useless (and expensive) protocol handler lookups.
    nsAutoCString spec(aURI);

    if (!StringBeginsWith(spec, NS_LITERAL_CSTRING("rdf:"))) {
        nsCOMPtr<nsIURI> uri;
        NS_NewURI(getter_AddRefs(uri), spec);
        if (uri) {
            rv = uri->GetSpec(spec);
            if (NS_FAILED(rv)) return rv;
        }
    }

    // First, check the cache to see if we already have this
    // datasource loaded and initialized.
    {
        nsIRDFDataSource* cached =
            static_cast<nsIRDFDataSource*>(PL_HashTableLookup(mNamedDataSources, spec.get()));

        if (cached) {
            NS_ADDREF(cached);
            *aDataSource = cached;
            return NS_OK;
        }
    }

    // Nope. So go to the repository to try to create it.
    nsCOMPtr<nsIRDFDataSource> ds;
    if (StringBeginsWith(spec, NS_LITERAL_CSTRING("rdf:"))) {
        // It's a built-in data source. Convert it to a contract ID.
        nsAutoCString contractID(
                NS_LITERAL_CSTRING(NS_RDF_DATASOURCE_CONTRACTID_PREFIX) +
                Substring(spec, 4, spec.Length() - 4));

        // Strip params to get ``base'' contractID for data source.
        int32_t p = contractID.FindChar(char16_t('&'));
        if (p >= 0)
            contractID.Truncate(p);

        ds = do_GetService(contractID.get(), &rv);
        if (NS_FAILED(rv)) return rv;

        nsCOMPtr<nsIRDFRemoteDataSource> remote = do_QueryInterface(ds);
        if (remote) {
            rv = remote->Init(spec.get());
            if (NS_FAILED(rv)) return rv;
        }
    }
    else {
        // Try to load this as an RDF/XML data source
        ds = do_CreateInstance(kRDFXMLDataSourceCID, &rv);
        if (NS_FAILED(rv)) return rv;

        nsCOMPtr<nsIRDFRemoteDataSource> remote(do_QueryInterface(ds));
        NS_ASSERTION(remote, "not a remote RDF/XML data source!");
        if (! remote) return NS_ERROR_UNEXPECTED;

        rv = remote->Init(spec.get());
        if (NS_FAILED(rv)) return rv;

        rv = remote->Refresh(aBlock);
        if (NS_FAILED(rv)) return rv;
    }

    *aDataSource = ds;
    NS_ADDREF(*aDataSource);
    return NS_OK;
}

////////////////////////////////////////////////////////////////////////

nsresult
RDFServiceImpl::RegisterLiteral(nsIRDFLiteral* aLiteral)
{
    const char16_t* value;
    aLiteral->GetValueConst(&value);

    NS_ASSERTION(!mLiterals.Search(value), "literal already registered");

    PLDHashEntryHdr *hdr = mLiterals.Add(value, fallible);
    if (! hdr)
        return NS_ERROR_OUT_OF_MEMORY;

    LiteralHashEntry *entry = static_cast<LiteralHashEntry *>(hdr);

    // N.B., we only hold a weak reference to the literal: that
    // way, the literal can be destroyed when the last refcount
    // goes away. The single addref that the CreateLiteral() call
    // made will be owned by the callee.
    entry->mLiteral = aLiteral;
    entry->mKey = value;

    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv   register-literal [%p] %s",
            aLiteral, (const char16_t*) value));

    return NS_OK;
}


nsresult
RDFServiceImpl::UnregisterLiteral(nsIRDFLiteral* aLiteral)
{
    const char16_t* value;
    aLiteral->GetValueConst(&value);

    NS_ASSERTION(mLiterals.Search(value), "literal was never registered");

    mLiterals.Remove(value);

    // N.B. that we _don't_ release the literal: we only held a weak
    // reference to it in the hashtable.
    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv unregister-literal [%p] %s",
            aLiteral, (const char16_t*) value));

    return NS_OK;
}

//----------------------------------------------------------------------

nsresult
RDFServiceImpl::RegisterInt(nsIRDFInt* aInt)
{
    int32_t value;
    aInt->GetValue(&value);

    NS_ASSERTION(!mInts.Search(&value), "int already registered");

    PLDHashEntryHdr *hdr = mInts.Add(&value, fallible);
    if (! hdr)
        return NS_ERROR_OUT_OF_MEMORY;

    IntHashEntry *entry = static_cast<IntHashEntry *>(hdr);

    // N.B., we only hold a weak reference to the literal: that
    // way, the literal can be destroyed when the last refcount
    // goes away. The single addref that the CreateInt() call
    // made will be owned by the callee.
    entry->mInt = aInt;
    entry->mKey = value;

    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv   register-int [%p] %d",
            aInt, value));

    return NS_OK;
}


nsresult
RDFServiceImpl::UnregisterInt(nsIRDFInt* aInt)
{
    int32_t value;
    aInt->GetValue(&value);

    NS_ASSERTION(mInts.Search(&value), "int was never registered");

    mInts.Remove(&value);

    // N.B. that we _don't_ release the literal: we only held a weak
    // reference to it in the hashtable.
    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv unregister-int [%p] %d",
            aInt, value));

    return NS_OK;
}

//----------------------------------------------------------------------

nsresult
RDFServiceImpl::RegisterDate(nsIRDFDate* aDate)
{
    PRTime value;
    aDate->GetValue(&value);

    NS_ASSERTION(!mDates.Search(&value), "date already registered");

    PLDHashEntryHdr *hdr = mDates.Add(&value, fallible);
    if (! hdr)
        return NS_ERROR_OUT_OF_MEMORY;

    DateHashEntry *entry = static_cast<DateHashEntry *>(hdr);

    // N.B., we only hold a weak reference to the literal: that
    // way, the literal can be destroyed when the last refcount
    // goes away. The single addref that the CreateDate() call
    // made will be owned by the callee.
    entry->mDate = aDate;
    entry->mKey = value;

    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv   register-date [%p] %ld",
            aDate, value));

    return NS_OK;
}


nsresult
RDFServiceImpl::UnregisterDate(nsIRDFDate* aDate)
{
    PRTime value;
    aDate->GetValue(&value);

    NS_ASSERTION(mDates.Search(&value), "date was never registered");

    mDates.Remove(&value);

    // N.B. that we _don't_ release the literal: we only held a weak
    // reference to it in the hashtable.
    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv unregister-date [%p] %ld",
            aDate, value));

    return NS_OK;
}

nsresult
RDFServiceImpl::RegisterBlob(BlobImpl *aBlob)
{
    NS_ASSERTION(!mBlobs.Search(&aBlob->mData), "blob already registered");

    PLDHashEntryHdr *hdr = mBlobs.Add(&aBlob->mData, fallible);
    if (! hdr)
        return NS_ERROR_OUT_OF_MEMORY;

    BlobHashEntry *entry = static_cast<BlobHashEntry *>(hdr);

    // N.B., we only hold a weak reference to the literal: that
    // way, the literal can be destroyed when the last refcount
    // goes away. The single addref that the CreateInt() call
    // made will be owned by the callee.
    entry->mBlob = aBlob;

    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv   register-blob [%p] %s",
            aBlob, aBlob->mData.mBytes));

    return NS_OK;
}

nsresult
RDFServiceImpl::UnregisterBlob(BlobImpl *aBlob)
{
    NS_ASSERTION(mBlobs.Search(&aBlob->mData), "blob was never registered");

    mBlobs.Remove(&aBlob->mData);

     // N.B. that we _don't_ release the literal: we only held a weak
     // reference to it in the hashtable.
    MOZ_LOG(gLog, LogLevel::Debug,
           ("rdfserv unregister-blob [%p] %s",
            aBlob, aBlob->mData.mBytes));

    return NS_OK;
}