1//
2// Copyright 2011 The Android Open Source Project
3//
4#ifndef MOCKDIRECTORYWALKER_H
5#define MOCKDIRECTORYWALKER_H
6
7#include <utils/Vector.h>
8#include <utils/String8.h>
9#include <utility>
10#include "DirectoryWalker.h"
11
12using namespace android;
13using std::pair;
14
15// String8 Directory Walker
16// This is an implementation of the Directory Walker abstraction that is built
17// for testing.
18// Instead of system calls it queries a private data structure for the directory
19// entries. It takes a path and a map of filenames and their modification times.
20// functions are inlined since they are short and simple
21
22class StringDirectoryWalker : public DirectoryWalker {
23public:
24    StringDirectoryWalker(String8& path, Vector< pair<String8,time_t> >& data)
25        :  mPos(0), mBasePath(path), mData(data) {
26        //fprintf(stdout,"StringDW built to mimic %s with %d files\n",
27        //       mBasePath.string());
28    };
29    // Default copy constructor, and destructor are fine
30
31    virtual bool openDir(String8 path) {
32        // If the user is trying to query the "directory" that this
33        // walker was initialized with, then return success. Else fail.
34        return path == mBasePath;
35    };
36    virtual bool openDir(const char* path) {
37        String8 p(path);
38        openDir(p);
39        return true;
40    };
41    // Advance to next entry in the Vector
42    virtual struct dirent* nextEntry() {
43        // Advance position and check to see if we're done
44        if (mPos >= mData.size())
45            return NULL;
46
47        // Place data in the entry descriptor. This class only returns files.
48        mEntry.d_type = DT_REG;
49        mEntry.d_ino = mPos;
50        // Copy chars from the string name to the entry name
51        size_t i = 0;
52        for (i; i < mData[mPos].first.size(); ++i)
53            mEntry.d_name[i] = mData[mPos].first[i];
54        mEntry.d_name[i] = '\0';
55
56        // Place data in stats
57        mStats.st_ino = mPos;
58        mStats.st_mtime = mData[mPos].second;
59
60        // Get ready to move to the next entry
61        mPos++;
62
63        return &mEntry;
64    };
65    // Get the stats for the current entry
66    virtual struct stat*   entryStats() {
67        return &mStats;
68    };
69    // Nothing to do in clean up
70    virtual void closeDir() {
71        // Nothing to do
72    };
73    virtual DirectoryWalker* clone() {
74        return new StringDirectoryWalker(*this);
75    };
76private:
77    // Current position in the Vector
78    size_t mPos;
79    // Base path
80    String8 mBasePath;
81    // Data to simulate a directory full of files.
82    Vector< pair<String8,time_t> > mData;
83};
84
85#endif // MOCKDIRECTORYWALKER_H