Skip to content

Instantly share code, notes, and snippets.

@mrandri19 mrandri19/jenga.cpp
Created Jun 26, 2018

Embed
What would you like to do?
#include "rapidjson/document.h"
#include <stack>
#include <unordered_set>
#include <vector>
using namespace rapidjson;
using namespace std;
#define PATH "/home/andrea/Desktop/dependencies.json"
// TODO: speed up (./jenga jayson should take less than 1s)
// TODO: speed up: analyze using perf
// TODO: speed up: use char* instead of string
unordered_set<string> already_downloaded;
void count_dependents(const Value& rows, string package)
{
string package_name = package;
uint total = 0;
stack<string> S;
S.push(package_name);
while (!S.empty()) {
package_name = S.top();
if (already_downloaded.find(package_name) != already_downloaded.end()) {
S.pop();
continue;
} else {
already_downloaded.insert(string(package_name));
}
vector<string> deps;
// Count the dependents packages
int n = 0;
for (const auto& row : rows.GetArray()) {
for (const auto& key : row["key"].GetArray()) {
if (key == package_name.c_str() && row["id"] != package_name.c_str()) {
auto id = row["id"].GetString();
deps.push_back(id);
n++;
}
}
}
S.pop();
if (n == 0) {
total++;
} else {
for (const auto& dep : deps) {
S.push(dep);
}
}
}
printf("Total dependents: %d\n", total);
}
int main(int argc, char** argv)
{
printf("Start\n");
if (argc != 2) {
printf("Usage %s package-name\n", argv[0]);
exit(1);
}
string package_name = string(argv[1]);
// Read the file and load in into the buffer
FILE* fp = fopen(PATH, "r");
fseek(fp, 0, SEEK_END);
auto file_size = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
auto * buffer = (char*)malloc(file_size + 1);
size_t readLength = fread(buffer, 1, file_size, fp);
buffer[readLength] = '\0';
fclose(fp);
// Parse the json inside the buffer
Document d;
d.ParseInsitu(buffer);
printf("Parsed the JSON\n");
// Start analyzing it
printf("Starting the analysis\n");
const Value& rows = d["rows"];
assert(rows.IsArray());
printf("Calling count_dependents\n");
count_dependents(rows, package_name);
printf("Stop\n");
free(buffer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.