コード例 #1
0
ファイル: deque_main.cpp プロジェクト: ushadow/scratchpad
int main() {
  Deque<int> deque;
  deque.PushBack(1);
  cout << deque.ToString() << endl;
   deque.PushBack(3);
  cout << deque.ToString() << endl;
  deque.PushFront(2);
  cout << deque.ToString() << endl;
  deque.PopBack();
  cout << deque.ToString() << endl;
  deque.PopFront();
  cout << deque.ToString() << endl;
  deque.PopFront();
  cout << deque.ToString() << endl;  
}
コード例 #2
0
ファイル: test-deque.c プロジェクト: maksverver/BSc
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;
}
コード例 #3
0
ファイル: test_main.cpp プロジェクト: IlRomanenko/Deque
 void AddElements(int size)
 {
     fori(i, size)
         deque_int.push_back(random(engine));
 }
コード例 #4
0
static PassOwnPtr<MessageDecoder> createMessageDecoder(mach_msg_header_t* header)
{
    if (!(header->msgh_bits & MACH_MSGH_BITS_COMPLEX)) {
        // We have a simple message.
        uint8_t* body = reinterpret_cast<uint8_t*>(header + 1);
        size_t bodySize = header->msgh_size - sizeof(mach_msg_header_t);

        return MessageDecoder::create(DataReference(body, bodySize));
    }

    bool messageBodyIsOOL = header->msgh_id & MessageBodyIsOOL;

    mach_msg_body_t* body = reinterpret_cast<mach_msg_body_t*>(header + 1);
    mach_msg_size_t numDescriptors = body->msgh_descriptor_count;
    ASSERT(numDescriptors);

    // Build attachment list
    Deque<Attachment> attachments;
    uint8_t* descriptorData = reinterpret_cast<uint8_t*>(body + 1);

    // If the message body was sent out-of-line, don't treat the last descriptor
    // as an attachment, since it is really the message body.
    if (messageBodyIsOOL)
        --numDescriptors;

    for (mach_msg_size_t i = 0; i < numDescriptors; ++i) {
        mach_msg_descriptor_t* descriptor = reinterpret_cast<mach_msg_descriptor_t*>(descriptorData);

        switch (descriptor->type.type) {
        case MACH_MSG_PORT_DESCRIPTOR:
            attachments.append(Attachment(descriptor->port.name, descriptor->port.disposition));
            descriptorData += sizeof(mach_msg_port_descriptor_t);
            break;
        case MACH_MSG_OOL_DESCRIPTOR:
            attachments.append(Attachment(descriptor->out_of_line.address, descriptor->out_of_line.size,
                                          descriptor->out_of_line.copy, descriptor->out_of_line.deallocate));
            descriptorData += sizeof(mach_msg_ool_descriptor_t);
            break;
        default:
            ASSERT(false && "Unhandled descriptor type");
        }
    }

    if (messageBodyIsOOL) {
        mach_msg_descriptor_t* descriptor = reinterpret_cast<mach_msg_descriptor_t*>(descriptorData);
        ASSERT(descriptor->type.type == MACH_MSG_OOL_DESCRIPTOR);
        Attachment messageBodyAttachment(descriptor->out_of_line.address, descriptor->out_of_line.size,
                                         descriptor->out_of_line.copy, descriptor->out_of_line.deallocate);

        uint8_t* messageBody = static_cast<uint8_t*>(messageBodyAttachment.address());
        size_t messageBodySize = messageBodyAttachment.size();

        OwnPtr<MessageDecoder> decoder;

        if (attachments.isEmpty())
            decoder = MessageDecoder::create(DataReference(messageBody, messageBodySize));
        else
            decoder = MessageDecoder::create(DataReference(messageBody, messageBodySize), attachments);

        vm_deallocate(mach_task_self(), reinterpret_cast<vm_address_t>(messageBodyAttachment.address()), messageBodyAttachment.size());

        return decoder.release();
    }

    uint8_t* messageBody = descriptorData;
    size_t messageBodySize = header->msgh_size - (descriptorData - reinterpret_cast<uint8_t*>(header));

    return MessageDecoder::create(DataReference(messageBody, messageBodySize), attachments);
}
コード例 #5
0
void FullscreenElementStack::requestFullScreenForElement(Element* element, unsigned short flags, FullScreenCheckType checkType)
{
    // Ignore this request if the document is not in a live frame.
    if (!document()->isActive())
        return;

    // The Mozilla Full Screen API <https://wiki.mozilla.org/Gecko:FullScreenAPI> has different requirements
    // for full screen mode, and do not have the concept of a full screen element stack.
    bool inLegacyMozillaMode = (flags & Element::LEGACY_MOZILLA_REQUEST);

    do {
        if (!element)
            element = document()->documentElement();

        // 1. If any of the following conditions are true, terminate these steps and queue a task to fire
        // an event named fullscreenerror with its bubbles attribute set to true on the context object's
        // node document:

        // The context object is not in a document.
        if (!element->inDocument())
            break;

        // The context object's node document, or an ancestor browsing context's document does not have
        // the fullscreen enabled flag set.
        if (checkType == EnforceIFrameAllowFullScreenRequirement && !fullScreenIsAllowedForElement(element))
            break;

        // The context object's node document fullscreen element stack is not empty and its top element
        // is not an ancestor of the context object. (NOTE: Ignore this requirement if the request was
        // made via the legacy Mozilla-style API.)
        if (!m_fullScreenElementStack.isEmpty() && !inLegacyMozillaMode) {
            Element* lastElementOnStack = m_fullScreenElementStack.last().get();
            if (lastElementOnStack == element || !lastElementOnStack->contains(element))
                break;
        }

        // A descendant browsing context's document has a non-empty fullscreen element stack.
        bool descendentHasNonEmptyStack = false;
        for (Frame* descendant = document()->frame() ? document()->frame()->tree().traverseNext() : 0; descendant; descendant = descendant->tree().traverseNext()) {
            if (!descendant->isLocalFrame())
                continue;
            ASSERT(toLocalFrame(descendant)->document());
            if (fullscreenElementFrom(*toLocalFrame(descendant)->document())) {
                descendentHasNonEmptyStack = true;
                break;
            }
        }
        if (descendentHasNonEmptyStack && !inLegacyMozillaMode)
            break;

        // This algorithm is not allowed to show a pop-up:
        //   An algorithm is allowed to show a pop-up if, in the task in which the algorithm is running, either:
        //   - an activation behavior is currently being processed whose click event was trusted, or
        //   - the event listener for a trusted click event is being handled.
        if (!UserGestureIndicator::processingUserGesture())
            break;

        // There is a previously-established user preference, security risk, or platform limitation.

        // 2. Let doc be element's node document. (i.e. "this")
        Document* currentDoc = document();

        // 3. Let docs be all doc's ancestor browsing context's documents (if any) and doc.
        Deque<Document*> docs;

        do {
            docs.prepend(currentDoc);
            currentDoc = currentDoc->ownerElement() ? &currentDoc->ownerElement()->document() : 0;
        } while (currentDoc);

        // 4. For each document in docs, run these substeps:
        Deque<Document*>::iterator current = docs.begin(), following = docs.begin();

        do {
            ++following;

            // 1. Let following document be the document after document in docs, or null if there is no
            // such document.
            Document* currentDoc = *current;
            Document* followingDoc = following != docs.end() ? *following : 0;

            // 2. If following document is null, push context object on document's fullscreen element
            // stack, and queue a task to fire an event named fullscreenchange with its bubbles attribute
            // set to true on the document.
            if (!followingDoc) {
                from(*currentDoc).pushFullscreenElementStack(element);
                addDocumentToFullScreenChangeEventQueue(currentDoc);
                continue;
            }

            // 3. Otherwise, if document's fullscreen element stack is either empty or its top element
            // is not following document's browsing context container,
            Element* topElement = fullscreenElementFrom(*currentDoc);
            if (!topElement || topElement != followingDoc->ownerElement()) {
                // ...push following document's browsing context container on document's fullscreen element
                // stack, and queue a task to fire an event named fullscreenchange with its bubbles attribute
                // set to true on document.
                from(*currentDoc).pushFullscreenElementStack(followingDoc->ownerElement());
                addDocumentToFullScreenChangeEventQueue(currentDoc);
                continue;
            }

            // 4. Otherwise, do nothing for this document. It stays the same.
        } while (++current != docs.end());

        // 5. Return, and run the remaining steps asynchronously.
        // 6. Optionally, perform some animation.
        m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
        document()->frameHost()->chrome().client().enterFullScreenForElement(element);

        // 7. Optionally, display a message indicating how the user can exit displaying the context object fullscreen.
        return;
    } while (0);

    m_fullScreenErrorEventTargetQueue.append(element ? element : document()->documentElement());
    m_fullScreenChangeDelayTimer.startOneShot(0, FROM_HERE);
}
コード例 #6
0
ファイル: deque.cpp プロジェクト: ziqifan16/Lintel
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());
}
コード例 #7
0
TEST( Deque, push_back)
{
	Deque<int> d;
	d.push_back(0);
	CHECK (	1 == d.size() );
}
コード例 #8
0
// 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();
}
コード例 #9
0
ファイル: deque.cpp プロジェクト: Flameeyes/stdcxx
void play_poker ()
{
    initialize_cards (deck_of_cards);
    deal_cards (current_hand.begin (), deck_of_cards.begin ()); 
}
コード例 #10
0
void FullscreenElementStack::webkitExitFullscreen()
{
    // The exitFullscreen() method must run these steps:

    // 1. Let doc be the context object. (i.e. "this")
    Document* currentDoc = document();

    // 2. If doc's fullscreen element stack is empty, terminate these steps.
    if (m_fullScreenElementStack.isEmpty())
        return;

    // 3. Let descendants be all the doc's descendant browsing context's documents with a non-empty fullscreen
    // element stack (if any), ordered so that the child of the doc is last and the document furthest
    // away from the doc is first.
    Deque<RefPtr<Document> > descendants;
    for (Frame* descendant = document()->frame() ?  document()->frame()->tree().traverseNext() : 0; descendant; descendant = descendant->tree().traverseNext()) {
        if (fullscreenElementFrom(descendant->document()))
            descendants.prepend(descendant->document());
    }

    // 4. For each descendant in descendants, empty descendant's fullscreen element stack, and queue a
    // task to fire an event named fullscreenchange with its bubbles attribute set to true on descendant.
    for (Deque<RefPtr<Document> >::iterator i = descendants.begin(); i != descendants.end(); ++i) {
        from(i->get())->clearFullscreenElementStack();
        addDocumentToFullScreenChangeEventQueue(i->get());
    }

    // 5. While doc is not null, run these substeps:
    Element* newTop = 0;
    while (currentDoc) {
        // 1. Pop the top element of doc's fullscreen element stack.
        from(currentDoc)->popFullscreenElementStack();

        //    If doc's fullscreen element stack is non-empty and the element now at the top is either
        //    not in a document or its node document is not doc, repeat this substep.
        newTop = fullscreenElementFrom(currentDoc);
        if (newTop && (!newTop->inDocument() || newTop->document() != currentDoc))
            continue;

        // 2. Queue a task to fire an event named fullscreenchange with its bubbles attribute set to true
        // on doc.
        addDocumentToFullScreenChangeEventQueue(currentDoc);

        // 3. If doc's fullscreen element stack is empty and doc's browsing context has a browsing context
        // container, set doc to that browsing context container's node document.
        if (!newTop && currentDoc->ownerElement()) {
            currentDoc = &currentDoc->ownerElement()->document();
            continue;
        }

        // 4. Otherwise, set doc to null.
        currentDoc = 0;
    }

    // 6. Return, and run the remaining steps asynchronously.
    // 7. Optionally, perform some animation.

    if (!document()->page())
        return;

    // Only exit out of full screen window mode if there are no remaining elements in the
    // full screen stack.
    if (!newTop) {
        document()->page()->chrome().client().exitFullScreenForElement(m_fullScreenElement.get());
        return;
    }

    // Otherwise, notify the chrome of the new full screen element.
    document()->page()->chrome().client().enterFullScreenForElement(newTop);
}
コード例 #11
0
ファイル: main.cpp プロジェクト: dbremner/airhan
void deque_test()
{
	Deque<int> deque;
	// something looks like...
	// 
	// come on migrate to google ut soon!
	assert(deque.Empty());
	deque.EnqueHead(1);
	assert( 1 == deque.DequeTail());
	assert( deque.Empty());
	// 4,1,2,3
	deque.EnqueHead(1);
	deque.EnqueTail(2);
	deque.EnqueTail(3);
	deque.EnqueHead(4);
	assert(deque.DequeTail() == 3);
	assert(deque.DequeTail() == 2);
	assert(deque.DequeHead() == 4);
	assert(deque.Empty() == false);
	assert(deque.DequeTail() == 1);
}
コード例 #12
0
ファイル: PointSET.cpp プロジェクト: caomw/KdTree-1
Deque<Point2D> PointSET::range(const RectHV& rect) {
	Deque<Point2D> points;
	for (Point2D p : set_)
		if (rect.contains(p)) points.addLast(p);
	return points;
}
コード例 #13
0
ファイル: Deque.cpp プロジェクト: c444b774/MediaTest
Deque::Deque(const Deque& other) : itsSize(other.size()),
                                   itsCap(other.capacity())
{
	copy_data(other.itsData);
}
コード例 #14
0
ファイル: 23.deque.special.cpp プロジェクト: Flameeyes/stdcxx
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);
}
コード例 #15
0
ファイル: deque.cpp プロジェクト: ziqifan16/Lintel
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);
}
コード例 #16
0
ファイル: mona.cpp プロジェクト: ondrik/mona-vata
int 
main(int argc, char *argv[])
{
  std::set_new_handler(&mem_error);

  if (!ParseArguments(argc, argv)) {
    Usage();
    exit(-1);
  }

  // Disable core dump
  struct rlimit r_core;
  r_core.rlim_cur = 0;
  r_core.rlim_max = 0;
  setrlimit(RLIMIT_CORE, &r_core);

  // Set demo limits 
  if (options.demo) {
    struct rlimit r_cpu, r_as;
    memlimit = true;

    r_cpu.rlim_cur = 30; // max 30 secs.
    r_cpu.rlim_max = 30;
    setrlimit(RLIMIT_CPU, &r_cpu);

    r_as.rlim_cur = 20971520; // max 20MB
    r_as.rlim_max = 20971520;
    setrlimit(RLIMIT_DATA, &r_as);

    signal(SIGXCPU, &cpuLimit);
  }

  initTimer();
  Timer timer_total;
  timer_total.start();
  
  ///////// PARSING ////////////////////////////////////////////////////////

  if (options.printProgress)
    cout << "MONA v" << VERSION << "-" << RELEASE <<  " for WS1S/WS2S\n"
      "Copyright (C) 1997-2008 BRICS\n\n"
      "PARSING\n";

  Timer timer_parsing;
  timer_parsing.start();

  loadFile(inputFileName);
  yyparse();
  MonaAST *ast = untypedAST->typeCheck();
  lastPosVar = ast->lastPosVar;
  allPosVar = ast->allPosVar;

  timer_parsing.stop();

  if (options.printProgress) {
    cout << "Time: ";
    timer_parsing.print();
  }

  delete untypedAST;

  if (options.dump) {
    // Dump AST for main formula, verify formulas, and assertion
    cout << "Main formula:\n";
    (ast->formula)->dump();
    Deque<ASTForm *>::iterator vf;
    Deque<char *>::iterator vt;
    for (vf = ast->verifyformlist.begin(), vt = ast->verifytitlelist.begin();
	 vf != ast->verifyformlist.end(); vf++, vt++) {
      cout << "\n\nFormula " << *vt << ":\n";
      (*vf)->dump();
    }
    cout << "\n\nAssertions:\n";
    (ast->assertion)->dump();
    cout << "\n";

    if (lastPosVar != -1)
      cout << "\nLastPos variable: " 
	   << symbolTable.lookupSymbol(lastPosVar) << "\n";
    if (allPosVar != -1)
      cout << "\nAllPos variable: " 
	   << symbolTable.lookupSymbol(allPosVar) << "\n";
    
    // Dump ASTs for predicates and macros
    PredLibEntry *pred = predicateLib.first();
    while (pred != NULL) {
      if (pred->isMacro)
	cout << "\nMacro '";
      else
	cout << "\nPredicate '";
      cout << symbolTable.lookupSymbol(pred->name) 
	   << "':\n";
      (pred->ast)->dump();
      cout << "\n";
      pred = predicateLib.next();
    }

    // Dump restrictions
    if (symbolTable.defaultRestriction1) {
      cout << "\nDefault first-order restriction (" 
	   << symbolTable.lookupSymbol(symbolTable.defaultIdent1) << "):\n";
      symbolTable.defaultRestriction1->dump();
      cout << "\n";
    }
    if (symbolTable.defaultRestriction2) {
      cout << "\nDefault second-order restriction (" 
	   << symbolTable.lookupSymbol(symbolTable.defaultIdent2) << "):\n";
      symbolTable.defaultRestriction2->dump();
      cout << "\n";
    }

    Ident id;
    for (id = 0; id < (Ident) symbolTable.noIdents; id++) {
      Ident t;
      ASTForm *f = symbolTable.getRestriction(id, &t);
      if (f) {
	cout << "\nRestriction for #" << id << " (" 
	     << symbolTable.lookupSymbol(id) << "):";
	if (t != -1)
	  cout << " default\n";
	else {
	  cout << "\n";
	  f->dump();
	  cout << "\n";
	}
      }
    }
  }

  if (options.mode != TREE && 
      (options.graphvizSatisfyingEx || options.graphvizCounterEx ||
       options.inheritedAcceptance)) 
    cout << "Warning: options -gc, -gs, and -h are only used in tree mode\n";
  if (options.mode == TREE && options.graphvizDFA)
    cout << "Warning: option -gw is only used in linear mode\n";
  
  if (options.mode == TREE && (options.dump || options.whole) && 
      !options.externalWhole)
    printGuide();


  ///////// CODE GENERATION ////////////////////////////////////////////////
  
  if (options.printProgress)
    cout << "\nCODE GENERATION\n";
  Timer timer_gencode;
  timer_gencode.start();
  
  // Generate code
  codeTable = new CodeTable;
  VarCode formulaCode = ast->formula->makeCode();
  VarCode assertionCode = ast->assertion->makeCode();
  Deque<VarCode> verifyCode;
  /* #warning NEW: 'VERIFY' */
  for (Deque<ASTForm *>::iterator i = ast->verifyformlist.begin(); 
       i != ast->verifyformlist.end(); i++)
    verifyCode.push_back((*i)->makeCode());

  // Implicitly assert restrictions for all global variables
  for (IdentList::iterator i = ast->globals.begin(); 
       i != ast->globals.end(); i++)
    assertionCode = andList(assertionCode, getRestriction(*i, NULL));

  // Restrict assertion if not trivial
  if (assertionCode.code->kind != cTrue)
    assertionCode = codeTable->insert
      (new Code_Restrict(assertionCode, assertionCode.code->pos));

  // Add assertion to main formula and to all verify formulas
  for (Deque<VarCode>::iterator i = verifyCode.begin(); 
       i != verifyCode.end(); i++) {
    assertionCode.code->refs++;
    *i = andList(*i, VarCode(copy(assertionCode.vars), assertionCode.code));
  }
  formulaCode = andList(formulaCode, assertionCode);

  timer_gencode.stop();
  if (options.printProgress) {
    codeTable->print_statistics();
    /* if (options.dump && options.statistics)
      codeTable->print_sizes(); */
    cout << "Time: ";
    timer_gencode.print();
  }
  
  ///////// REORDER BDD OFFSETS ////////////////////////////////////////////

  if (options.reorder >= 1) {
    Timer timer_reorder;
    timer_reorder.start();
    if (options.printProgress)
      cout << "\nREORDERING\n";

    // reorder using heuristics
    offsets.reorder();
    
    // regenerate DAG in new codetable
    CodeTable *oldCodeTable = codeTable, *newCodeTable = new CodeTable;
    IdentList emptylist;
    codeTable = newCodeTable;
    regenerate = true; // force making new nodes
    VarCode newcode = formulaCode.substCopy(&emptylist, &emptylist);
    Deque<VarCode> newverifycode;
    for (Deque<VarCode>::iterator i = verifyCode.begin(); 
	 i != verifyCode.end(); i++)
      newverifycode.push_back((*i).substCopy(&emptylist, &emptylist));
    codeTable->clearSCTable();
    regenerate = false;
    codeTable = oldCodeTable;
    formulaCode.remove();
    for (Deque<VarCode>::iterator i = verifyCode.begin(); 
	 i != verifyCode.end(); i++)
      (*i).remove();
    formulaCode = newcode;
    verifyCode.reset();
    for (Deque<VarCode>::iterator i = newverifycode.begin(); 
	 i != newverifycode.end(); i++)
      verifyCode.push_back(*i);
    delete oldCodeTable;
    codeTable = newCodeTable;

    if (options.printProgress) {
      codeTable->print_statistics2();
      cout << "Time: ";
      timer_reorder.print();
    }
  }

  ///////// REDUCTION AND CODE DUMPING /////////////////////////////////////

  if (options.optimize >= 1) {
    if (options.printProgress)
      cout << "\nREDUCTION\n";
    Timer timer_reduction;
    timer_reduction.start();
    
    // Reduce
    formulaCode.reduceAll(&verifyCode);

    timer_reduction.stop();
    if (options.printProgress) {
      codeTable->print_reduction_statistics();
      /* if (options.dump && options.statistics)
	 codeTable->print_sizes(); */
      cout << "Time: ";
      timer_reduction.print();
    }
  }
  
  if (options.dump) {
    // Dump symboltable
    symbolTable.dump();
    
    // Dump code
    cout << "\nMain formula:\n";
    formulaCode.dump();
    cout << "\n\n";
    Deque<VarCode>::iterator i;
    Deque<char *>::iterator j;
    for (i = verifyCode.begin(), j = ast->verifytitlelist.begin(); 
	 i != verifyCode.end(); i++, j++) {
      cout << "Formula " << *j << ":\n";
      (*i).dump();
      cout << "\n\n";
    }
  }
  
  if (options.graphvizDAG) {
    printf("digraph MONA_CODE_DAG {\n"
	   " size = \"7.5,10.5\";\n"
	   " main [shape = plaintext];\n"
	   " main -> L%lx;\n", 
	   (unsigned long) formulaCode.code);
    formulaCode.code->viz();
    Deque<VarCode>::iterator i;
    Deque<char *>::iterator j;
    for (i = verifyCode.begin(), j = ast->verifytitlelist.begin(); 
	 i != verifyCode.end(); i++, j++) {
      printf(" \"%s\" [shape = plaintext];\n"
	     " \"%s\" -> L%lx;\n", 
	     *j, *j, (unsigned long) (*i).code);
      (*i).code->viz();
    }
    formulaCode.unmark();
    for (Deque<VarCode>::iterator i = verifyCode.begin(); 
	 i != verifyCode.end(); i++)
      (*i).unmark();
    cout << "}\n";
  }

  ///////// AUTOMATON CONSTRUCTION /////////////////////////////////////////

  // Make variable lists
  Deque<char *> *verifytitlelist = ast->verifytitlelist.copy();
  if (lastPosVar != -1)
    ast->globals.remove(lastPosVar); 
  if (allPosVar != -1)
    ast->globals.remove(allPosVar); 
  ast->globals.sort(); // sort by id (= index)
  int numVars = ast->globals.size();
  int ix = 0;
  char **vnames = new char*[numVars];
  unsigned *offs = new unsigned[numVars];
  char *types = new char[numVars];
  int **univs = new int*[numVars];
  int *trees = new int[numVars];
  SSSet *statespaces = new SSSet[numVars];
  IdentList sign, freeVars;
  IdentList::iterator id;
  for (id = ast->globals.begin(); id != ast->globals.end(); id++, ix++) {
    statespaces[ix] = stateSpaces(*id);
    vnames[ix] = symbolTable.lookupSymbol(*id);
    offs[ix] = offsets.off(*id);
    sign.push_back(ix);
    freeVars.push_back(*id);
    switch (symbolTable.lookupType(*id)) {
    case VarnameTree:
      trees[ix] = 1;
      break;
    default:
      trees[ix] = 0;
    }
    IdentList *uu = symbolTable.lookupUnivs(*id);
    if (uu) {
      unsigned j;
      univs[ix] = new int[uu->size()+1];
      for (j = 0; j < uu->size(); j++)
	univs[ix][j] = symbolTable.lookupUnivNumber(uu->get(j));
      univs[ix][j] = -1;
    }
    else
      univs[ix] = 0;
    switch (symbolTable.lookupType(*id)) 
      {
      case Varname0: 
	types[ix] = 0;
	break;
      case Varname1: 
	types[ix] = 1;
	break;
      default:
	types[ix] = 2;
	break;
      }
  }
  
  if (options.printProgress)
    cout << "\nAUTOMATON CONSTRUCTION\n";

  Timer timer_automaton;
  timer_automaton.start();
  
  DFA *dfa = 0;
  Deque<DFA *> dfalist;
  GTA *gta = 0;
  Deque<GTA *> gtalist;
  
  // Initialize
  bdd_init();
  codeTable->init_print_progress();

  if (options.mode != TREE) { 
    // Generate DFAs
    dfa = formulaCode.DFATranslate();
    if (lastPosVar != -1)
      dfa = st_dfa_lastpos(dfa, lastPosVar);
    if (allPosVar != -1)
      dfa = st_dfa_allpos(dfa, allPosVar);
    for (Deque<VarCode>::iterator i = verifyCode.begin(); 
	 i != verifyCode.end(); i++) {
      DFA *d = (*i).DFATranslate();
      if (lastPosVar != -1)
	d = st_dfa_lastpos(d, lastPosVar);
      if (allPosVar != -1)
	d = st_dfa_allpos(d, allPosVar);
      dfalist.push_back(d);
    }
  }
  else { 
    // Generate GTAs
    gta = formulaCode.GTATranslate();
    if (allPosVar != -1)
      gta = st_gta_allpos(gta, allPosVar);
    for (Deque<VarCode>::iterator i = verifyCode.begin(); 
	 i != verifyCode.end(); i++) {
      GTA *g = (*i).GTATranslate();
      if (allPosVar != -1)
	g = st_gta_allpos(g, allPosVar);
      gtalist.push_back(g);
    }
  }
  formulaCode.remove();
  for (Deque<VarCode>::iterator i = verifyCode.begin(); 
       i != verifyCode.end(); i++)
    (*i).remove();
  
  timer_automaton.stop();
  if (options.printProgress) {
    if (options.statistics)
      cout << "Total automaton construction time: ";
    else
      cout << "Time: ";
    timer_automaton.print();
  }

  delete ast;
  delete codeTable;

  ///////// PRINT AUTOMATON ////////////////////////////////////////////////

  DFA *dfa2 = dfa;
  GTA *gta2 = gta;
  Deque<DFA *> *dfalist2 = &dfalist;
  Deque<GTA *> *gtalist2 = &gtalist;

  if (options.whole &&
      !options.externalWhole)
    cout << "\n";
  if (options.unrestrict) {
    // Unrestrict automata
    if (options.mode != TREE) {
      DFA *t = dfaCopy(dfa2);
      dfaUnrestrict(t);
      dfa2 = dfaMinimize(t);
      dfaFree(t);
      dfalist2 = new Deque<DFA *>;
      for (Deque<DFA *>::iterator i = dfalist.begin(); i != dfalist.end(); i++) {
	t = dfaCopy(*i);
	dfaUnrestrict(t);
	dfalist2->push_back(dfaMinimize(t));
	dfaFree(t);
      }
    }
    else {
      GTA *t = gtaCopy(gta2);
      gtaUnrestrict(t);
      gta2 = gtaMinimize(t);
      gtaFree(t);
      gtalist2 = new Deque<GTA *>;
      for (Deque<GTA *>::iterator i = gtalist.begin(); i != gtalist.end(); i++) {
	t = gtaCopy(*i);
	gtaUnrestrict(t);
	gtalist2->push_back(gtaMinimize(t));
	gtaFree(t);	
      }
    }
  }

  if (options.whole)
    // Print whole automaton
    if (options.mode != TREE) {
      if (options.externalWhole) {
	if (!dfalist.empty())
	  cout << "Main formula:\n";
	DFA *t = dfaCopy(dfa2);
	st_dfa_replace_indices(t, &sign, &freeVars, false, true);
	dfaExport(t, 0, numVars, vnames, types);
	dfaFree(t);
	Deque<DFA *>::iterator i;
	Deque<char *>::iterator j;
	for (i = dfalist2->begin(), j = verifytitlelist->begin();
	     i != dfalist2->end(); i++, j++) {
	  cout << "\nFormula " << *j << ":\n";
	  t = dfaCopy(*i);
	  st_dfa_replace_indices(t, &sign, &freeVars, false, true);
	  dfaExport(t, 0, numVars, vnames, types);
	  dfaFree(t);
	}
      }
      else if (options.graphvizDFA) {
	dfaPrintGraphviz(dfa2, numVars, offs);
	for (Deque<DFA *>::iterator i = dfalist2->begin(); i != dfalist2->end(); i++)
	  dfaPrintGraphviz(*i, numVars, offs);
      }
      else {
	if (!dfalist.empty())
	  cout << "Main formula:\n";
	dfaPrint(dfa2, numVars, vnames, offs);
	Deque<DFA *>::iterator i;
	Deque<char *>::iterator j;
	for (i = dfalist2->begin(), j = verifytitlelist->begin(); 
	     i != dfalist2->end(); i++, j++) {
	  cout << "\nFormula " << *j << ":\n";
	  dfaPrint(*i, numVars, vnames, offs);
	}
      }
    }
    else {
      if (options.externalWhole) {
	if (!gtalist.empty())
	  cout << "Main formula:\n";
	GTA *t = gtaCopy(gta2);
	st_gta_replace_indices(t, &sign, &freeVars, false, true);
	gtaExport(t, 0, numVars, vnames, types, statespaces, 
		  options.inheritedAcceptance);
	gtaFree(t);
	Deque<GTA *>::iterator i;
	Deque<char *>::iterator j;
	for (i = gtalist2->begin(), j = verifytitlelist->begin();
	     i != gtalist2->end(); i++, j++) {
	  cout << "\nFormula " << *j << ":\n";
	  t = gtaCopy(*i);
	  st_gta_replace_indices(t, &sign, &freeVars, false, true);
	  gtaExport(t, 0, numVars, vnames, types, statespaces, 
		    options.inheritedAcceptance);
	  gtaFree(t);
	}
      }
      else {
	if (!gtalist.empty())
	  cout << "Main formula:\n";
	gtaPrint(gta2, offs, numVars, vnames, 
		 options.inheritedAcceptance);
	Deque<GTA *>::iterator i;
	Deque<char *>::iterator j;
	for (i = gtalist2->begin(), j = verifytitlelist->begin();
	     i != gtalist2->end(); i++, j++) {
	  cout << "\nFormula " << *j << ":\n";
	  gtaPrint(*i, offs, numVars, vnames, 
		   options.inheritedAcceptance);
	}
      }
    }
  else if (options.analysis &&
	   !options.graphvizSatisfyingEx &&
	   !options.graphvizCounterEx &&
	   options.printProgress) {
    // Print summary only
    if (options.mode != TREE) {
      if (!dfalist.empty())
	cout << "Main formula:";
      dfaPrintVitals(dfa2);
      Deque<DFA *>::iterator i;
      Deque<char *>::iterator j;
      for (i = dfalist2->begin(), j = verifytitlelist->begin(); 
	   i != dfalist2->end(); i++, j++) {
	cout << "\nFormula " << *j << ":";
	dfaPrintVitals(*i);
      }
    }
    else {
      if (!gtalist.empty())
	cout << "Main formula:";
      gtaPrintTotalSize(gta2);
      Deque<GTA *>::iterator i;
      Deque<char *>::iterator j;
      for (i = gtalist2->begin(), j = verifytitlelist->begin(); 
	   i != gtalist2->end(); i++, j++) {
	cout << "\nFormula " << *j << ":";
	gtaPrintTotalSize(*i);
      }
    }
  }
  if (dfa2 != dfa) {
    dfaFree(dfa2);
    for (Deque<DFA *>::iterator i = dfalist2->begin(); i != dfalist2->end(); i++) 
      dfaFree(*i);
    delete dfalist2;
  }
  if (gta2 != gta) {
    gtaFree(gta2);
    for (Deque<GTA *>::iterator i = gtalist2->begin(); i != gtalist2->end(); i++) 
      gtaFree(*i);
    delete gtalist2;
  }

  ///////// AUTOMATON ANALYSIS /////////////////////////////////////////////

  if (options.analysis) {
    if (options.printProgress)
      cout << "\nANALYSIS\n";
    
    if (options.mode != TREE) {
      if (!dfalist.empty())
	cout << "Main formula:\n";
      dfaAnalyze(dfa, numVars, vnames, offs, types, 
		 options.treemodeOutput);
      Deque<DFA *>::iterator i;
      Deque<char *>::iterator j;
      for (i = dfalist.begin(), j = verifytitlelist->begin(); 
	   i != dfalist.end(); i++, j++) {
	cout << "\nFormula " << *j << ":\n";
	dfaAnalyze(*i, numVars, vnames, offs, types, 
		   options.treemodeOutput);
      }
    }
    else {
      if (numTypes == 0 || options.treemodeOutput) {
	if (!gtalist.empty())
	  cout << "Main formula:\n";
	gtaAnalyze(gta, numVars, vnames, offs,
		   options.graphvizSatisfyingEx,
		   options.graphvizCounterEx);
	Deque<GTA *>::iterator i;
	Deque<char *>::iterator j;
	for (i = gtalist.begin(), j = verifytitlelist->begin(); 
	     i != gtalist.end(); i++, j++) {
	  cout << "\nFormula " << *j << ":\n";
	  gtaAnalyze(*i, numVars, vnames, offs,
		     options.graphvizSatisfyingEx,
		     options.graphvizCounterEx);
	}
      }
      else {
	if (options.graphvizSatisfyingEx ||
	    options.graphvizCounterEx)
	  cout << "Graphviz output of typed trees not implemented.\n";
	if (!gtalist.empty())
	  cout << "Main formula:\n";
	gtaTypeAnalyze(gta, numVars, vnames, types, offs, univs, trees);
	Deque<GTA *>::iterator i;
	Deque<char *>::iterator j;
	for (i = gtalist.begin(), j = verifytitlelist->begin(); 
	     i != gtalist.end(); i++, j++) {
	  cout << "\nFormula " << *j << ":\n";
	  gtaTypeAnalyze(*i, numVars, vnames, types, offs, univs, trees);
	}
      }
    }
  }

  ///////// CLEAN UP ///////////////////////////////////////////////////////

  if (options.mode != TREE) {
    dfaFree(dfa);
    for (Deque<DFA *>::iterator i = dfalist.begin(); i != dfalist.end(); i++)
      dfaFree(*i);
  }
  else {
    gtaFree(gta);
    for (Deque<GTA *>::iterator i = gtalist.begin(); i != gtalist.end(); i++)
      gtaFree(*i);
    freeGuide();
  }
  delete verifytitlelist;

  Deque<FileSource *>::iterator i;
  for (i = source.begin(); i != source.end(); i++)
    delete *i;
  
  for (ix = 0; ix < numVars; ix++) {
    delete[] univs[ix];
    mem_free(statespaces[ix]);
  }
  delete[] statespaces;
  delete[] vnames;
  delete[] offs;
  delete[] types;
  delete[] univs;
  delete[] trees;
  freeTreetypes();
    
  if (options.statistics)
    print_statistics();

  if (options.time) {
    timer_total.stop();
    cout << "\nTotal time:     ";
    timer_total.print();
    print_timing();
  }
  else if (options.printProgress) { 
    timer_total.stop();
    cout << "\nTotal time: ";
    timer_total.print();
  }
#ifdef MAXALLOCATED
  cout << "Maximum space allocated: " << (maxallocated+524288)/1048576 << " MB\n";
#endif
}
コード例 #17
0
ファイル: deque.cpp プロジェクト: ziqifan16/Lintel
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);
}
コード例 #18
0
ファイル: Deque.cpp プロジェクト: cheekiatng/webkit
TEST(WTF_Deque, Remove)
{
    Deque<int> deque;
    deque.append(11);
    deque.prepend(10);
    deque.append(12);
    deque.append(13);

    EXPECT_EQ(10, deque.first());
    EXPECT_EQ(13, deque.last());

    deque.removeLast();
    EXPECT_EQ(10, deque.first());
    EXPECT_EQ(12, deque.last());

    deque.removeFirst();
    EXPECT_EQ(11, deque.first());
    EXPECT_EQ(12, deque.last());

    deque.removeFirst();
    EXPECT_EQ(12, deque.first());
    EXPECT_EQ(12, deque.last());

    deque.removeLast();
    EXPECT_TRUE(deque.isEmpty());
}
コード例 #19
0
TEST( Deque, construction)
{
	Deque<int> d;
	CHECK ( 0 == d.size() );
}
コード例 #20
0
ファイル: main.cpp プロジェクト: Bplusplus/DataStructures
int main()
{
    srand(time(NULL));
    int counter=0;
    int random[100];
    int n =5;


    std::cout<<"---------Deque Tests start here------------------v"<<std::endl;

    Deque Q;
    for(int i=0;i<100;i++)
        {
        random[i]=rand() % 10;
        Q.addRight(random[i]);
        counter++;
        if(counter==10)
            {
                counter=0;
                std::cout<<std::endl;
            }

        }

        std::cout<<std::endl;
        std::cout<<"Default 100 Deque filled completely listed head to tail"<<std::endl;
        std::cout<<Q.listLeftRight()<<std::endl;
        std::cout<<"Default 100 Deque filled completely listed tail to head"<<std::endl;
        std::cout<<Q.listRightLeft()<<std::endl;

         std::cout<<"Now removing a random number of elements from the left"<<std::endl;
      for(int i=0;i<random[1];i++)
        {
        std::cout<<Q.getLeft()<<std::endl;
        }

        std::cout<<"How the deque looks now, listed tail to head"<<std::endl;
        std::cout<<Q.listRightLeft()<<std::endl;

        std::cout<<"How the deque looks now, listed head to tail"<<std::endl;
        std::cout<<Q.listLeftRight()<<std::endl;

        std::cout<<"Now removing a random number of elements from the right"<<std::endl;
      for(int i=0;i<random[99];i++)
        {
        std::cout<<Q.getRight()<<std::endl;
        }
        std::cout<<std::endl<<std::endl;

        std::cout<<"How the deque looks now, listed tail to head"<<std::endl;
        std::cout<<Q.listRightLeft()<<std::endl;

        std::cout<<"How the deque looks now, listed head to tail"<<std::endl;
        std::cout<<Q.listLeftRight()<<std::endl;

    Deque Q1(n);

    for(int i=0;i<6;i++)
        {
        Q1.addRight(random[i]);

        }

        std::cout<<std::endl<<std::endl<<std::endl;

        std::cout<<Q1.listLeftRight()<<std::endl;
        std::cout<<"Deque 6 filled completely listed head to tail"<<std::endl;
        std::cout<<Q1.listRightLeft()<<std::endl;
        std::cout<<"Deque 6 filled completely listed tail to head"<<std::endl;


        std::cout<<std::endl<<std::endl<<std::endl;

        std::cout<<Q1.getLeft()<<std::endl;
        std::cout<<Q1.getLeft()<<std::endl;

        std::cout<<"How the deque looks now, listed head to tail"<<std::endl<<Q1.listLeftRight()<<std::endl;
        std::cout<<"How the deque looks now, listed tail to head"<<std::endl<<Q1.listRightLeft()<<std::endl;

        std::cout<<"Adding 9 to the array on the right four times"<<std::endl;
        Q1.addRight(9);
        Q1.addRight(9);
        Q1.addRight(9);
        Q1.addRight(9);

        std::cout<<std::endl;

        std::cout<<"How the deque looks now, listed head to tail"<<std::endl<<Q1.listLeftRight()<<std::endl;
        std::cout<<"How the deque looks now, listed tail to head"<<std::endl<<Q1.listRightLeft()<<std::endl;

std::cout<<"v--------------Stack Tests start here------------------v"<<std::endl;


    Stack S1(n);

    for(int i=0;i<5;i++)
        {
        random[i]=rand() % 10;
        S1.push(random[i]);
        }
        std::cout<<S1.peek()<<std::endl;
    for(int i=0;i<3;i++)
        {
        std::cout<<S1.pop()<<std::endl;
        }
        std::cout<<S1.peek()<<std::endl;
std::cout<<"v--------------Priority Queue Tests start here------------------v"<<std::endl;
    PQueue PQ1(n);
      for(int i=0;i<100;i++)
        {
        random[i]=rand() % 10;
        PQ1.addValue(random[i]);
        }
        for(int i=0;i<5;i++)
        {
        std::cout<<PQ1.removeSmallest()<<' ';
        }
        std::cout<<std::endl;
         for(int i=0;i<5;i++)
        {
         PQ1.addValue(random[i]);
        }
        for(int i=0;i<5;i++)
        {
        std::cout<<PQ1.removeLargest()<<' ';
        }

    return 0;
}
コード例 #21
0
TEST (Deque, push_front)
{
	Deque<int> d;
	d.push_front(0);
	CHECK ( 1 == d.size() );
}
コード例 #22
0
ファイル: DequeClientAGS.cpp プロジェクト: ldfaiztt/cse250
int main(int argc, char* argv[]) {
    vector<Deque<StringWrap>*>* chains = new vector<Deque<StringWrap>*>();
    string infileName = (argc==1) ? "" : argv[1];
    ifstream* INFILEp = new ifstream(infileName.c_str(), ios_base::in);
    int n = (argc==2) ? 1 : atoi(argv[2]); //Intended for debugging
    int numItems = 0; //Intended for debugging
    //Intended for debugging - sets the vector size of each deque in chains
    int numDeque = (argc==4) ? atoi(argv[3]) : 100;
    //Holds the index of the longest deques in chains
    vector<int>* longestWord = new vector<int>;
    int longestWordLength = 0;
    string word;

    while((*INFILEp) >> word && numItems < n) {
        StringWrap sw(word);
        bool attachedWord;
        //Makes sure that the length of word is at least 3
        if(word.length()<3) {
            attachedWord = true;
        }
        else {
            sw.makeLower();
            sw.trimNonAlpha();
            attachedWord = ((sw.str().length()<3 || (!sw.isAlpha()))) ? true : false;
        }
        numItems = (argc==2) ? numItems : ++numItems;

        //Attaches a word to an already existing chain if possible
        for(int i=0; (i<chains->size())&&(attachedWord == false); i++) {
            //Makes sure a word chain never contains sequences such as "hip hop hip hop"
            if((sw.str().compare(chains->at(i)->previousFront().str())==0) ||
                    (sw.str().compare(chains->at(i)->previousRear().str()))==0) {
                attachedWord = true;
            }
            else if(ed1(chains->at(i)->front().str(), sw.str()) == true) {
                chains->at(i)->pushFront(sw);
                attachedWord = true;
            }
            else if(ed1(chains->at(i)->rear().str(), sw.str()) == true) {
                chains->at(i)->pushRear(sw);
                attachedWord = true;
            }
            else {
                //Do Nothing
            }

            //Helps determine the chains with the longest words
            switch(attachedWord) {
            case true :
                if(sw.str().length() > longestWordLength) {
                    longestWord->clear();
                    longestWord->push_back(i);
                    longestWordLength = sw.str().length();
                }
                else if(sw.str().length() == longestWordLength) {
                    if(chains->at(i) == chains->at(longestWord->back())) {
                        //Do Nothing
                    }
                    else {
                        longestWord->push_back(i);
                    }
                }
                break;
            default :
                break;
            }
        }

        //Creates a new chain when word can not be attached to any
        if(!attachedWord) {
            Deque<StringWrap>* sq = new Deque<StringWrap>(numDeque);
            sq->pushFront(sw);
            chains->push_back(sq);
            cout << "Added chain number " << chains->size() << endl;

            //Helps determine the chains with the longest words
            if(sw.str().length() > longestWordLength) {
                longestWord->clear();
                longestWord->push_back(chains->size()-1);
                longestWordLength = sw.str().length();
            }
            else if(sw.str().length() == longestWordLength) {
                longestWord->push_back(chains->size()-1);
            }
            else {
                //Do Nothing
            }
        }
    }

    if(argc == 1) {
        cerr << "Please specify an appropriate filename!" << endl;
    }
    //Makes sure that an appropriate number of words is specified in argv[2]
    else if((argc==3) && (atoi(argv[2])<1)) {
        cerr << "No word chains were formed." << endl;
        cerr << "Please make sure to specify a number of words higher than 0!"<< endl;
    }
    else if(chains->size() == 0) {
        cout << "No word chains were formed from the words read in " <<  argv[1] << endl;
    }
    else {
        vector<Deque<StringWrap>*>* report = new vector<Deque<StringWrap>*>();
        cout << "Longest chain(s) found:" << endl;
        //Determines what the longest word chains are
        for(int i=0; i<chains->size(); i++) {
            if(report->empty()) {
                report->push_back(chains->at(i));
            }
            else if(chains->at(i)->size() > report->back()->size()) {
                report->clear();
                report->push_back(chains->at(i));
            }
            else if(chains->at(i)->size() == report->back()->size()) {
                report->push_back(chains->at(i));
            }
            else {
                //Do Nothing
            }
        }
        //Outputs the longest word chains
        for(int i=0; i<report->size(); i++) {
            cout << report->at(i)->toString() << endl;
        }
        delete report;

        cout << "Chain(s) with the longest word(s):" << endl;
        //Outputs the chains with the longest words
        for(int i=0; i<longestWord->size(); i++) {
            cout << chains->at(longestWord->at(i))->toString() << endl;
        }
    }
    INFILEp->close();
    return (0);
}
コード例 #23
0
ファイル: Thread.cpp プロジェクト: larsiusprime/hxcpp
	static void clean(hx::Object *inObj)
	{
		Deque *d = dynamic_cast<Deque *>(inObj);
		if (d) d->Clean();
	}
コード例 #24
0
ファイル: main.cpp プロジェクト: m-chrome/trains_cpp
int main(int argc, char* argv[])
{
    char op, dir;           //op - операция (+/-), dir - направление (</>)
    size_t num;             //Число вагонов для операции (целое)

    if (argc!=3)             //Проверка на аргументы
    {
        printf("There is a wrong number of arguments!");
        return 1;
    }

    FILE* input=fopen(argv[1], "r");
    //Файлопроверка
    if (CheckFile(input)==false)
    {
        return 1;
    }

    FILE* output=fopen(argv[2], "w");
    //Файлопроверка
    if (CheckFile(output)==false)
    {
        fclose(input);
        return 1;
    }

    fscanf(input,"%u", &num);
    //Считывание первого числа вагонов

    Deque d;
    //Инициализация объекта d класса Deque
    //Конструктор инициализирует начальные данные нового объекта класса

    d.PushBack(num);
    //Заполнение массива вагонов первый раз

    d.PrintResult(output);
    //Вывод данных в консоль и файл

    while (fscanf(input, " %c%c%u", &op, &dir, &num)==3)
    {
        if (op=='+')
        //Ветка прицепления вагонов к составу
        {
            if(dir=='>')
            //Прицепить вагоны спереди
            {
                d.PushFront(num);
            }
            else if (dir=='<')
            //Прицепить вагоны сзади
            {
                d.PushBack(num);
            }
        }
        else if (op == '-')
        //Ветка отцепления вагонов от состава
        {
            if(dir == '<')
            //Удалить вагоны с конца
            {
                if (d.PopBack(num)==false)
                {
                    printf("Fatal operation:\nYou have negative number of wagons!");
                    return 1;
                }
            }
            else if (dir == '>')
            //Удалить вагоны с начала
            {
                if (d.PopFront(num)==false)
                {
                    printf("Fatal operation:\nYou have negative number of wagons!");
                    return 1;
                }
            }
        }
        d.PrintResult(output);
        //Вывод в файловый поток output и в консоль
    }
    fclose(input);
    fclose(output);
    return 0;
    //Программа вызывает деструктор
}
コード例 #25
0
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;
}
コード例 #26
0
ファイル: history.cpp プロジェクト: descent/progs
int main()
{

#if 0
  CString cstr;

  cstr.init("abc");
  cstr.print();
  printf("\n");

  Deque<CString> deque;
  deque.init();

  deque.push_back(cstr);

  CString ps;
  ps = "102";

  cstr.init("def");
  deque.push_back(cstr);

  deque.print();
  deque.back(0, ps);
  ps.print();
  printf("\n");
#endif

#if 1
  setlocale(LC_ALL, "");

  initscr();
  keypad(stdscr,true);
  curs_set(0);
  // KEY_UP
  // KEY_DOWN

  //Deque<string> deque;
  Deque<CString> deque;

  deque.init();

  move(0,0);
  int fail_time=1;
  while(1)
  {
    char str[128];
    getstr(str);
    move(0,0);
    //std::string s(str);
    CString s;
    s.init(str);
    if (deque.push_back(s) == false)
    {
      mvprintw(20, 0, "push back fail ## %d", fail_time++);
      deque.pop_front();
      deque.push_back(s);
    }

    deque.print();

    int index=0;
    noecho();
    //string ps;
    CString ps;
    while(1)
    {
      mvprintw(17, 0, "index: %d", index);
      refresh();
      int ch = getch();
      switch(ch)
      {
        case KEY_UP:
        {
          ++index;
          if (deque.back(index, ps) == true)
          {
            mvprintw(0, 15, "%s", ps.c_str());
          }
          else
            --index;
          break;
        }
        case KEY_DOWN:
        {
          --index;
          if (deque.back(index, ps) == true)
          {
            mvprintw(0, 15, "%s", ps.c_str());
          }
          else
          {
            //mvprintw(17, 5, "back fail");
            ++index;
          }
          break;
        }
        case 'q':
        {
          goto end;
        }
        default:
        {
          ungetch(ch);
          move(0, 0);
          goto outer;
          break;
        }
      }
      mvprintw(17, 0, "index: %d", index);
      refresh();
    }
    outer:
    echo();
  }
end:
  endwin();
#endif
  return 0;
}