Bug 1620113 - part1 : support contain and length for LinkedList. r=froydnj

Differential Revision: https://phabricator.services.mozilla.com/D66854

--HG--
extra : moz-landing-system : lando
This commit is contained in:
alwu 2020-03-18 22:14:59 +00:00
parent f546d53728
commit c90111145c
2 changed files with 35 additions and 0 deletions

View File

@ -402,6 +402,12 @@ class LinkedList {
Type mCurrent;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
explicit Iterator(Type aCurrent) : mCurrent(aCurrent) {}
Type operator*() const { return mCurrent; }
@ -488,6 +494,13 @@ class LinkedList {
*/
bool isEmpty() const { return !sentinel.isInList(); }
/**
* Returns whether the given element is in the list.
*/
bool contains(ConstRawType aElm) const {
return std::find(begin(), end(), aElm) != end();
}
/*
* Remove all the elements from the list.
*
@ -499,6 +512,19 @@ class LinkedList {
}
}
/**
* Return the length of elements in the list.
*/
size_t length() const {
size_t length = 0;
ConstRawType element = getFirst();
while (element) {
length++;
element = element->getNext();
}
return length;
}
/*
* Allow range-based iteration:
*

View File

@ -33,6 +33,7 @@ static void TestList() {
SomeClass one(1), two(2), three(3);
MOZ_RELEASE_ASSERT(list.isEmpty());
MOZ_RELEASE_ASSERT(list.length() == 0);
MOZ_RELEASE_ASSERT(!list.getFirst());
MOZ_RELEASE_ASSERT(!list.getLast());
MOZ_RELEASE_ASSERT(!list.popFirst());
@ -53,7 +54,12 @@ static void TestList() {
MOZ_RELEASE_ASSERT(!two.isInList());
MOZ_RELEASE_ASSERT(!three.isInList());
MOZ_RELEASE_ASSERT(list.contains(&one));
MOZ_RELEASE_ASSERT(!list.contains(&two));
MOZ_RELEASE_ASSERT(!list.contains(&three));
MOZ_RELEASE_ASSERT(!list.isEmpty());
MOZ_RELEASE_ASSERT(list.length() == 1);
MOZ_RELEASE_ASSERT(list.getFirst()->mValue == 1);
MOZ_RELEASE_ASSERT(list.getLast()->mValue == 1);
@ -63,6 +69,7 @@ static void TestList() {
CheckListValues(list, check);
}
MOZ_RELEASE_ASSERT(list.length() == 2);
MOZ_RELEASE_ASSERT(list.getFirst()->mValue == 2);
MOZ_RELEASE_ASSERT(list.getLast()->mValue == 1);
@ -72,6 +79,7 @@ static void TestList() {
CheckListValues(list, check);
}
MOZ_RELEASE_ASSERT(list.length() == 3);
MOZ_RELEASE_ASSERT(list.getFirst()->mValue == 2);
MOZ_RELEASE_ASSERT(list.getLast()->mValue == 3);
@ -153,6 +161,7 @@ static void TestList() {
x->incr();
}
MOZ_RELEASE_ASSERT(list.length() == 2);
MOZ_RELEASE_ASSERT(list.getFirst() == &two);
MOZ_RELEASE_ASSERT(list.getLast() == &three);
MOZ_RELEASE_ASSERT(list.getFirst()->mValue == 3);