void main ( void ) { Deque<int> intQ; printf ( "isEmpty(1): %d\n", intQ.isEmpty ( ) ? 1 : 0 ); intQ.insertFirst ( 4 ); cout << intQ <<endl; printf ( "removeLast(4): %d\n", intQ.removeLast ( ) ); cout << intQ <<endl; intQ.insertFirst ( 5 ); intQ.insertFirst ( 12 ); intQ.insertLast ( 7 ); intQ.insertLast ( 13 ); cout << intQ <<endl; printf ( "first(12): %d\n", intQ.first ( ) ); printf ( "last(13): %d\n", intQ.last ( ) ); printf ( "size(4): %d\n", intQ.size ( ) ); printf ( "isEmpty(0): %d\n", intQ.isEmpty ( ) ? 1 : 0 ); printf ( "removeLast(13) :%d\n", intQ.removeLast ( ) ); printf ( "removeLast(7) :%d\n", intQ.removeLast ( ) ); printf ( "removeLast(5) :%d\n", intQ.removeLast ( ) ); cout << intQ <<endl; printf ( "removeFirst(12) :%d\n", intQ.removeFirst ( ) ); cout << intQ <<endl; printf ( "size(0): %d\n", intQ.size ( ) ); printf ( "isEmpty(1): %d\n", intQ.isEmpty ( ) ? 1 : 0 ); intQ.removeLast ( ); }
int main() { Deque <string> D; D.insertFront("Alice"); D.insertRear("Bob"); cout << D.front() << endl; cout << D.rear() << endl; cout << D.size() << endl; D.insertRear("Charlie"); cout << D.front() << endl; cout << D.rear() << endl; D.removeFront(); cout << D.front() << endl; cout << D.rear() << endl; cout << D.size() << endl; D.removeFront(); cout << D.size() << endl; }
void update(int64_t packet_raw, int packet_size, const Int64TimeField &packet_at, const string &filename) { LintelLogDebug("IPRolling::packet", format("UPD %d %d") % packet_raw % packet_size); if (!packets_in_flight.empty()) { int64_t cur_back_ts_raw = packets_in_flight.back().timestamp_raw; INVARIANT(packet_raw >= cur_back_ts_raw, format("out of order by %.4fs in %s; %d < %d") % packet_at.rawToDoubleSeconds(cur_back_ts_raw - packet_raw) % filename % packet_raw % cur_back_ts_raw); } while ((packet_raw - cur_time_raw) > interval_width_raw) { // update statistics for the interval from cur_time to cur_time + interval_width // all packets in p_i_f must have been received in that interval double bw = cur_bytes_in_queue * MiB_per_second_convert; MiB_per_second.add(bw); double pps = packets_in_flight.size() * kpackets_per_second_convert; kpackets_per_second.add(pps); LintelLogDebug("IPRolling::detail", format("[%d..%d[: %.0f, %d -> %.6g %.6g") % cur_time_raw % (cur_time_raw + update_step_raw) % cur_bytes_in_queue % packets_in_flight.size() % bw % pps); cur_time_raw += update_step_raw; while (! packets_in_flight.empty() && packets_in_flight.front().timestamp_raw < cur_time_raw) { cur_bytes_in_queue -= packets_in_flight.front().packetsize; packets_in_flight.pop_front(); } } packets_in_flight.push_back(packetTimeSize(packet_raw, packet_size)); cur_bytes_in_queue += packet_size; }
void testNoDefaultConstructor() { Deque<NoDefaultConstructor> deque; deque.reserve(8); for(int i = 0; i < 5; ++i) { deque.push_back(NoDefaultConstructor(i)); SINVARIANT(deque.back().v == i); SINVARIANT(deque.size() == static_cast<size_t>(i + 1)); INVARIANT(NoDefaultConstructor::ndc_count == i + 1, format("%d != %d + 1") % NoDefaultConstructor::ndc_count % i); } for(int i = 0; i < 5; ++i) { SINVARIANT(deque.front().v == i); deque.pop_front(); deque.push_back(NoDefaultConstructor(i)); SINVARIANT(deque.back().v == i); SINVARIANT(deque.size() == 5); SINVARIANT(NoDefaultConstructor::ndc_count == 5); } for(int i = 0; i < 5; ++i) { SINVARIANT(deque.front().v == i); deque.pop_front(); SINVARIANT(deque.size() == static_cast<size_t>(4 - i)); SINVARIANT(NoDefaultConstructor::ndc_count == 4 - i); } SINVARIANT(NoDefaultConstructor::ndc_count == 0); }
TEST(Deque, pop_front) { Deque d; d.push_front(0); CHECK(1 == d.size()); CHECK(0 == d.pop_front()); CHECK(0 == d.size()); }
TEST(EmptyDequeTest, PushFront) { Deque<int> deque; for (int i = 0; i < 10; ++i) { EXPECT_EQ(deque.size(), i); deque.push_front(i); EXPECT_EQ(deque[0], i); EXPECT_EQ(deque.size(), i+1); } }
void testPushBack() { Deque<int> deque; SINVARIANT(deque.empty()); deque.reserve(8); SINVARIANT(deque.empty() && deque.capacity() == 8); for(int i = 0; i < 5; ++i) { deque.push_back(i); SINVARIANT(deque.back() == i); SINVARIANT(deque.size() == static_cast<size_t>(i + 1)); } for(int i = 0; i < 5; ++i) { SINVARIANT(deque.at(i) == i); } for(int i = 0; i < 5; ++i) { SINVARIANT(deque.front() == i); deque.pop_front(); deque.push_back(i); SINVARIANT(deque.back() == i); SINVARIANT(deque.size() == 5); } for(int i = 0; i < 5; ++i) { SINVARIANT(deque.at(i) == i); } { Deque<int>::iterator i = deque.begin(); int j = 0; while(i != deque.end()) { INVARIANT(*i == j, format("%d != %d") % *i % j); ++i; ++j; } } vector<int> avec; for(int i = 5; i < 10; ++i) { avec.push_back(i); } deque.push_back(avec); for(int i = 0; i < 10; ++i) { SINVARIANT(deque.front() == i); deque.pop_front(); } SINVARIANT(deque.empty()); }
static void busAcquiredCallback(GDBusConnection* connection, const char* name, gpointer userData) { static GDBusNodeInfo* introspectionData = 0; if (!introspectionData) introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, 0); GOwnPtr<GError> error; unsigned registrationID = g_dbus_connection_register_object( connection, "/org/webkit/gtk/WebExtensionTest", introspectionData->interfaces[0], &interfaceVirtualTable, g_object_ref(userData), static_cast<GDestroyNotify>(g_object_unref), &error.outPtr()); if (!registrationID) g_warning("Failed to register object: %s\n", error->message); g_object_set_data(G_OBJECT(userData), "dbus-connection", connection); while (delayedSignalsQueue.size()) { OwnPtr<DelayedSignal> delayedSignal = delayedSignalsQueue.takeFirst(); switch (delayedSignal->type) { case DocumentLoadedSignal: emitDocumentLoaded(connection); break; case URIChangedSignal: emitURIChanged(connection, delayedSignal->uri.data()); break; } } }
bool HarfBuzzShaper::collectFallbackHintChars( const Deque<HolesQueueItem>& holesQueue, Vector<UChar32>& hint) const { if (!holesQueue.size()) return false; hint.clear(); size_t numCharsAdded = 0; for (auto it = holesQueue.begin(); it != holesQueue.end(); ++it) { if (it->m_action == HolesQueueNextFont) break; UChar32 hintChar; RELEASE_ASSERT(it->m_startIndex + it->m_numCharacters <= m_normalizedBufferLength); UTF16TextIterator iterator(m_normalizedBuffer + it->m_startIndex, it->m_numCharacters); while (iterator.consume(hintChar)) { hint.append(hintChar); numCharsAdded++; iterator.advance(); } } return numCharsAdded > 0; }
TEST_F(ReadableStreamTest, ReadQueue) { ScriptState::Scope scope(scriptState()); ExceptionState exceptionState(ExceptionState::ConstructionContext, "property", "interface", scriptState()->context()->Global(), isolate()); StringStream* stream = construct(); Checkpoint checkpoint; { InSequence s; EXPECT_CALL(checkpoint, Call(0)); EXPECT_CALL(*m_underlyingSource, pullSource()).Times(1); EXPECT_CALL(checkpoint, Call(1)); } Deque<std::pair<String, size_t>> queue; EXPECT_TRUE(stream->enqueue("hello")); EXPECT_TRUE(stream->enqueue("bye")); EXPECT_EQ(ReadableStream::Readable, stream->stateInternal()); EXPECT_FALSE(stream->isPulling()); checkpoint.Call(0); EXPECT_FALSE(stream->isDisturbed()); stream->readInternal(queue); EXPECT_TRUE(stream->isDisturbed()); checkpoint.Call(1); ASSERT_EQ(2u, queue.size()); EXPECT_EQ(std::make_pair(String("hello"), static_cast<size_t>(5)), queue[0]); EXPECT_EQ(std::make_pair(String("bye"), static_cast<size_t>(3)), queue[1]); EXPECT_EQ(ReadableStream::Readable, stream->stateInternal()); EXPECT_TRUE(stream->isPulling()); EXPECT_FALSE(stream->isDraining()); }
TEST(Deque, grow) { Deque d; for (int i = 0; i < 10; i++) d.push_back(i); d.push_back(10); CHECK(11 == d.size()); CHECK(10 == d.pop_back()); }
TEST (Deque, double_test) { Deque<double> d; d.push_front(0.1); d.push_back(1.1); d.push_back(2.1); d.push_back(3.1); CHECK ( 4 == d.size() ); CHECK ( 0.1 == d.pop_front() ); CHECK ( 3.1 == d.pop_back() ); }
TEST(Deque, doit) { Deque d; d.push_front(0); d.push_back(1); d.push_back(2); d.push_back(3); CHECK(4 == d.size()); CHECK(0 == d.pop_front()); CHECK(3 == d.pop_back()); }
int main() { // Stack behavior using a general dequeue Deque q; try { if ( q.isEmpty() ) { cout << "Deque is empty" << endl; } // Push elements q.insertBack(100); q.insertBack(200); q.insertBack(300); // Size of queue cout << "Size of dequeue = " << q.size() << endl; // Pop elements cout << q.removeBack() << endl; cout << q.removeBack() << endl; cout << q.removeBack() << endl; } catch (...) { cout << "Some exception occured" << endl; } // Queue behavior using a general dequeue Deque q1; try { if ( q1.isEmpty() ) { cout << "Deque is empty" << endl; } // Push elements q1.insertBack(100); q1.insertBack(200); q1.insertBack(300); // Size of queue cout << "Size of dequeue = " << q1.size() << endl; // Pop elements cout << q1.removeFront() << endl; cout << q1.removeFront() << endl; cout << q1.removeFront() << endl; } catch (...) { cout << "Some exception occured" << endl; } }
static void buildMaze(int y, int x) { int numOffsets, offset, offsets[4]; while (1) { numOffsets = 0; maze[y][x].visited = true; if (y > 0 && !maze[y - 1][x].visited) offsets[numOffsets ++] = -width; if (y < height - 1 && !maze[y + 1][x].visited) offsets[numOffsets ++] = width; if (x > 0 && !maze[y][x - 1].visited) offsets[numOffsets ++] = -1; if (x < width - 1 && !maze[y][x + 1].visited) offsets[numOffsets ++] = 1; if (numOffsets > 0) { offset = offsets[rand() % numOffsets]; dp.addFirst(offset(x, y)); if (offset == -width) { maze[y - 1][x].bottom = false; buildMaze(y - 1, x); } else if (offset == width) { maze[y][x].bottom = false; buildMaze(y + 1, x); } else if (offset == -1) { maze[y][x - 1].right = false; buildMaze(y, x - 1); } else if (offset == 1) { maze[y][x].right = false; buildMaze(y, x + 1); } else abort(); } else if (dp.size() > 0) { offset = dp.removeFirst(); x = xcoord(offset); y = ycoord(offset); } else break; } maze[height - 1][width - 1].right = false; }
int main(int argc, char** argv) { Deque<char> a; char base_pair; while(cin >> base_pair) a.addLast(base_pair); while(!a.isEmpty()) { if(a.size() == 1) { cout << "false" << endl; return 0; } char first = a.removeFirst(); char last = a.removeLast(); switch(first) { case 'A': if(last != 'T') { cout << "false" << endl; return 0; } continue; case 'T': if(last != 'A') { cout << "false" << endl; return 0; } continue; case 'C': if(last != 'G') { cout << "false" << endl; return 0; } continue; case 'G': if(last != 'C') { cout << "false" << endl; return 0; } continue; default: cout << "false" << endl; return 0; } } cout << "true" << endl; return 0; }
void Pos::printsource() { char *str; int c; size_t t; char temp[77]; if (line == -1) return; for (t = 0; t < fileNames.size(); t++) if (fileName == fileNames.get(t)) break; cout << " '" << fileName << "' line " << line << " column " << col << "\n"; str = source.get(t)->get(line-1); c = col; if (strlen(str) >= 73) { if (col > 73) { for (t = 0; t < 77; t++) { if (str[col - 40 + t] != '\0') temp[t] = str[col - 40 + t]; else break; } temp[t] = '\0'; c = 40; } else { strncpy(temp, str, 77); temp[76] = '\0'; } } else strcpy(temp, str); cout << " " << temp << "\n "; if (c < 77) { for (t = 1; t < (size_t)c; t++) if (t < strlen(temp) && temp[t] == '\t') cout << "\t"; else cout << " "; cout << "^"; } }
TEST(WTF_Deque, MoveConstructor) { Deque<MoveOnly, 4> deque; for (unsigned i = 0; i < 10; ++i) deque.append(MoveOnly(i)); EXPECT_EQ(10u, deque.size()); Deque<MoveOnly, 4> deque2 = WTF::move(deque); EXPECT_EQ(10u, deque2.size()); unsigned i = 0; for (auto& element : deque2) { EXPECT_EQ(i, element.value()); ++i; } }
TEST(WTF_Deque, InitializerList) { Deque<int> deque = { 1, 2, 3, 4 }; EXPECT_EQ(4u, deque.size()); auto it = deque.begin(); auto end = deque.end(); EXPECT_TRUE(end != it); EXPECT_EQ(1, *it); ++it; EXPECT_EQ(2, *it); ++it; EXPECT_EQ(3, *it); ++it; EXPECT_EQ(4, *it); ++it; EXPECT_TRUE(end == it); }
// Sorts the given list of layers such that they can be painted in a back-to-front // order. Sorting produces correct results for non-intersecting layers that don't have // cyclical order dependencies. Cycles and intersections are broken (somewhat) aribtrarily. // Sorting of layers is done via a topological sort of a directed graph whose nodes are // the layers themselves. An edge from node A to node B signifies that layer A needs to // be drawn before layer B. If A and B have no dependency between each other, then we // preserve the ordering of those layers as they were in the original list. // // The draw order between two layers is determined by projecting the two triangles making // up each layer quad to the Z = 0 plane, finding points of intersection between the triangles // and backprojecting those points to the plane of the layer to determine the corresponding Z // coordinate. The layer with the lower Z coordinate (farther from the eye) needs to be rendered // first. // // If the layer projections don't intersect, then no edges (dependencies) are created // between them in the graph. HOWEVER, in this case we still need to preserve the ordering // of the original list of layers, since that list should already have proper z-index // ordering of layers. // void CCLayerSorter::sort(LayerList::iterator first, LayerList::iterator last) { #if !defined( NDEBUG ) LOG(CCLayerSorter, "Sorting start ----\n"); #endif createGraphNodes(first, last); createGraphEdges(); Vector<GraphNode*> sortedList; Deque<GraphNode*> noIncomingEdgeNodeList; // Find all the nodes that don't have incoming edges. for (NodeList::iterator la = m_nodes.begin(); la < m_nodes.end(); la++) { if (!la->incoming.size()) noIncomingEdgeNodeList.append(la); } #if !defined( NDEBUG ) LOG(CCLayerSorter, "Sorted list: "); #endif while (m_activeEdges.size() || noIncomingEdgeNodeList.size()) { while (noIncomingEdgeNodeList.size()) { // It is necessary to preserve the existing ordering of layers, when there are // no explicit dependencies (because this existing ordering has correct // z-index/layout ordering). To preserve this ordering, we process Nodes in // the same order that they were added to the list. GraphNode* fromNode = noIncomingEdgeNodeList.takeFirst(); // Add it to the final list. sortedList.append(fromNode); #if !defined( NDEBUG ) LOG(CCLayerSorter, "%d, ", fromNode->layer->debugID()); #endif // Remove all its outgoing edges from the graph. for (unsigned i = 0; i < fromNode->outgoing.size(); i++) { GraphEdge* outgoingEdge = fromNode->outgoing[i]; m_activeEdges.remove(outgoingEdge); removeEdgeFromList(outgoingEdge, outgoingEdge->to->incoming); outgoingEdge->to->incomingEdgeWeight -= outgoingEdge->weight; if (!outgoingEdge->to->incoming.size()) noIncomingEdgeNodeList.append(outgoingEdge->to); } fromNode->outgoing.clear(); } if (!m_activeEdges.size()) break; // If there are still active edges but the list of nodes without incoming edges // is empty then we have run into a cycle. Break the cycle by finding the node // with the smallest overall incoming edge weight and use it. This will favor // nodes that have zero-weight incoming edges i.e. layers that are being // occluded by a layer that intersects them. float minIncomingEdgeWeight = FLT_MAX; GraphNode* nextNode = 0; for (unsigned i = 0; i < m_nodes.size(); i++) { if (m_nodes[i].incoming.size() && m_nodes[i].incomingEdgeWeight < minIncomingEdgeWeight) { minIncomingEdgeWeight = m_nodes[i].incomingEdgeWeight; nextNode = &m_nodes[i]; } } ASSERT(nextNode); // Remove all its incoming edges. for (unsigned e = 0; e < nextNode->incoming.size(); e++) { GraphEdge* incomingEdge = nextNode->incoming[e]; m_activeEdges.remove(incomingEdge); removeEdgeFromList(incomingEdge, incomingEdge->from->outgoing); } nextNode->incoming.clear(); nextNode->incomingEdgeWeight = 0; noIncomingEdgeNodeList.append(nextNode); #if !defined( NDEBUG ) LOG(CCLayerSorter, "Breaking cycle by cleaning up incoming edges from %d (weight = %f)\n", nextNode->layer->debugID(), minIncomingEdgeWeight); #endif } // Note: The original elements of the list are in no danger of having their ref count go to zero // here as they are all nodes of the layer hierarchy and are kept alive by their parent nodes. int count = 0; for (LayerList::iterator it = first; it < last; it++) *it = sortedList[count++]->layer; #if !defined( NDEBUG ) LOG(CCLayerSorter, "Sorting end ----\n"); #endif m_nodes.clear(); m_edges.clear(); m_activeEdges.clear(); }
void testIteratorOperations() { Deque<int> deque; MersenneTwisterRandom rng; int n_ops = rng.randInt(100); for (int i = 0; i < n_ops; ++i) { if (rng.randInt(10) < 3 && !deque.empty()) { deque.pop_front(); } else { deque.push_back(rng.randInt()); } } // Test iterator unary operators { for (Deque<int>::iterator it = deque.begin(); it != deque.end(); ) { Deque<int>::iterator it1 = it; Deque<int>::iterator it2 = it; SINVARIANT(it1 == it2); Deque<int>::iterator it3 = it1++; INVARIANT(it3 == it && it3 != it1 && it1 != it2, "return unchanged && return different from iterator && iterator changed"); Deque<int>::iterator it4 = ++it2; INVARIANT(it4 != it && it4 == it1 && it2 == it1, "return changed && return == updated && two updates same"); it = it4; } } // Test distance operators Deque<int>::iterator it_forward = deque.begin(); Deque<int>::iterator it_backward = deque.end(); ptrdiff_t dist_from_start = 0; // start can be .begin() or .end() ptrdiff_t dist_from_finish = deque.end() - deque.begin(); // finish can be .end() or .begin() for (; it_forward != deque.end(); ++dist_from_start, --dist_from_finish) { SINVARIANT(it_backward - it_forward == dist_from_finish - dist_from_start); SINVARIANT(it_forward + dist_from_finish == deque.end()); SINVARIANT(it_backward - dist_from_finish == deque.begin()); SINVARIANT((it_forward < it_backward) == (dist_from_start < dist_from_finish)); SINVARIANT((it_forward <= it_backward) == (dist_from_start <= dist_from_finish)); SINVARIANT((it_forward > it_backward) == (dist_from_start > dist_from_finish)); SINVARIANT((it_forward >= it_backward) == (dist_from_start >= dist_from_finish)); Deque<int>::iterator temp_a(it_forward); Deque<int>::iterator temp_b; temp_b = it_backward; SINVARIANT(temp_b - temp_a == dist_from_finish - dist_from_start); temp_a += dist_from_finish; SINVARIANT(temp_a == deque.end()); temp_b -= dist_from_finish; SINVARIANT(temp_b == deque.begin()); if (rng.randBool()) { // Exercise both variants of the increment/decrement operators ++it_forward; --it_backward; } else { it_forward++; it_backward--; } } SINVARIANT(it_backward == deque.begin()); SINVARIANT(static_cast<size_t>(dist_from_start) == deque.size()); SINVARIANT(dist_from_finish == 0); }
void test_deque() { const size_t SIZE = 10; Deque<int, SIZE> deque; cout << "--> testing push_back..." << endl; for (size_t i = 0; i < SIZE; i++) { try { deque.push_back(i); } catch (std::overflow_error &e) { cout << "i: " << i << endl; cout << e.what() << endl; } } deque.traverse(print); cout << endl; cout << "size: " << deque.size() << endl; deque.print_mark(); cout << "--> testing pop_back..." << endl; while (!deque.empty()) { deque.pop_back(); } deque.traverse(print); cout << endl; cout << "size: " << deque.size() << endl; deque.print_mark(); cout << "--> testing push_front..." << endl; for (size_t i = 0; i < SIZE; i++) { try { deque.push_front(i); } catch (std::overflow_error &e) { cout << "i: " << i << endl; cout << e.what() << endl; } } deque.traverse(print); cout << endl; cout << "size: " << deque.size() << endl; deque.print_mark(); cout << "--> testing pop_front..." << endl; while (!deque.empty()) { deque.pop_front(); } deque.traverse(print); cout << endl; cout << "size: " << deque.size() << endl; deque.print_mark(); }
void test_swap (const T *lhs_seq, std::size_t lhs_seq_len, const T *rhs_seq, std::size_t rhs_seq_len, std::deque<T, Allocator>*, const char *tname) { typedef std::deque<T, Allocator> Deque; typedef typename Deque::iterator Iterator; typedef typename Deque::size_type SizeType; // create two containers from the provided sequences Deque lhs (lhs_seq, lhs_seq + lhs_seq_len); Deque rhs (rhs_seq, rhs_seq + rhs_seq_len); // save the begin and and iterators and the size // of each container before swapping the objects const Iterator lhs_begin_0 = lhs.begin (); const Iterator lhs_end_0 = lhs.end (); const SizeType lhs_size_0 = lhs.size (); const Iterator rhs_begin_0 = rhs.begin (); const Iterator rhs_end_0 = rhs.end (); const SizeType rhs_size_0 = rhs.size (); // swap the two containers lhs.swap (rhs); // compute the begin and and iterators and the size // of each container after swapping the objects const Iterator lhs_begin_1 = lhs.begin (); const Iterator lhs_end_1 = lhs.end (); const SizeType lhs_size_1 = lhs.size (); const Iterator rhs_begin_1 = rhs.begin (); const Iterator rhs_end_1 = rhs.end (); const SizeType rhs_size_1 = rhs.size (); static const int cwidth = sizeof (T); // verify that the iterators and sizes // of the two objects were swapped rw_assert (lhs_begin_0 == rhs_begin_1 && lhs_begin_1 == rhs_begin_0, 0, __LINE__, "begin() not swapped for \"%{X=*.*}\" and \"%{X=*.*}\"", cwidth, int (lhs_seq_len), -1, lhs_seq, cwidth, int (rhs_seq_len), -1, rhs_seq); rw_assert (lhs_end_0 == rhs_end_1 && lhs_end_1 == rhs_end_0, 0, __LINE__, "end() not swapped for \"%{X=*.*}\" and \"%{X=*.*}\"", cwidth, int (lhs_seq_len), -1, lhs_seq, cwidth, int (rhs_seq_len), -1, rhs_seq); rw_assert (lhs_size_0 == rhs_size_1 && lhs_size_1 == rhs_size_0, 0, __LINE__, "size() not swapped for \"%{X=*.*}\" and \"%{X=*.*}\"", cwidth, int (lhs_seq_len), -1, lhs_seq, cwidth, int (rhs_seq_len), -1, rhs_seq); // swap one of the containers with an empty unnamed temporary // container and verify that the object is empty { Deque ().swap (lhs); } const Iterator lhs_begin_2 = lhs.begin (); const Iterator lhs_end_2 = lhs.end (); const SizeType lhs_size_2 = lhs.size (); rw_assert (lhs_begin_2 == lhs_end_2, 0, __LINE__, "deque<%s>().begin() not swapped for \"%{X=*.*}\"", tname, cwidth, int (rhs_seq_len), -1, rhs_seq); rw_assert (0 == lhs_size_2, 0, __LINE__, "deque<%s>().size() not swapped for \"%{X=*.*}\"", tname, cwidth, int (rhs_seq_len), -1, rhs_seq); }
void exception_loop (int line /* line number in caller*/, MemberFunction mfun /* deque member function */, const char *fcall /* function call string */, int exceptions /* enabled exceptions */, Deque &deq /* container to call function on */, const Deque::iterator &it /* iterator into container */, int n /* number of elements or offset */, const UserClass *x /* pointer to an element or 0 */, const Iterator &first /* beginning of range */, const Iterator &last /* end of range to insert */, int *n_copy /* number of copy ctors */, int *n_asgn /* number of assignments */) { std::size_t throw_after = 0; // get the initial size of the container and its begin() iterator // to detect illegal changes after an exception (i.e., violations // if the strong exception guarantee) const std::size_t size = deq.size (); const Deque::const_iterator begin = deq.begin (); const Deque::const_iterator end = deq.end (); #ifdef DEFINE_REPLACEMENT_NEW_AND_DELETE rwt_free_store* const pst = rwt_get_free_store (0); #endif // DEFINE_REPLACEMENT_NEW_AND_DELETE // repeatedly call the specified member function until it returns // without throwing an exception for ( ; ; ) { // detect objects constructed but not destroyed after an exception std::size_t x_count = UserClass::count_; _RWSTD_ASSERT (n_copy); _RWSTD_ASSERT (n_asgn); *n_copy = UserClass::n_total_copy_ctor_; *n_asgn = UserClass::n_total_op_assign_; #ifndef _RWSTD_NO_EXCEPTIONS // iterate for `n=throw_after' starting at the next call to operator // new, forcing each call to throw an exception, until the insertion // finally succeeds (i.e, no exception is thrown) # ifdef DEFINE_REPLACEMENT_NEW_AND_DELETE if (exceptions & NewThrows) { *pst->throw_at_calls_ [0] = pst->new_calls_ [0] + throw_after + 1; } # endif // DEFINE_REPLACEMENT_NEW_AND_DELETE if (exceptions & CopyCtorThrows) { UserClass::copy_ctor_throw_count_ = UserClass::n_total_copy_ctor_ + throw_after; } if (exceptions & AssignmentThrows) { UserClass::op_assign_throw_count_ = UserClass::n_total_op_assign_ + throw_after; } #endif // _RWSTD_NO_EXCEPTIONS _TRY { switch (mfun) { case Assign_n: _RWSTD_ASSERT (x); deq.assign (n, *x); break; case AssignRange: deq.assign (first, last); break; case Erase_1: deq.erase (it); break; case EraseRange: { const Deque::iterator erase_end (it + n); deq.erase (it, erase_end); break; } case Insert_1: _RWSTD_ASSERT (x); deq.insert (it, *x); break; case Insert_n: _RWSTD_ASSERT (x); deq.insert (it, n, *x); break; case InsertRange: deq.insert (it, first, last); break; } } _CATCH (...) { // verify that an exception thrown from the member function // didn't cause a change in the state of the container rw_assert (deq.size () == size, 0, line, "line %d: %s: size unexpectedly changed " "from %zu to %zu after an exception", __LINE__, fcall, size, deq.size ()); rw_assert (deq.begin () == begin, 0, line, "line %d: %s: begin() unexpectedly " "changed after an exception by %td", __LINE__, fcall, deq.begin () - begin); rw_assert (deq.end () == end, 0, line, "line %d: %s: end() unexpectedly " "changed after an exception by %td", __LINE__, fcall, deq.end () - end); // count the number of objects to detect leaks x_count = UserClass::count_ - x_count; rw_assert (x_count == deq.size () - size, 0, line, "line %d: %s: leaked %zu objects after an exception", __LINE__, fcall, x_count - (deq.size () - size)); if (exceptions) { // increment to allow this call to operator new to succeed // and force the next one to fail, and try to insert again ++throw_after; } else break; continue; } // count the number of objects to detect leaks x_count = UserClass::count_ - x_count; rw_assert (x_count == deq.size () - size, 0, line, "line %d: %s: leaked %zu objects " "after a successful insertion", __LINE__, fcall, x_count - (deq.size () - size)); break; }
TEST(Deque, push_back) { Deque d; d.push_back(0); CHECK(1 == d.size()); }
TEST(Deque, construction) { Deque d; CHECK(0 == d.size()); }
Deque::Deque(const Deque& other) : itsSize(other.size()), itsCap(other.capacity()) { copy_data(other.itsData); }
TEST (Deque, push_front) { Deque<int> d; d.push_front(0); CHECK ( 1 == d.size() ); }
int main(int argc, char *argv[]) { Deque *deque; char line[4096]; size_t len; void *data; size_t size; if (argc == 1) { deque = Memory_Deque_create(); } else if (argc == 2 && argv[1][0] != '-') { deque = File_Deque_create(argv[1]); } else { printf("Usage:\n" " test-deque -- use the in-memory deque\n" " test-deque <path> -- use the file-based deque\n" "\n" "Commands:\n" " destroy -- destroy the deque and exit\n" " empty -- report if the deque is empty\n" " size -- print number of elements in the deque\n" " push_back -- add element at the back\n" " push_front -- add element at the front\n" " get_back -- print element at the back\n" " get_front -- print element at the front\n" " pop_back -- remove element at the back\n" " pop_front -- remove element at the front\n"); return 1; } if (deque == NULL) { fprintf(stderr, "Unable to create deque!\n"); exit(1); } while (fgets(line, sizeof(line), stdin) != NULL) { /* Determine length and strip trailing newline character */ len = strlen(line); if (len == 0) break; if (line[len - 1] == '\n') { line[len - 1] = '\0'; len -= 1; } if (strcmp(line, "destroy") == 0) { break; } else if (strcmp(line, "empty") == 0) { printf("empty=%s\n", deque->empty(deque) ? "true" : "false"); } else if (strcmp(line, "size") == 0) { printf("size=%ld\n", (long)deque->size(deque)); } else if (strncmp(line, "push_back ", 10) == 0) { if (!deque->push_back(deque, line + 10, len - 10)) printf("push_back failed!\n"); } else if (strncmp(line, "push_front ", 11) == 0) { if (!deque->push_front(deque, line + 11, len - 11)) printf("push_front failed!\n"); } else if (strcmp(line, "get_back") == 0) { if (!deque->get_back(deque, &data, &size)) printf("get_back failed!\n"); else { fwrite(data, size, 1, stdout); fputc('\n', stdout); } } else if (strcmp(line, "get_front") == 0) { if (!deque->get_front(deque, &data, &size)) printf("get_front failed!\n"); else { fwrite(data, size, 1, stdout); fputc('\n', stdout); } } else if (strcmp(line, "pop_back") == 0) { if (!deque->pop_back(deque)) printf("pop_back failed!\n"); } else if (strcmp(line, "pop_front") == 0) { if (!deque->pop_front(deque)) printf("pop_front failed!\n"); } else { printf("Unrecognized input line: %s!\n", line); } } deque->destroy(deque); return 0; }