repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
renaudbedard/littlebits-arduino
|
Sketches/UberSync/Pins.h
|
<filename>Sketches/UberSync/Pins.h
#include "Arduino.h"
#ifndef PINS_H
#define PINS_H
class In
{
public:
class Digital
{
public:
};
class Analog
{
public:
static const byte Sync = 0;
static const byte DutyCycle = 1;
};
};
class Out
{
public:
class Digital
{
public:
static const byte DoubleSpeed = 1;
static const byte QuadSpeed = 5;
static const byte OctoSpeed = 9;
};
class Analog
{
public:
};
};
#endif
|
renaudbedard/littlebits-arduino
|
Libraries/Util/Util.h
|
<filename>Libraries/Util/Util.h
#ifndef UTIL_H
#define UTIL_H
#include "Arduino.h"
#include <stdio.h>
#include <avr/pgmspace.h>
#define ulong unsigned long
#define ADD_PRINTF_SUPPORT \
static FILE uartout = {0}; \
static int uart_putchar(char c, FILE* stream) \
{ \
(void) stream; \
Serial.write(c); \
return c; \
} \
static void printf_setup() \
{ \
fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE); \
stdout = &uartout; \
}
#define P(string_literal) PSTR(string_literal "\n")
#define ANALOG_HIGH 511
#ifdef _DEBUG
#define assert(cond, ...) \
while (!cond) \
printf_P(__VA_ARGS__);
#define trace(...) \
printf_P(__VA_ARGS__)
#else
#define assert(cond, ...)
#define trace(...)
#endif
bool boolAnalogRead(byte pin);
float floatAnalogRead(byte pin);
void floatAnalogWrite(byte pin, float value);
static const byte MedianSampleCount = 24;
static const byte MedianMaxBuckets = 16;
static const byte MedianAveragedBuckets = 3;
static const byte MedianMaxVariance = 10;
int smartMedianAnalogRead(byte pin);
#endif
|
renaudbedard/littlebits-arduino
|
Sketches/MultiSync/Pins.h
|
<reponame>renaudbedard/littlebits-arduino<gh_stars>10-100
#include <stdint.h>
#ifndef PINS_H
#define PINS_H
class In
{
public:
class Digital
{
public:
static const byte Sync = 0;
};
class Analog
{
public:
static const byte Multiplier = 0;
static const byte DutyCycle = 1;
};
};
class Out
{
public:
class Digital
{
public:
static const byte Sequencer1 = 1;
static const byte Sequencer2 = 5;
static const byte Sequencer3 = 9;
};
class Analog
{
public:
};
};
#endif
|
renaudbedard/littlebits-arduino
|
Sketches/DutyCycle/Pins.h
|
<reponame>renaudbedard/littlebits-arduino<gh_stars>10-100
#include "Arduino.h"
#ifndef PINS_H
#define PINS_H
class In
{
public:
class Digital
{
public:
static const byte Pulse = 0;
};
class Analog
{
public:
static const byte DutyCycle = 0;
};
};
class Out
{
public:
class Digital
{
public:
static const byte Oscillator = 1;
};
class Analog
{
public:
};
};
#endif
|
renaudbedard/littlebits-arduino
|
Sketches/BleepDrum/Pins.h
|
<gh_stars>10-100
#include "Arduino.h"
#ifndef PINS_H
#define PINS_H
class In
{
public:
class Digital
{
public:
static const byte Pulse = 0;
};
class Analog
{
public:
};
};
class Out
{
public:
class Digital
{
public:
static const byte Midi = 1;
};
class Analog
{
public:
};
};
#endif
|
renaudbedard/littlebits-arduino
|
Sketches/UberLatch/Pins.h
|
#include "Arduino.h"
#ifndef PINS_H
#define PINS_H
class In
{
public:
class Digital
{
public:
static const byte Pulse = 0;
};
class Analog
{
public:
static const byte DutyCycle = 0;
};
};
class Out
{
public:
class Digital
{
public:
static const byte HalfSpeed = 1;
static const byte QuarterSpeed = 5;
static const byte EighthSpeed = 9;
};
class Analog
{
public:
};
};
#endif
|
renaudbedard/littlebits-arduino
|
Sketches/KeyboardRecorder/Pins.h
|
#include "Arduino.h"
#ifndef PINS_H
#define PINS_H
class In
{
public:
class Digital
{
public:
static const byte Pulse = 0;
};
class Analog
{
public:
static const byte Keyboard = 0;
static const byte ModeSwitch = 1;
};
};
class Out
{
public:
class Digital
{
public:
static const byte Unused = 1;
};
class Analog
{
public:
static const byte Oscillator = 5;
static const byte Unused = 9;
};
};
#endif
|
amarantedaniel/AsyncImage
|
AsyncImage/AsyncImage.h
|
//
// AsyncImage.h
// AsyncImage
//
// Created by <NAME> on 5/9/20.
// Copyright © 2020 Tigerhood. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for AsyncImage.
FOUNDATION_EXPORT double AsyncImageVersionNumber;
//! Project version string for AsyncImage.
FOUNDATION_EXPORT const unsigned char AsyncImageVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <AsyncImage/PublicHeader.h>
|
mertcankokcur/CountingTheFrequencyOfWords
|
WordType.h
|
<filename>WordType.h<gh_stars>0
#pragma once
#include <iostream>
#include <string>
using namespace std;
class WordType
{
public:
string word;
int count;
WordType(string);
void setCounter();
bool operator == (WordType sec)
{
if(word==sec.word) return true;
return false;
}
};
|
mertcankokcur/CountingTheFrequencyOfWords
|
Node.h
|
#ifndef _NODE_
#define _NODE_
#include <iostream>
//using namespace std;
template <class ElemType>
class Node
{
public:
ElemType data;
Node *next;
Node(){next=NULL;}
Node(const ElemType &e):data(e),next(NULL){}
};
#endif
|
mertcankokcur/CountingTheFrequencyOfWords
|
LinkedList.h
|
#ifndef _LINKEDLIST_
#define _LINKEDLIST_
#include "Node.h"
#include <iostream>
#include <fstream>
using namespace std;
template <class ElemType>
class LinkedList
{
private:
Node<ElemType> *head;
int numberOfItems;
public:
//problems solved during lecture hours
LinkedList() :head(NULL), numberOfItems(0)
{
}
bool isEmpty()const { return head == NULL; }
bool isFull()const { return false; }
bool LisMember(const ElemType &key)const
{
Node<ElemType> *walk = head;
while (walk != NULL)
{
if (walk->data == key)
return true;
walk = walk->next;
}
return false;
}
void updateMember(const ElemType &key)const
{
Node<ElemType> *walk=head;
while(walk!=NULL)
{
if(walk->data==key)
{
walk->data.setCounter();
return;
}
walk=walk->next;
}
}
int indexOf(const ElemType &key)const
{
Node<ElemType> *walk = head;
int index = -1;
while (walk != NULL)
{
if (walk->data == key)
return index;
walk = walk->next;
index++;
}
return -1;
}
int getSize() const
{
return numberOfItems;
}
void insertFront(const ElemType &e)
{
Node<ElemType> *t = new Node<ElemType>(e);
t->next = head;
head = t;
numberOfItems++;
}
void insertEnd(const ElemType &e)
{
Node<ElemType> *t = new Node<ElemType>(e);
Node<ElemType> *walk = head;
if (head == NULL)
head = t;
else
{
while (walk->next != NULL)
{
walk = walk->next;
}
walk->next = t;
}
numberOfItems++;
}
void insertAt(const ElemType &e, int pos)
{
if (head != NULL)
{
if (pos >= 0 && pos <= numberOfItems)
{
Node<ElemType> *t = new Node<ElemType>(e);
if (pos == 0)//insert to front
{
t->next = head;
head = t;
}
else
{
Node<ElemType> *prev = head;
Node<ElemType> *walk = head->next;
int cnt = 1;
while (walk != NULL && cnt<pos)
{
prev = walk;
walk = walk->next;
}
prev->next = t;
t->next = walk;
numberOfItems++;
}
}
}
}
void deleteFront()
{
if (head != NULL)
{
Node<ElemType> *old = head;
head = head->next;
delete old;
numberOfItems--;
}
}
void delteEnd()
{
if (head != NULL)
{
if (head->next == NULL)
{
delete head;
head = NULL;
}
else
{
Node<ElemType> *walk = head->next;
Node<ElemType> *prev = head;
while (walk->next != NULL)
{
prev = walk;
walk = walk->next;
}
prev->next = walk->next;
delete walk;
}
numberOfItems--;
}
}
//this method removes a node located at pos
//pre condition: linked list is not empty, pos is positive value btween 0 and numberOfItems. The node pointed by head is 0th node
void deleteAt(int pos)
{
if (head != NULL)
{
if (pos >= 0 && pos < numberOfItems)
{
if (pos == 0) //
{
Node<ElemType> *old = head;
head = head->next;
delete old;
}
else
{
Node<ElemType> *prev = head;
Node<ElemType> *walk = head->next;//walk will be pointing the node to be deleted
int cnt = 1; //we have already checked 0th node, therefore start with 1
while (walk != NULL && cnt < pos)//traverse until cnt becomes equal to pos
{
cnt++;
prev = walk;
walk = walk->next;
}
//remove node pointed by walk
prev->next = walk->next;
delete walk;
}
numberOfItems--;
}
}
}
void remove(const ElemType& key)
{
if (head != NULL)
{
if (key == head->data) //check if the key in the first node, => remove first
{
Node<ElemType> *old = head;
head = head->next;
delete old;
numberOfItems--;
}
else //key might be in rest of the linked list, keep looking for until the end of linked list
{
Node<ElemType> *prev = head;
Node<ElemType> *walk = head->next;
while (walk != NULL)
{
prev = walk;
walk = walk->next;
}
//walk becomes NULL if the key is not in any of nodes
if (walk != NULL) {
prev->next = walk->next;
delete walk;
numberOfItems--;
}
}
}
}
const ElemType & getFirst()const
{
if (head != NULL)
return head->data;
exit(0);
}
const ElemType & getLast()const
{
if (head != NULL)
{
if (head->next == NULL)
{
return head->data;
}
else {
Node<ElemType> *walk = head->next;
while (walk->next != NULL)
{
walk = walk->next;
}
return walk->data;
}
}
else
exit(0);
}
const ElemType & itemAt(int pos)const
{
if (head != NULL)
{
if (pos >= 0 && pos < numberOfItems)
{
if (pos == 0) //
{
return head->data;
}
else
{
Node<ElemType> *prev = head;
Node<ElemType> *walk = head->next;//walk will be pointing the node to be deleted
int cnt = 1; //we have already checked 0th node, therefore start with 1
while (walk != NULL && cnt < pos)//traverse until cnt becomes equal to pos
{
cnt++;
prev = walk;
walk = walk->next;
}
//remove node pointed by walk
return walk->data;
}
}
}
}
void print()const
{
Node<ElemType> *walk = head;
ofstream file;
file.open("output.txt", std::ios_base::app);
while (walk != NULL)
{
file << walk->data.word << " " << walk ->data.count << endl;
walk = walk->next;
}
file.close();
}
const ElemType & getMin() const
{
if (head == NULL) //if linked list is empty nothing to return just terminate the program execution. To do: more elegant implementaion with exection is required
exit(0);
Node<ElemType> *nodeMin = head;
Node<ElemType> *walk = head->next;
while (walk != NULL)
{
if (walk->data < nodeMin->data)
nodeMin = walk;
walk = walk->next;
}
return nodeMin->data;
}
void deleteMin()
{
if (head != NULL)
{
if (head->next == NULL)//if there is only one
{
delete head;
head = NULL;
numberOfItems--;
}
else
{
Node<ElemType> *nodeMin, *prevMin;
Node<ElemType> *walk, *prev;
nodeMin = head;
prevMin = NULL;
prev = head;
walk = head->next;
while (walk != NULL)
{
if (nodeMin->data > walk->data)
{
prevMin = prev;
nodeMin = walk;
}
prev = walk;
walk = walk->next;
}
if (nodeMin == head)//if the minimum element is in node poited by head apply remove first algorithm
{
Node *old = head;
head = head->next;
delete head;
}
else
{
prevMin->next = nodeMin->next;
delete nodeMin;
}
numberOfItems--;
}
}
}
LinkedList sum(LinkedList l1, LinkedList l2)
{
LinkedList res;
int carry, digit, total;
Node <ElemType> *walk, *w1=l1.head, *w2=l2.head;
total=(w1!=NULL?w1->data:0)+(w2!=NULL?w2->data:0);
digit = total % 10;
carry = total / 10;
if (total > 0)
res.head = new Node<ElemType>(total);
else
return res;
walk = res.head;
w1 = (w1 != NULL ? w1->next : w1);
w2 = (w2 != NULL ? w2->next : w2);
while (w1 != NULL || w2 != NULL)
{
total=carry+ (w1 != NULL ? w1->data : 0) + (w2 != NULL ? w2->data : 0);
digit = total % 10;
carry = total / 10;
walk->next = new Node<ElemType>(digit);
walk = walk->next;
w1 = (w1 != NULL ? w1->next : w1);
w2 = (w2 != NULL ? w2->next : w2);
}
if(carry>0)
walk->next= new Node<ElemType>(carry);
return res;
}
};
#endif
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/ui_arrayitem_editor.h
|
<reponame>eXl-Nic/eXl
/********************************************************************************
** Form generated from reading UI file 'arrayitem_editorNawqgf.ui'
**
** Created by: Qt User Interface Compiler version 5.15.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef ARRAYITEM_EDITORNAWQGF_H
#define ARRAYITEM_EDITORNAWQGF_H
#include <QtCore/QVariant>
#include <QtGui/QIcon>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFrame>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_ArrayItemEditor
{
public:
QVBoxLayout *verticalLayout;
QFrame *frame;
QHBoxLayout *horizontalLayout;
QLabel *ItemIndexLabel;
QPushButton *InsertButton;
QPushButton *RemoveItemButton;
void setupUi(QWidget *ArrayItemEditor)
{
if (ArrayItemEditor->objectName().isEmpty())
ArrayItemEditor->setObjectName(QString::fromUtf8("ArrayItemEditor"));
ArrayItemEditor->resize(94, 26);
ArrayItemEditor->setAutoFillBackground(true);
verticalLayout = new QVBoxLayout(ArrayItemEditor);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
frame = new QFrame(ArrayItemEditor);
frame->setObjectName(QString::fromUtf8("frame"));
frame->setAutoFillBackground(true);
frame->setFrameShape(QFrame::StyledPanel);
frame->setFrameShadow(QFrame::Raised);
horizontalLayout = new QHBoxLayout(frame);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
horizontalLayout->setContentsMargins(0, 0, 0, 0);
ItemIndexLabel = new QLabel(frame);
ItemIndexLabel->setObjectName(QString::fromUtf8("ItemIndexLabel"));
horizontalLayout->addWidget(ItemIndexLabel);
InsertButton = new QPushButton(frame);
InsertButton->setObjectName(QString::fromUtf8("InsertButton"));
horizontalLayout->addWidget(InsertButton);
RemoveItemButton = new QPushButton(frame);
RemoveItemButton->setObjectName(QString::fromUtf8("RemoveItemButton"));
RemoveItemButton->setAutoFillBackground(true);
QIcon icon;
QString iconThemeName = QString::fromUtf8("SP_DialogCancelButton");
if (QIcon::hasThemeIcon(iconThemeName)) {
icon = QIcon::fromTheme(iconThemeName);
} else {
icon.addFile(QString::fromUtf8("."), QSize(), QIcon::Normal, QIcon::Off);
}
RemoveItemButton->setIcon(icon);
horizontalLayout->addWidget(RemoveItemButton);
verticalLayout->addWidget(frame);
retranslateUi(ArrayItemEditor);
QMetaObject::connectSlotsByName(ArrayItemEditor);
} // setupUi
void retranslateUi(QWidget *ArrayItemEditor)
{
ArrayItemEditor->setWindowTitle(QCoreApplication::translate("ArrayItemEditor", "Form", nullptr));
ItemIndexLabel->setText(QCoreApplication::translate("ArrayItemEditor", "0", nullptr));
InsertButton->setText(QString());
RemoveItemButton->setText(QString());
} // retranslateUi
};
namespace Ui {
class ArrayItemEditor: public Ui_ArrayItemEditor {};
} // namespace Ui
QT_END_NAMESPACE
#endif // ARRAYITEM_EDITORNAWQGF_H
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/ui_quaternion_editor.h
|
<filename>src/engine/editor/eXl_Editor/ui_quaternion_editor.h<gh_stars>0
/********************************************************************************
** Form generated from reading UI file 'quaternion_editorRJTfBE.ui'
**
** Created by: Qt User Interface Compiler version 5.15.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef QUATERNION_EDITORRJTFBE_H
#define QUATERNION_EDITORRJTFBE_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_QuatEditor
{
public:
QGridLayout *gridLayout;
QLabel *label;
QLineEdit *w_Edit;
QLabel *label_2;
QLineEdit *x_Edit;
QLabel *label_4;
QLineEdit *y_Edit;
QLabel *label_3;
QLineEdit *z_Edit;
void setupUi(QWidget *QuatEditor)
{
if (QuatEditor->objectName().isEmpty())
QuatEditor->setObjectName(QString::fromUtf8("QuatEditor"));
QuatEditor->resize(320, 38);
gridLayout = new QGridLayout(QuatEditor);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
label = new QLabel(QuatEditor);
label->setObjectName(QString::fromUtf8("label"));
gridLayout->addWidget(label, 0, 0, 1, 1);
w_Edit = new QLineEdit(QuatEditor);
w_Edit->setObjectName(QString::fromUtf8("w_Edit"));
gridLayout->addWidget(w_Edit, 0, 1, 1, 1);
label_2 = new QLabel(QuatEditor);
label_2->setObjectName(QString::fromUtf8("label_2"));
gridLayout->addWidget(label_2, 0, 2, 1, 1);
x_Edit = new QLineEdit(QuatEditor);
x_Edit->setObjectName(QString::fromUtf8("x_Edit"));
gridLayout->addWidget(x_Edit, 0, 3, 1, 1);
label_4 = new QLabel(QuatEditor);
label_4->setObjectName(QString::fromUtf8("label_4"));
gridLayout->addWidget(label_4, 0, 4, 1, 1);
y_Edit = new QLineEdit(QuatEditor);
y_Edit->setObjectName(QString::fromUtf8("y_Edit"));
gridLayout->addWidget(y_Edit, 0, 5, 1, 1);
label_3 = new QLabel(QuatEditor);
label_3->setObjectName(QString::fromUtf8("label_3"));
gridLayout->addWidget(label_3, 0, 6, 1, 1);
z_Edit = new QLineEdit(QuatEditor);
z_Edit->setObjectName(QString::fromUtf8("z_Edit"));
gridLayout->addWidget(z_Edit, 0, 7, 1, 1);
retranslateUi(QuatEditor);
QObject::connect(w_Edit, SIGNAL(editingFinished()), QuatEditor, SLOT(OnEditingFinished()));
QObject::connect(x_Edit, SIGNAL(editingFinished()), QuatEditor, SLOT(OnEditingFinished()));
QObject::connect(y_Edit, SIGNAL(editingFinished()), QuatEditor, SLOT(OnEditingFinished()));
QObject::connect(z_Edit, SIGNAL(editingFinished()), QuatEditor, SLOT(OnEditingFinished()));
QMetaObject::connectSlotsByName(QuatEditor);
} // setupUi
void retranslateUi(QWidget *QuatEditor)
{
QuatEditor->setWindowTitle(QCoreApplication::translate("QuatEditor", "Form", nullptr));
label->setText(QCoreApplication::translate("QuatEditor", "W", nullptr));
label_2->setText(QCoreApplication::translate("QuatEditor", "X", nullptr));
label_4->setText(QCoreApplication::translate("QuatEditor", "Y", nullptr));
label_3->setText(QCoreApplication::translate("QuatEditor", "Z", nullptr));
} // retranslateUi
};
namespace Ui {
class QuatEditor: public Ui_QuatEditor {};
} // namespace Ui
QT_END_NAMESPACE
#endif // QUATERNION_EDITORRJTFBE_H
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/vector_editor.h
|
#pragma once
#include "../dynobjecteditor.hpp"
class QAbstractSpinBox;
class Vector_Editor : public DynObjectEditor
{
Q_OBJECT
public:
static DynObjectEditor* Construct(QWidget *parent)
{return new Vector_Editor(parent);}
Vector_Editor(QWidget *parent);
protected slots:
void OnEditingFinished();
protected:
void UpdateView();
bool m_Integer;
QAbstractSpinBox* m_Boxes[4];
};
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/array_editor.h
|
<filename>src/engine/editor/eXl_Editor/array_editor.h
#pragma once
#include <QWidget>
#include <editor/editordef.hpp>
#include <editor/dynobjecteditor.hpp>
namespace Ui
{
class ArrayEditor;
}
class Array_Editor : public DynObjectEditor
{
Q_OBJECT
public:
Array_Editor(QWidget*);
~Array_Editor();
void SetObject(eXl::ConstDynObject const* iObj) override
{
m_ConstObj = iObj;
UpdateView();
}
Q_SIGNALS:
void onAddItem();
void onEmptyArray();
protected:
void UpdateView();
Ui::ArrayEditor *ui;
eXl::ConstDynObject const* m_ConstObj = nullptr;
};
|
eXl-Nic/eXl
|
src/engine/editor/mainwindow.h
|
#pragma once
#include <QMainWindow>
#include <QAbstractItemModel>
#include <core/type/dynobject.hpp>
#include <core/resource/resource.hpp>
namespace Ui
{
class MainWindow;
}
class QTreeView;
class QMdiArea;
namespace eXl
{
class ResourceContainerModel;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
Q_SIGNALS:
void mainWindowClosed();
protected:
void closeEvent(QCloseEvent* event);
protected slots:
void newProject();
void openProject();
void closeProject();
void save();
void close();
void projectOpened();
void projectClosed();
void onResourceDoubleClick(QModelIndex const& );
void OpenResource(Resource::UUID const& );
private slots:
void onCreateAction(QObject*);
private:
class EventFilter;
Ui::MainWindow *ui;
QTreeView* m_ResourcesView = nullptr;
QMdiArea* m_Documents;
};
}
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/ui_mainwindow.h
|
<filename>src/engine/editor/eXl_Editor/ui_mainwindow.h
/********************************************************************************
** Form generated from reading UI file 'mainwindowIQJaRl.ui'
**
** Created by: Qt User Interface Compiler version 5.15.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef MAINWINDOWIQJARL_H
#define MAINWINDOWIQJARL_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QAction *actionNewProject;
QAction *actionOpenProject;
QAction *actionCloseProject;
QAction *actionSave;
QAction *actionClose;
QWidget *centralwidget;
QMenuBar *menubar;
QMenu *menuFile;
QMenu *menuCreate;
QMenu *menuEdit;
QStatusBar *statusbar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(898, 792);
actionNewProject = new QAction(MainWindow);
actionNewProject->setObjectName(QString::fromUtf8("actionNewProject"));
actionOpenProject = new QAction(MainWindow);
actionOpenProject->setObjectName(QString::fromUtf8("actionOpenProject"));
actionCloseProject = new QAction(MainWindow);
actionCloseProject->setObjectName(QString::fromUtf8("actionCloseProject"));
actionSave = new QAction(MainWindow);
actionSave->setObjectName(QString::fromUtf8("actionSave"));
actionClose = new QAction(MainWindow);
actionClose->setObjectName(QString::fromUtf8("actionClose"));
centralwidget = new QWidget(MainWindow);
centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
MainWindow->setCentralWidget(centralwidget);
menubar = new QMenuBar(MainWindow);
menubar->setObjectName(QString::fromUtf8("menubar"));
menubar->setGeometry(QRect(0, 0, 898, 21));
menuFile = new QMenu(menubar);
menuFile->setObjectName(QString::fromUtf8("menuFile"));
menuCreate = new QMenu(menubar);
menuCreate->setObjectName(QString::fromUtf8("menuCreate"));
menuEdit = new QMenu(menubar);
menuEdit->setObjectName(QString::fromUtf8("menuEdit"));
MainWindow->setMenuBar(menubar);
statusbar = new QStatusBar(MainWindow);
statusbar->setObjectName(QString::fromUtf8("statusbar"));
MainWindow->setStatusBar(statusbar);
menubar->addAction(menuFile->menuAction());
menubar->addAction(menuCreate->menuAction());
menubar->addAction(menuEdit->menuAction());
menuFile->addAction(actionNewProject);
menuFile->addAction(actionOpenProject);
menuFile->addAction(actionCloseProject);
menuFile->addSeparator();
menuFile->addAction(actionSave);
menuFile->addAction(actionClose);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QCoreApplication::translate("MainWindow", "MainWindow", nullptr));
actionNewProject->setText(QCoreApplication::translate("MainWindow", "New Project", nullptr));
actionOpenProject->setText(QCoreApplication::translate("MainWindow", "Open Project", nullptr));
actionCloseProject->setText(QCoreApplication::translate("MainWindow", "Close Project", nullptr));
actionSave->setText(QCoreApplication::translate("MainWindow", "Save", nullptr));
#if QT_CONFIG(shortcut)
actionSave->setShortcut(QCoreApplication::translate("MainWindow", "Ctrl+S", nullptr));
#endif // QT_CONFIG(shortcut)
actionClose->setText(QCoreApplication::translate("MainWindow", "Close", nullptr));
menuFile->setTitle(QCoreApplication::translate("MainWindow", "File", nullptr));
menuCreate->setTitle(QCoreApplication::translate("MainWindow", "Create", nullptr));
menuEdit->setTitle(QCoreApplication::translate("MainWindow", "Edit", nullptr));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // MAINWINDOWIQJARL_H
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/ui_tilinggroup_toolbox.h
|
/********************************************************************************
** Form generated from reading UI file 'tilinggroup_toolboxxrQADp.ui'
**
** Created by: Qt User Interface Compiler version 5.15.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef TILINGGROUP_TOOLBOXXRQADP_H
#define TILINGGROUP_TOOLBOXXRQADP_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_TilingGroupToolbox
{
public:
QVBoxLayout *verticalLayout;
QHBoxLayout *horizontalLayout;
QLabel *label;
QSpinBox *patternSizeX;
QSpinBox *patternSizeY;
QHBoxLayout *horizontalLayout_2;
QLabel *label_2;
QSpinBox *anchorX;
QSpinBox *anchorY;
void setupUi(QWidget *TilingGroupToolbox)
{
if (TilingGroupToolbox->objectName().isEmpty())
TilingGroupToolbox->setObjectName(QString::fromUtf8("TilingGroupToolbox"));
TilingGroupToolbox->resize(210, 100);
QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(TilingGroupToolbox->sizePolicy().hasHeightForWidth());
TilingGroupToolbox->setSizePolicy(sizePolicy);
verticalLayout = new QVBoxLayout(TilingGroupToolbox);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalLayout->setSizeConstraint(QLayout::SetMaximumSize);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
horizontalLayout->setSizeConstraint(QLayout::SetMinimumSize);
label = new QLabel(TilingGroupToolbox);
label->setObjectName(QString::fromUtf8("label"));
horizontalLayout->addWidget(label);
patternSizeX = new QSpinBox(TilingGroupToolbox);
patternSizeX->setObjectName(QString::fromUtf8("patternSizeX"));
patternSizeX->setMinimum(1);
patternSizeX->setMaximum(65536);
horizontalLayout->addWidget(patternSizeX);
patternSizeY = new QSpinBox(TilingGroupToolbox);
patternSizeY->setObjectName(QString::fromUtf8("patternSizeY"));
patternSizeY->setMinimum(1);
patternSizeY->setMaximum(65536);
horizontalLayout->addWidget(patternSizeY);
verticalLayout->addLayout(horizontalLayout);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
horizontalLayout_2->setSizeConstraint(QLayout::SetMinimumSize);
label_2 = new QLabel(TilingGroupToolbox);
label_2->setObjectName(QString::fromUtf8("label_2"));
horizontalLayout_2->addWidget(label_2);
anchorX = new QSpinBox(TilingGroupToolbox);
anchorX->setObjectName(QString::fromUtf8("anchorX"));
anchorX->setMinimum(-1);
anchorX->setMaximum(65536);
horizontalLayout_2->addWidget(anchorX);
anchorY = new QSpinBox(TilingGroupToolbox);
anchorY->setObjectName(QString::fromUtf8("anchorY"));
anchorY->setMinimum(-1);
anchorY->setMaximum(65536);
horizontalLayout_2->addWidget(anchorY);
verticalLayout->addLayout(horizontalLayout_2);
retranslateUi(TilingGroupToolbox);
QMetaObject::connectSlotsByName(TilingGroupToolbox);
} // setupUi
void retranslateUi(QWidget *TilingGroupToolbox)
{
TilingGroupToolbox->setWindowTitle(QCoreApplication::translate("TilingGroupToolbox", "Form", nullptr));
label->setText(QCoreApplication::translate("TilingGroupToolbox", "Pattern Size", nullptr));
label_2->setText(QCoreApplication::translate("TilingGroupToolbox", "Anchor Position", nullptr));
} // retranslateUi
};
namespace Ui {
class TilingGroupToolbox: public Ui_TilingGroupToolbox {};
} // namespace Ui
QT_END_NAMESPACE
#endif // TILINGGROUP_TOOLBOXXRQADP_H
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/objectptr_editor.h
|
<reponame>eXl-Nic/eXl
#ifndef OBJECTPTR_EDITOR_H
#define OBJECTPTR_EDITOR_H
#if 0
#include "../dynobjecteditor.hpp"
namespace Ui {
class ObjectPtr_Editor;
}
class ObjectPtr_Editor : public DynObjectEditor
{
Q_OBJECT
public:
static DynObjectEditor* Construct(QWidget *parent)
{return new ObjectPtr_Editor(parent);}
explicit ObjectPtr_Editor(QWidget *parent = 0);
~ObjectPtr_Editor();
signals:
void editingFinished();
protected:
void UpdateView();
private slots:
void on_RttiList_currentIndexChanged(int index);
private:
Ui::ObjectPtr_Editor *ui;
};
#endif
#endif // OBJECTPTR_EDITOR_H
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/ui_enum_editor.h
|
<reponame>eXl-Nic/eXl
/********************************************************************************
** Form generated from reading UI file 'enum_editorMweAOJ.ui'
**
** Created by: Qt User Interface Compiler version 5.15.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef ENUM_EDITORMWEAOJ_H
#define ENUM_EDITORMWEAOJ_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Enum_Editor
{
public:
QVBoxLayout *verticalLayout;
QComboBox *EnumNames;
void setupUi(QWidget *Enum_Editor)
{
if (Enum_Editor->objectName().isEmpty())
Enum_Editor->setObjectName(QString::fromUtf8("Enum_Editor"));
Enum_Editor->resize(239, 24);
verticalLayout = new QVBoxLayout(Enum_Editor);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
EnumNames = new QComboBox(Enum_Editor);
EnumNames->setObjectName(QString::fromUtf8("EnumNames"));
verticalLayout->addWidget(EnumNames);
retranslateUi(Enum_Editor);
QMetaObject::connectSlotsByName(Enum_Editor);
} // setupUi
void retranslateUi(QWidget *Enum_Editor)
{
Enum_Editor->setWindowTitle(QCoreApplication::translate("Enum_Editor", "Form", nullptr));
} // retranslateUi
};
namespace Ui {
class Enum_Editor: public Ui_Enum_Editor {};
} // namespace Ui
QT_END_NAMESPACE
#endif // ENUM_EDITORMWEAOJ_H
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/ui_objectptr_editor.h
|
<gh_stars>0
/********************************************************************************
** Form generated from reading UI file 'objectptr_editorKCzoCT.ui'
**
** Created by: Qt User Interface Compiler version 5.15.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef OBJECTPTR_EDITORKCZOCT_H
#define OBJECTPTR_EDITORKCZOCT_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_ObjectPtr_Editor
{
public:
QVBoxLayout *verticalLayout;
QComboBox *RttiList;
void setupUi(QWidget *ObjectPtr_Editor)
{
if (ObjectPtr_Editor->objectName().isEmpty())
ObjectPtr_Editor->setObjectName(QString::fromUtf8("ObjectPtr_Editor"));
ObjectPtr_Editor->resize(214, 39);
verticalLayout = new QVBoxLayout(ObjectPtr_Editor);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
RttiList = new QComboBox(ObjectPtr_Editor);
RttiList->setObjectName(QString::fromUtf8("RttiList"));
verticalLayout->addWidget(RttiList);
retranslateUi(ObjectPtr_Editor);
QMetaObject::connectSlotsByName(ObjectPtr_Editor);
} // setupUi
void retranslateUi(QWidget *ObjectPtr_Editor)
{
ObjectPtr_Editor->setWindowTitle(QCoreApplication::translate("ObjectPtr_Editor", "Form", nullptr));
} // retranslateUi
};
namespace Ui {
class ObjectPtr_Editor: public Ui_ObjectPtr_Editor {};
} // namespace Ui
QT_END_NAMESPACE
#endif // OBJECTPTR_EDITORKCZOCT_H
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/arrayitem_editor.h
|
#pragma once
#include <QWidget>
#include <editor/editordef.hpp>
namespace Ui
{
class ArrayItemEditor;
}
class ArrayItem_Editor : public QWidget
{
Q_OBJECT
public:
ArrayItem_Editor(uint32_t iItemIndex, QWidget*);
~ArrayItem_Editor();
Q_SIGNALS:
void onRemoveItem();
void onInsertItem();
protected:
Ui::ArrayItemEditor *ui;
};
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/quaternion_editor.h
|
#pragma once
#include "../dynobjecteditor.hpp"
namespace Ui
{
class QuatEditor;
}
class Quaternion_Editor : public DynObjectEditor
{
Q_OBJECT
public:
static DynObjectEditor* Construct(QWidget *parent)
{return new Quaternion_Editor(parent);}
Quaternion_Editor(QWidget *parent);
protected slots:
void OnEditingFinished();
protected:
virtual void UpdateView();
Ui::QuatEditor* ui;
};
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/ui_tileset_toolbox.h
|
/********************************************************************************
** Form generated from reading UI file 'tileset_toolboxeFuVok.ui'
**
** Created by: Qt User Interface Compiler version 5.15.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef TILESET_TOOLBOXEFUVOK_H
#define TILESET_TOOLBOXEFUVOK_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_TilesetToolbox
{
public:
QVBoxLayout *verticalLayout;
QHBoxLayout *horizontalLayout;
QLabel *label;
QSpinBox *gridSizeX;
QSpinBox *gridSizeY;
QHBoxLayout *horizontalLayout_2;
QLabel *label_2;
QSpinBox *offsetX;
QSpinBox *offsetY;
QPushButton *bootstrapButton;
void setupUi(QWidget *TilesetToolbox)
{
if (TilesetToolbox->objectName().isEmpty())
TilesetToolbox->setObjectName(QString::fromUtf8("TilesetToolbox"));
TilesetToolbox->resize(129, 97);
QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(TilesetToolbox->sizePolicy().hasHeightForWidth());
TilesetToolbox->setSizePolicy(sizePolicy);
verticalLayout = new QVBoxLayout(TilesetToolbox);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
label = new QLabel(TilesetToolbox);
label->setObjectName(QString::fromUtf8("label"));
horizontalLayout->addWidget(label);
gridSizeX = new QSpinBox(TilesetToolbox);
gridSizeX->setObjectName(QString::fromUtf8("gridSizeX"));
gridSizeX->setMinimum(1);
gridSizeX->setMaximum(65536);
horizontalLayout->addWidget(gridSizeX);
gridSizeY = new QSpinBox(TilesetToolbox);
gridSizeY->setObjectName(QString::fromUtf8("gridSizeY"));
gridSizeY->setMinimum(1);
gridSizeY->setMaximum(65536);
horizontalLayout->addWidget(gridSizeY);
verticalLayout->addLayout(horizontalLayout);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
label_2 = new QLabel(TilesetToolbox);
label_2->setObjectName(QString::fromUtf8("label_2"));
horizontalLayout_2->addWidget(label_2);
offsetX = new QSpinBox(TilesetToolbox);
offsetX->setObjectName(QString::fromUtf8("offsetX"));
offsetX->setMaximum(65536);
horizontalLayout_2->addWidget(offsetX);
offsetY = new QSpinBox(TilesetToolbox);
offsetY->setObjectName(QString::fromUtf8("offsetY"));
offsetY->setMaximum(65536);
horizontalLayout_2->addWidget(offsetY);
verticalLayout->addLayout(horizontalLayout_2);
bootstrapButton = new QPushButton(TilesetToolbox);
bootstrapButton->setObjectName(QString::fromUtf8("bootstrapButton"));
verticalLayout->addWidget(bootstrapButton);
retranslateUi(TilesetToolbox);
QMetaObject::connectSlotsByName(TilesetToolbox);
} // setupUi
void retranslateUi(QWidget *TilesetToolbox)
{
TilesetToolbox->setWindowTitle(QCoreApplication::translate("TilesetToolbox", "Form", nullptr));
label->setText(QCoreApplication::translate("TilesetToolbox", "Grid", nullptr));
label_2->setText(QCoreApplication::translate("TilesetToolbox", "Offset", nullptr));
bootstrapButton->setText(QCoreApplication::translate("TilesetToolbox", "Bootstrap", nullptr));
} // retranslateUi
};
namespace Ui {
class TilesetToolbox: public Ui_TilesetToolbox {};
} // namespace Ui
QT_END_NAMESPACE
#endif // TILESET_TOOLBOXEFUVOK_H
|
eXl-Nic/eXl
|
src/engine/editor/eXl_Editor/resourcehandle_editor.h
|
#pragma once
#include "../dynobjecteditor.hpp"
class QComboBox;
class QAbstractItemModel;
class ResourceHandle_Editor : public DynObjectEditor
{
Q_OBJECT
public:
static DynObjectEditor* Construct(QWidget *parent)
{return new ResourceHandle_Editor(parent);}
ResourceHandle_Editor(QWidget *parent);
protected slots:
void OnEditingFinished();
protected:
void UpdateView();
bool m_Integer;
QComboBox* m_ResourceCombo;
QAbstractItemModel* m_CurModel = nullptr;
};
|
epgres/UdemyCpp_Template
|
Programmierprojekt1/DynArray.h
|
<reponame>epgres/UdemyCpp_Template<filename>Programmierprojekt1/DynArray.h
#pragma once
#include <cstddef>
/**
* @brief DynamicArray Structure
*
* @param double* m_data
* @param std::size_t m_length
*/
struct DynamicArray
{
double* m_data;
std::size_t m_length;
};
/**
* @brief Create a dynamic array object
*
* @param value The fill value for the array
* @param length The length of the array
* @return DynamicArray
*/
DynamicArray create_dynamic_array(const double &value, const std::size_t &length);
/**
* @brief Push backs the *value* at the end of the array.
*
* @param dynamic_array Pointer to the array
* @param value The new value at the aend of the array
*/
void push_back(DynamicArray &dynamic_array, const int &value);
/**
* @brief Pop backs the *value* at the end of the array.
*
* @param dynamic_array Pointer to the array
* @param value The new value at the aend of the array
*/
void pop_back(DynamicArray &dynamic_array);
|
epgres/UdemyCpp_Template
|
6_Programmieraufgabe/exercise.h
|
<gh_stars>0
#pragma once
#include <utility>
#include <map>
#include <string>
// Aufgabe 1
typedef std::map<std::string, std::pair<int, int>> Friends;
// Aufgabe 2
std::string get_oldest_friend(const Friends &friends);
std::string get_heaviest_friend(const Friends &friends);
|
gentlemans/gentlemanly-engine
|
deps/openal-soft/Alc/mixer_defs.h
|
#ifndef MIXER_DEFS_H
#define MIXER_DEFS_H
#include "AL/alc.h"
#include "AL/al.h"
#include "alMain.h"
#include "alu.h"
struct MixGains;
struct HrtfParams;
struct HrtfState;
/* C resamplers */
const ALfloat *Resample_copy32_C(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment, ALfloat *restrict dst, ALuint dstlen);
const ALfloat *Resample_point32_C(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment, ALfloat *restrict dst, ALuint dstlen);
const ALfloat *Resample_lerp32_C(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment, ALfloat *restrict dst, ALuint dstlen);
const ALfloat *Resample_fir4_32_C(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment, ALfloat *restrict dst, ALuint dstlen);
const ALfloat *Resample_fir8_32_C(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment, ALfloat *restrict dst, ALuint dstlen);
const ALfloat *Resample_bsinc32_C(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment, ALfloat *restrict dst, ALuint dstlen);
/* C mixers */
void MixHrtf_C(ALfloat (*restrict OutBuffer)[BUFFERSIZE], const ALfloat *data,
ALuint Counter, ALuint Offset, ALuint OutPos, const ALuint IrSize,
const struct HrtfParams *hrtfparams, struct HrtfState *hrtfstate,
ALuint BufferSize);
void Mix_C(const ALfloat *data, ALuint OutChans, ALfloat (*restrict OutBuffer)[BUFFERSIZE],
struct MixGains *Gains, ALuint Counter, ALuint OutPos, ALuint BufferSize);
/* SSE mixers */
void MixHrtf_SSE(ALfloat (*restrict OutBuffer)[BUFFERSIZE], const ALfloat *data,
ALuint Counter, ALuint Offset, ALuint OutPos, const ALuint IrSize,
const struct HrtfParams *hrtfparams, struct HrtfState *hrtfstate,
ALuint BufferSize);
void Mix_SSE(const ALfloat *data, ALuint OutChans, ALfloat (*restrict OutBuffer)[BUFFERSIZE],
struct MixGains *Gains, ALuint Counter, ALuint OutPos, ALuint BufferSize);
/* SSE resamplers */
inline void InitiatePositionArrays(ALuint frac, ALuint increment, ALuint *frac_arr, ALuint *pos_arr, ALuint size)
{
ALuint i;
pos_arr[0] = 0;
frac_arr[0] = frac;
for(i = 1;i < size;i++)
{
ALuint frac_tmp = frac_arr[i-1] + increment;
pos_arr[i] = pos_arr[i-1] + (frac_tmp>>FRACTIONBITS);
frac_arr[i] = frac_tmp&FRACTIONMASK;
}
}
const ALfloat *Resample_bsinc32_SSE(const BsincState *state, const ALfloat *src, ALuint frac,
ALuint increment, ALfloat *restrict dst, ALuint dstlen);
const ALfloat *Resample_lerp32_SSE2(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment,
ALfloat *restrict dst, ALuint numsamples);
const ALfloat *Resample_lerp32_SSE41(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment,
ALfloat *restrict dst, ALuint numsamples);
const ALfloat *Resample_fir4_32_SSE3(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment,
ALfloat *restrict dst, ALuint numsamples);
const ALfloat *Resample_fir4_32_SSE41(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment,
ALfloat *restrict dst, ALuint numsamples);
const ALfloat *Resample_fir8_32_SSE3(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment,
ALfloat *restrict dst, ALuint numsamples);
const ALfloat *Resample_fir8_32_SSE41(const BsincState *state, const ALfloat *src, ALuint frac, ALuint increment,
ALfloat *restrict dst, ALuint numsamples);
/* Neon mixers */
void MixHrtf_Neon(ALfloat (*restrict OutBuffer)[BUFFERSIZE], const ALfloat *data,
ALuint Counter, ALuint Offset, ALuint OutPos, const ALuint IrSize,
const struct HrtfParams *hrtfparams, struct HrtfState *hrtfstate,
ALuint BufferSize);
void Mix_Neon(const ALfloat *data, ALuint OutChans, ALfloat (*restrict OutBuffer)[BUFFERSIZE],
struct MixGains *Gains, ALuint Counter, ALuint OutPos, ALuint BufferSize);
#endif /* MIXER_DEFS_H */
|
gentlemans/gentlemanly-engine
|
deps/openal-soft/Alc/effects/compressor.c
|
/**
* OpenAL cross platform audio library
* Copyright (C) 2013 by <NAME>
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include <stdlib.h>
#include "config.h"
#include "alError.h"
#include "alMain.h"
#include "alAuxEffectSlot.h"
#include "alu.h"
typedef struct ALcompressorState {
DERIVE_FROM_TYPE(ALeffectState);
/* Effect gains for each channel */
ALfloat Gain[MAX_OUTPUT_CHANNELS];
/* Effect parameters */
ALboolean Enabled;
ALfloat AttackRate;
ALfloat ReleaseRate;
ALfloat GainCtrl;
} ALcompressorState;
static ALvoid ALcompressorState_Destruct(ALcompressorState *UNUSED(state))
{
}
static ALboolean ALcompressorState_deviceUpdate(ALcompressorState *state, ALCdevice *device)
{
const ALfloat attackTime = device->Frequency * 0.2f; /* 200ms Attack */
const ALfloat releaseTime = device->Frequency * 0.4f; /* 400ms Release */
state->AttackRate = 1.0f / attackTime;
state->ReleaseRate = 1.0f / releaseTime;
return AL_TRUE;
}
static ALvoid ALcompressorState_update(ALcompressorState *state, ALCdevice *device, const ALeffectslot *slot)
{
state->Enabled = slot->EffectProps.Compressor.OnOff;
ComputeAmbientGains(device, slot->Gain, state->Gain);
}
static ALvoid ALcompressorState_process(ALcompressorState *state, ALuint SamplesToDo, const ALfloat *SamplesIn, ALfloat (*SamplesOut)[BUFFERSIZE], ALuint NumChannels)
{
ALuint it, kt;
ALuint base;
for(base = 0;base < SamplesToDo;)
{
ALfloat temps[256];
ALuint td = minu(256, SamplesToDo-base);
if(state->Enabled)
{
ALfloat output, smp, amplitude;
ALfloat gain = state->GainCtrl;
for(it = 0;it < td;it++)
{
smp = SamplesIn[it+base];
amplitude = fabsf(smp);
if(amplitude > gain)
gain = minf(gain+state->AttackRate, amplitude);
else if(amplitude < gain)
gain = maxf(gain-state->ReleaseRate, amplitude);
output = 1.0f / clampf(gain, 0.5f, 2.0f);
temps[it] = smp * output;
}
state->GainCtrl = gain;
}
else
{
ALfloat output, smp, amplitude;
ALfloat gain = state->GainCtrl;
for(it = 0;it < td;it++)
{
smp = SamplesIn[it+base];
amplitude = 1.0f;
if(amplitude > gain)
gain = minf(gain+state->AttackRate, amplitude);
else if(amplitude < gain)
gain = maxf(gain-state->ReleaseRate, amplitude);
output = 1.0f / clampf(gain, 0.5f, 2.0f);
temps[it] = smp * output;
}
state->GainCtrl = gain;
}
for(kt = 0;kt < NumChannels;kt++)
{
ALfloat gain = state->Gain[kt];
if(!(fabsf(gain) > GAIN_SILENCE_THRESHOLD))
continue;
for(it = 0;it < td;it++)
SamplesOut[kt][base+it] += gain * temps[it];
}
base += td;
}
}
DECLARE_DEFAULT_ALLOCATORS(ALcompressorState)
DEFINE_ALEFFECTSTATE_VTABLE(ALcompressorState);
typedef struct ALcompressorStateFactory {
DERIVE_FROM_TYPE(ALeffectStateFactory);
} ALcompressorStateFactory;
static ALeffectState *ALcompressorStateFactory_create(ALcompressorStateFactory *UNUSED(factory))
{
ALcompressorState *state;
state = ALcompressorState_New(sizeof(*state));
if(!state) return NULL;
SET_VTABLE2(ALcompressorState, ALeffectState, state);
state->Enabled = AL_TRUE;
state->AttackRate = 0.0f;
state->ReleaseRate = 0.0f;
state->GainCtrl = 1.0f;
return STATIC_CAST(ALeffectState, state);
}
DEFINE_ALEFFECTSTATEFACTORY_VTABLE(ALcompressorStateFactory);
ALeffectStateFactory *ALcompressorStateFactory_getFactory(void)
{
static ALcompressorStateFactory CompressorFactory = { { GET_VTABLE2(ALcompressorStateFactory, ALeffectStateFactory) } };
return STATIC_CAST(ALeffectStateFactory, &CompressorFactory);
}
void ALcompressor_setParami(ALeffect *effect, ALCcontext *context, ALenum param, ALint val)
{
ALeffectProps *props = &effect->Props;
switch(param)
{
case AL_COMPRESSOR_ONOFF:
if(!(val >= AL_COMPRESSOR_MIN_ONOFF && val <= AL_COMPRESSOR_MAX_ONOFF))
SET_ERROR_AND_RETURN(context, AL_INVALID_VALUE);
props->Compressor.OnOff = val;
break;
default:
SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM);
}
}
void ALcompressor_setParamiv(ALeffect *effect, ALCcontext *context, ALenum param, const ALint *vals)
{
ALcompressor_setParami(effect, context, param, vals[0]);
}
void ALcompressor_setParamf(ALeffect *UNUSED(effect), ALCcontext *context, ALenum UNUSED(param), ALfloat UNUSED(val))
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); }
void ALcompressor_setParamfv(ALeffect *effect, ALCcontext *context, ALenum param, const ALfloat *vals)
{
ALcompressor_setParamf(effect, context, param, vals[0]);
}
void ALcompressor_getParami(const ALeffect *effect, ALCcontext *context, ALenum param, ALint *val)
{
const ALeffectProps *props = &effect->Props;
switch(param)
{
case AL_COMPRESSOR_ONOFF:
*val = props->Compressor.OnOff;
break;
default:
SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM);
}
}
void ALcompressor_getParamiv(const ALeffect *effect, ALCcontext *context, ALenum param, ALint *vals)
{
ALcompressor_getParami(effect, context, param, vals);
}
void ALcompressor_getParamf(const ALeffect *UNUSED(effect), ALCcontext *context, ALenum UNUSED(param), ALfloat *UNUSED(val))
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); }
void ALcompressor_getParamfv(const ALeffect *effect, ALCcontext *context, ALenum param, ALfloat *vals)
{
ALcompressor_getParamf(effect, context, param, vals);
}
DEFINE_ALEFFECT_VTABLE(ALcompressor);
|
gentlemans/gentlemanly-engine
|
deps/libRocket/Contrib/Include/Rocket/ProgressBar/ElementProgressBar.h
|
<reponame>gentlemans/gentlemanly-engine
#ifndef ROCKETPROGRESSBARELEMENTPROGRESSBAR_H
#define ROCKETPROGRESSBARELEMENTPROGRESSBAR_H
#include <Rocket/ProgressBar/Header.h>
#include <Rocket/Core/Element.h>
#include <Rocket/Core/Geometry.h>
#include <Rocket/Core/Texture.h>
namespace Rocket {
namespace ProgressBar {
/**
A progress bar element using a value between 0 and 1.
@author <NAME>
*/
class ROCKETPROGRESSBAR_API ElementProgressBar : public Core::Element
{
public:
/// Constructs a new ElementProgressBar. This should not be called directly; use the Factory instead.
/// @param[in] tag The tag the element was declared as in RML.
ElementProgressBar(const Rocket::Core::String& tag);
virtual ~ElementProgressBar();
/// Returns float value between 0 and 1.
/// @return The value of the progress bar.
float GetValue() const;
/// Sets the current value of the progress bar.
/// @param[in] value The new value of the progress bar.
void SetValue(const float value);
protected:
/// Called during the update loop after children are updated.
virtual void OnUpdate();
/// Called during render after backgrounds, borders, decorators, but before children, are rendered.
virtual void OnRender();
/// Called when attributes on the element are changed.
/// @param[in] changed_attributes The attributes changed on the element.
virtual void OnAttributeChange(const Core::AttributeNameList& changed_attributes);
/// Called when properties on the element are changed.
/// @param[in] changed_properties The properties changed on the element.
virtual void OnPropertyChange(const Core::PropertyNameList& changed_properties);
private:
/// Called when value has changed.
void GenerateGeometry();
/// Called when source texture has changed.
void LoadTexture(int index);
Core::Texture texture[3];
// The geometries used to render this element.
Core::Geometry left_geometry;
Core::Geometry center_geometry;
Core::Geometry right_geometry;
bool geometry_dirty;
// The current value of the progress bar.
float value;
};
}
}
#endif
|
gentlemans/gentlemanly-engine
|
deps/libRocket/Contrib/Include/Rocket/ProgressBar/Header.h
|
#ifndef ROCKETPROGRESSBARHEADER_H
#define ROCKETPROGRESSBARHEADER_H
#include <Rocket/Core/Platform.h>
#if !defined STATIC_LIB
#ifdef ROCKET_PLATFORM_WIN32
#ifdef RocketProgressBar_EXPORTS
#define ROCKETPROGRESSBAR_API __declspec(dllexport)
#else
#define ROCKETPROGRESSBAR_API __declspec(dllimport)
#endif
#else
#define ROCKETPROGRESSBAR_API __attribute__((visibility("default")))
#endif
#else
#define ROCKETPROGRESSBAR_API
#endif
#endif
|
gentlemans/gentlemanly-engine
|
deps/libRocket/Contrib/Include/Rocket/ProgressBar.h
|
<filename>deps/libRocket/Contrib/Include/Rocket/ProgressBar.h
#ifndef ROCKETPROGRESSBARPROGRESSBAR_H
#define ROCKETPROGRESSBARPROGRESSBAR_H
#include <Rocket/ProgressBar/Header.h>
namespace Rocket {
namespace ProgressBar {
ROCKETPROGRESSBAR_API void Initialise();
}
}
#endif
|
gentlemans/gentlemanly-engine
|
deps/openal-soft/OpenAL32/Include/alu.h
|
<reponame>gentlemans/gentlemanly-engine<gh_stars>100-1000
#ifndef _ALU_H_
#define _ALU_H_
#include <limits.h>
#include <math.h>
#ifdef HAVE_FLOAT_H
#include <float.h>
#endif
#ifdef HAVE_IEEEFP_H
#include <ieeefp.h>
#endif
#include "alMain.h"
#include "alBuffer.h"
#include "alFilter.h"
#include "hrtf.h"
#include "align.h"
#include "math_defs.h"
#define MAX_PITCH (255)
/* Maximum number of buffer samples before the current pos needed for resampling. */
#define MAX_PRE_SAMPLES 12
/* Maximum number of buffer samples after the current pos needed for resampling. */
#define MAX_POST_SAMPLES 12
#ifdef __cplusplus
extern "C" {
#endif
struct ALsource;
struct ALvoice;
/* The number of distinct scale and phase intervals within the filter table. */
#define BSINC_SCALE_BITS 4
#define BSINC_SCALE_COUNT (1<<BSINC_SCALE_BITS)
#define BSINC_PHASE_BITS 4
#define BSINC_PHASE_COUNT (1<<BSINC_PHASE_BITS)
/* Interpolator state. Kind of a misnomer since the interpolator itself is
* stateless. This just keeps it from having to recompute scale-related
* mappings for every sample.
*/
typedef struct BsincState {
ALfloat sf; /* Scale interpolation factor. */
ALuint m; /* Coefficient count. */
ALint l; /* Left coefficient offset. */
struct {
const ALfloat *filter; /* Filter coefficients. */
const ALfloat *scDelta; /* Scale deltas. */
const ALfloat *phDelta; /* Phase deltas. */
const ALfloat *spDelta; /* Scale-phase deltas. */
} coeffs[BSINC_PHASE_COUNT];
} BsincState;
typedef union aluVector {
alignas(16) ALfloat v[4];
} aluVector;
inline void aluVectorSet(aluVector *vector, ALfloat x, ALfloat y, ALfloat z, ALfloat w)
{
vector->v[0] = x;
vector->v[1] = y;
vector->v[2] = z;
vector->v[3] = w;
}
typedef union aluMatrixf {
alignas(16) ALfloat m[4][4];
} aluMatrixf;
inline void aluMatrixfSetRow(aluMatrixf *matrix, ALuint row,
ALfloat m0, ALfloat m1, ALfloat m2, ALfloat m3)
{
matrix->m[row][0] = m0;
matrix->m[row][1] = m1;
matrix->m[row][2] = m2;
matrix->m[row][3] = m3;
}
inline void aluMatrixfSet(aluMatrixf *matrix, ALfloat m00, ALfloat m01, ALfloat m02, ALfloat m03,
ALfloat m10, ALfloat m11, ALfloat m12, ALfloat m13,
ALfloat m20, ALfloat m21, ALfloat m22, ALfloat m23,
ALfloat m30, ALfloat m31, ALfloat m32, ALfloat m33)
{
aluMatrixfSetRow(matrix, 0, m00, m01, m02, m03);
aluMatrixfSetRow(matrix, 1, m10, m11, m12, m13);
aluMatrixfSetRow(matrix, 2, m20, m21, m22, m23);
aluMatrixfSetRow(matrix, 3, m30, m31, m32, m33);
}
typedef union aluMatrixd {
alignas(16) ALdouble m[4][4];
} aluMatrixd;
inline void aluMatrixdSetRow(aluMatrixd *matrix, ALuint row,
ALdouble m0, ALdouble m1, ALdouble m2, ALdouble m3)
{
matrix->m[row][0] = m0;
matrix->m[row][1] = m1;
matrix->m[row][2] = m2;
matrix->m[row][3] = m3;
}
inline void aluMatrixdSet(aluMatrixd *matrix, ALdouble m00, ALdouble m01, ALdouble m02, ALdouble m03,
ALdouble m10, ALdouble m11, ALdouble m12, ALdouble m13,
ALdouble m20, ALdouble m21, ALdouble m22, ALdouble m23,
ALdouble m30, ALdouble m31, ALdouble m32, ALdouble m33)
{
aluMatrixdSetRow(matrix, 0, m00, m01, m02, m03);
aluMatrixdSetRow(matrix, 1, m10, m11, m12, m13);
aluMatrixdSetRow(matrix, 2, m20, m21, m22, m23);
aluMatrixdSetRow(matrix, 3, m30, m31, m32, m33);
}
enum ActiveFilters {
AF_None = 0,
AF_LowPass = 1,
AF_HighPass = 2,
AF_BandPass = AF_LowPass | AF_HighPass
};
typedef struct MixGains {
ALfloat Current;
ALfloat Step;
ALfloat Target;
} MixGains;
typedef struct DirectParams {
ALfloat (*OutBuffer)[BUFFERSIZE];
ALuint OutChannels;
/* If not 'moving', gain/coefficients are set directly without fading. */
ALboolean Moving;
/* Stepping counter for gain/coefficient fading. */
ALuint Counter;
/* Last direction (relative to listener) and gain of a moving source. */
aluVector LastDir;
ALfloat LastGain;
struct {
enum ActiveFilters ActiveType;
ALfilterState LowPass;
ALfilterState HighPass;
} Filters[MAX_INPUT_CHANNELS];
struct {
HrtfParams Params;
HrtfState State;
} Hrtf[MAX_INPUT_CHANNELS];
MixGains Gains[MAX_INPUT_CHANNELS][MAX_OUTPUT_CHANNELS];
} DirectParams;
typedef struct SendParams {
ALfloat (*OutBuffer)[BUFFERSIZE];
ALboolean Moving;
ALuint Counter;
struct {
enum ActiveFilters ActiveType;
ALfilterState LowPass;
ALfilterState HighPass;
} Filters[MAX_INPUT_CHANNELS];
/* Gain control, which applies to each input channel to a single (mono)
* output buffer. */
MixGains Gains[MAX_INPUT_CHANNELS];
} SendParams;
typedef const ALfloat* (*ResamplerFunc)(const BsincState *state,
const ALfloat *src, ALuint frac, ALuint increment, ALfloat *restrict dst, ALuint dstlen
);
typedef void (*MixerFunc)(const ALfloat *data, ALuint OutChans,
ALfloat (*restrict OutBuffer)[BUFFERSIZE], struct MixGains *Gains,
ALuint Counter, ALuint OutPos, ALuint BufferSize);
typedef void (*HrtfMixerFunc)(ALfloat (*restrict OutBuffer)[BUFFERSIZE], const ALfloat *data,
ALuint Counter, ALuint Offset, ALuint OutPos,
const ALuint IrSize, const HrtfParams *hrtfparams,
HrtfState *hrtfstate, ALuint BufferSize);
#define GAIN_SILENCE_THRESHOLD (0.00001f) /* -100dB */
#define SPEEDOFSOUNDMETRESPERSEC (343.3f)
#define AIRABSORBGAINHF (0.99426f) /* -0.05dB */
#define FRACTIONBITS (12)
#define FRACTIONONE (1<<FRACTIONBITS)
#define FRACTIONMASK (FRACTIONONE-1)
inline ALfloat minf(ALfloat a, ALfloat b)
{ return ((a > b) ? b : a); }
inline ALfloat maxf(ALfloat a, ALfloat b)
{ return ((a > b) ? a : b); }
inline ALfloat clampf(ALfloat val, ALfloat min, ALfloat max)
{ return minf(max, maxf(min, val)); }
inline ALdouble mind(ALdouble a, ALdouble b)
{ return ((a > b) ? b : a); }
inline ALdouble maxd(ALdouble a, ALdouble b)
{ return ((a > b) ? a : b); }
inline ALdouble clampd(ALdouble val, ALdouble min, ALdouble max)
{ return mind(max, maxd(min, val)); }
inline ALuint minu(ALuint a, ALuint b)
{ return ((a > b) ? b : a); }
inline ALuint maxu(ALuint a, ALuint b)
{ return ((a > b) ? a : b); }
inline ALuint clampu(ALuint val, ALuint min, ALuint max)
{ return minu(max, maxu(min, val)); }
inline ALint mini(ALint a, ALint b)
{ return ((a > b) ? b : a); }
inline ALint maxi(ALint a, ALint b)
{ return ((a > b) ? a : b); }
inline ALint clampi(ALint val, ALint min, ALint max)
{ return mini(max, maxi(min, val)); }
inline ALint64 mini64(ALint64 a, ALint64 b)
{ return ((a > b) ? b : a); }
inline ALint64 maxi64(ALint64 a, ALint64 b)
{ return ((a > b) ? a : b); }
inline ALint64 clampi64(ALint64 val, ALint64 min, ALint64 max)
{ return mini64(max, maxi64(min, val)); }
inline ALuint64 minu64(ALuint64 a, ALuint64 b)
{ return ((a > b) ? b : a); }
inline ALuint64 maxu64(ALuint64 a, ALuint64 b)
{ return ((a > b) ? a : b); }
inline ALuint64 clampu64(ALuint64 val, ALuint64 min, ALuint64 max)
{ return minu64(max, maxu64(min, val)); }
union ResamplerCoeffs {
ALfloat FIR4[FRACTIONONE][4];
ALfloat FIR8[FRACTIONONE][8];
};
extern alignas(16) union ResamplerCoeffs ResampleCoeffs;
extern alignas(16) const ALfloat bsincTab[18840];
inline ALfloat lerp(ALfloat val1, ALfloat val2, ALfloat mu)
{
return val1 + (val2-val1)*mu;
}
inline ALfloat resample_fir4(ALfloat val0, ALfloat val1, ALfloat val2, ALfloat val3, ALuint frac)
{
const ALfloat *k = ResampleCoeffs.FIR4[frac];
return k[0]*val0 + k[1]*val1 + k[2]*val2 + k[3]*val3;
}
inline ALfloat resample_fir8(ALfloat val0, ALfloat val1, ALfloat val2, ALfloat val3, ALfloat val4, ALfloat val5, ALfloat val6, ALfloat val7, ALuint frac)
{
const ALfloat *k = ResampleCoeffs.FIR8[frac];
return k[0]*val0 + k[1]*val1 + k[2]*val2 + k[3]*val3 +
k[4]*val4 + k[5]*val5 + k[6]*val6 + k[7]*val7;
}
void aluInitMixer(void);
ALvoid aluInitPanning(ALCdevice *Device);
/**
* ComputeDirectionalGains
*
* Sets channel gains based on a direction. The direction must be a 3-component
* vector no longer than 1 unit.
*/
void ComputeDirectionalGains(const ALCdevice *device, const ALfloat dir[3], ALfloat ingain, ALfloat gains[MAX_OUTPUT_CHANNELS]);
/**
* ComputeAngleGains
*
* Sets channel gains based on angle and elevation. The angle and elevation
* parameters are in radians, going right and up respectively.
*/
void ComputeAngleGains(const ALCdevice *device, ALfloat angle, ALfloat elevation, ALfloat ingain, ALfloat gains[MAX_OUTPUT_CHANNELS]);
/**
* ComputeAmbientGains
*
* Sets channel gains for ambient, omni-directional sounds.
*/
void ComputeAmbientGains(const ALCdevice *device, ALfloat ingain, ALfloat gains[MAX_OUTPUT_CHANNELS]);
/**
* ComputeBFormatGains
*
* Sets channel gains for a given (first-order) B-Format channel. The matrix is
* a 1x4 'slice' of the rotation matrix for a given channel used to orient the
* coefficients.
*/
void ComputeBFormatGains(const ALCdevice *device, const ALfloat mtx[4], ALfloat ingain, ALfloat gains[MAX_OUTPUT_CHANNELS]);
ALvoid UpdateContextSources(ALCcontext *context);
ALvoid CalcSourceParams(struct ALvoice *voice, const struct ALsource *source, const ALCcontext *ALContext);
ALvoid CalcNonAttnSourceParams(struct ALvoice *voice, const struct ALsource *source, const ALCcontext *ALContext);
ALvoid MixSource(struct ALvoice *voice, struct ALsource *source, ALCdevice *Device, ALuint SamplesToDo);
ALvoid aluMixData(ALCdevice *device, ALvoid *buffer, ALsizei size);
/* Caller must lock the device. */
ALvoid aluHandleDisconnect(ALCdevice *device);
extern ALfloat ConeScale;
extern ALfloat ZScale;
#ifdef __cplusplus
}
#endif
#endif
|
gentlemans/gentlemanly-engine
|
deps/openal-soft/Alc/mixer_inc.c
|
#include "config.h"
#include "alMain.h"
#include "alSource.h"
#include "hrtf.h"
#include "mixer_defs.h"
#include "align.h"
static inline void SetupCoeffs(ALfloat (*restrict OutCoeffs)[2],
const HrtfParams *hrtfparams,
ALuint IrSize, ALuint Counter);
static inline void ApplyCoeffsStep(ALuint Offset, ALfloat (*restrict Values)[2],
const ALuint irSize,
ALfloat (*restrict Coeffs)[2],
const ALfloat (*restrict CoeffStep)[2],
ALfloat left, ALfloat right);
static inline void ApplyCoeffs(ALuint Offset, ALfloat (*restrict Values)[2],
const ALuint irSize,
ALfloat (*restrict Coeffs)[2],
ALfloat left, ALfloat right);
void MixHrtf(ALfloat (*restrict OutBuffer)[BUFFERSIZE], const ALfloat *data,
ALuint Counter, ALuint Offset, ALuint OutPos, const ALuint IrSize,
const HrtfParams *hrtfparams, HrtfState *hrtfstate, ALuint BufferSize)
{
alignas(16) ALfloat Coeffs[HRIR_LENGTH][2];
ALuint Delay[2];
ALfloat left, right;
ALuint pos;
SetupCoeffs(Coeffs, hrtfparams, IrSize, Counter);
Delay[0] = hrtfparams->Delay[0] - (hrtfparams->DelayStep[0]*Counter);
Delay[1] = hrtfparams->Delay[1] - (hrtfparams->DelayStep[1]*Counter);
pos = 0;
for(;pos < BufferSize && pos < Counter;pos++)
{
hrtfstate->History[Offset&HRTF_HISTORY_MASK] = data[pos];
left = lerp(hrtfstate->History[(Offset-(Delay[0]>>HRTFDELAY_BITS))&HRTF_HISTORY_MASK],
hrtfstate->History[(Offset-(Delay[0]>>HRTFDELAY_BITS)-1)&HRTF_HISTORY_MASK],
(Delay[0]&HRTFDELAY_MASK)*(1.0f/HRTFDELAY_FRACONE));
right = lerp(hrtfstate->History[(Offset-(Delay[1]>>HRTFDELAY_BITS))&HRTF_HISTORY_MASK],
hrtfstate->History[(Offset-(Delay[1]>>HRTFDELAY_BITS)-1)&HRTF_HISTORY_MASK],
(Delay[1]&HRTFDELAY_MASK)*(1.0f/HRTFDELAY_FRACONE));
Delay[0] += hrtfparams->DelayStep[0];
Delay[1] += hrtfparams->DelayStep[1];
hrtfstate->Values[(Offset+IrSize)&HRIR_MASK][0] = 0.0f;
hrtfstate->Values[(Offset+IrSize)&HRIR_MASK][1] = 0.0f;
Offset++;
ApplyCoeffsStep(Offset, hrtfstate->Values, IrSize, Coeffs, hrtfparams->CoeffStep, left, right);
OutBuffer[0][OutPos] += hrtfstate->Values[Offset&HRIR_MASK][0];
OutBuffer[1][OutPos] += hrtfstate->Values[Offset&HRIR_MASK][1];
OutPos++;
}
Delay[0] >>= HRTFDELAY_BITS;
Delay[1] >>= HRTFDELAY_BITS;
for(;pos < BufferSize;pos++)
{
hrtfstate->History[Offset&HRTF_HISTORY_MASK] = data[pos];
left = hrtfstate->History[(Offset-Delay[0])&HRTF_HISTORY_MASK];
right = hrtfstate->History[(Offset-Delay[1])&HRTF_HISTORY_MASK];
hrtfstate->Values[(Offset+IrSize)&HRIR_MASK][0] = 0.0f;
hrtfstate->Values[(Offset+IrSize)&HRIR_MASK][1] = 0.0f;
Offset++;
ApplyCoeffs(Offset, hrtfstate->Values, IrSize, Coeffs, left, right);
OutBuffer[0][OutPos] += hrtfstate->Values[Offset&HRIR_MASK][0];
OutBuffer[1][OutPos] += hrtfstate->Values[Offset&HRIR_MASK][1];
OutPos++;
}
}
|
gentlemans/gentlemanly-engine
|
deps/openal-soft/Alc/hrtf.h
|
#ifndef ALC_HRTF_H
#define ALC_HRTF_H
#include "AL/al.h"
#include "AL/alc.h"
#include "alstring.h"
enum DevFmtChannels;
struct Hrtf;
typedef struct HrtfEntry {
al_string name;
al_string filename;
const struct Hrtf *hrtf;
} HrtfEntry;
TYPEDEF_VECTOR(HrtfEntry, vector_HrtfEntry)
#define HRIR_BITS (7)
#define HRIR_LENGTH (1<<HRIR_BITS)
#define HRIR_MASK (HRIR_LENGTH-1)
#define HRTFDELAY_BITS (20)
#define HRTFDELAY_FRACONE (1<<HRTFDELAY_BITS)
#define HRTFDELAY_MASK (HRTFDELAY_FRACONE-1)
void FreeHrtfs(void);
vector_HrtfEntry EnumerateHrtf(const_al_string devname);
void FreeHrtfList(vector_HrtfEntry *list);
ALuint GetHrtfSampleRate(const struct Hrtf *Hrtf);
ALuint GetHrtfIrSize(const struct Hrtf *Hrtf);
void GetLerpedHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat dirfact, ALfloat gain, ALfloat (*coeffs)[2], ALuint *delays);
ALuint GetMovingHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat dirfact, ALfloat gain, ALfloat delta, ALint counter, ALfloat (*coeffs)[2], ALuint *delays, ALfloat (*coeffStep)[2], ALint *delayStep);
void GetBFormatHrtfCoeffs(const struct Hrtf *Hrtf, const ALuint num_chans, ALfloat (**coeffs_list)[2], ALuint **delay_list);
#endif /* ALC_HRTF_H */
|
pwmb/vscode-esp-idf-extension
|
templates/new_component/new_component.c
|
<reponame>pwmb/vscode-esp-idf-extension
#include <stdio.h>
#include "new_component.h"
void func(void)
{
}
|
Elbandi/lighttpd
|
src/network_solaris_sendfilev.c
|
#include "network_backends.h"
#ifdef USE_SOLARIS_SENDFILEV
#include "network.h"
#include "fdevent.h"
#include "log.h"
#include "stat_cache.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#ifndef UIO_MAXIOV
# define UIO_MAXIOV IOV_MAX
#endif
/**
* a very simple sendfilev() interface for solaris which can be optimised a lot more
* as solaris sendfilev() supports 'sending everythin in one syscall()'
*
* If you want such an interface and need the performance, just give me an account on
* a solaris box.
* - <EMAIL>
*/
int network_write_chunkqueue_solarissendfilev(server *srv, connection *con, int fd, chunkqueue *cq) {
chunk *c;
size_t chunks_written = 0;
for(c = cq->first; c; c = c->next, chunks_written++) {
int chunk_finished = 0;
switch(c->type) {
case MEM_CHUNK: {
char * offset;
size_t toSend;
ssize_t r;
size_t num_chunks, i;
struct iovec chunks[UIO_MAXIOV];
chunk *tc;
size_t num_bytes = 0;
/* we can't send more then SSIZE_MAX bytes in one chunk */
/* build writev list
*
* 1. limit: num_chunks < UIO_MAXIOV
* 2. limit: num_bytes < SSIZE_MAX
*/
for(num_chunks = 0, tc = c; tc && tc->type == MEM_CHUNK && num_chunks < UIO_MAXIOV; num_chunks++, tc = tc->next);
for(tc = c, i = 0; i < num_chunks; tc = tc->next, i++) {
if (tc->mem->used == 0) {
chunks[i].iov_base = tc->mem->ptr;
chunks[i].iov_len = 0;
} else {
offset = tc->mem->ptr + tc->offset;
toSend = tc->mem->used - 1 - tc->offset;
chunks[i].iov_base = offset;
/* protect the return value of writev() */
if (toSend > SSIZE_MAX ||
num_bytes + toSend > SSIZE_MAX) {
chunks[i].iov_len = SSIZE_MAX - num_bytes;
num_chunks = i + 1;
break;
} else {
chunks[i].iov_len = toSend;
}
num_bytes += toSend;
}
}
if ((r = writev(fd, chunks, num_chunks)) < 0) {
switch (errno) {
case EAGAIN:
case EINTR:
r = 0;
break;
case EPIPE:
case ECONNRESET:
return -2;
default:
log_error_write(srv, __FILE__, __LINE__, "ssd",
"writev failed:", strerror(errno), fd);
return -1;
}
}
/* check which chunks have been written */
cq->bytes_out += r;
for(i = 0, tc = c; i < num_chunks; i++, tc = tc->next) {
if (r >= (ssize_t)chunks[i].iov_len) {
/* written */
r -= chunks[i].iov_len;
tc->offset += chunks[i].iov_len;
if (chunk_finished) {
/* skip the chunks from further touches */
chunks_written++;
c = c->next;
} else {
/* chunks_written + c = c->next is done in the for()*/
chunk_finished++;
}
} else {
/* partially written */
tc->offset += r;
chunk_finished = 0;
break;
}
}
break;
}
case FILE_CHUNK: {
ssize_t r;
off_t offset;
size_t toSend, written;
sendfilevec_t fvec;
stat_cache_entry *sce = NULL;
int ifd;
if (HANDLER_ERROR == stat_cache_get_entry(srv, con, c->file.name, &sce)) {
log_error_write(srv, __FILE__, __LINE__, "sb",
strerror(errno), c->file.name);
return -1;
}
offset = c->file.start + c->offset;
toSend = c->file.length - c->offset;
if (offset > sce->st.st_size) {
log_error_write(srv, __FILE__, __LINE__, "sb", "file was shrinked:", c->file.name);
return -1;
}
if (-1 == (ifd = open(c->file.name->ptr, O_RDONLY))) {
log_error_write(srv, __FILE__, __LINE__, "ss", "open failed: ", strerror(errno));
return -1;
}
fvec.sfv_fd = ifd;
fvec.sfv_flag = 0;
fvec.sfv_off = offset;
fvec.sfv_len = toSend;
/* Solaris sendfilev() */
if (-1 == (r = sendfilev(fd, &fvec, 1, &written))) {
if (errno != EAGAIN) {
log_error_write(srv, __FILE__, __LINE__, "ssd", "sendfile: ", strerror(errno), errno);
close(ifd);
return -1;
}
r = 0;
}
close(ifd);
c->offset += written;
cq->bytes_out += written;
if (c->offset == c->file.length) {
chunk_finished = 1;
}
break;
}
default:
log_error_write(srv, __FILE__, __LINE__, "ds", c, "type not known");
return -1;
}
if (!chunk_finished) {
/* not finished yet */
break;
}
}
return chunks_written;
}
#endif
|
Elbandi/lighttpd
|
src/plugin.c
|
#include "plugin.h"
#include "log.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef HAVE_VALGRIND_VALGRIND_H
# include <valgrind/valgrind.h>
#endif
#ifndef __WIN32
# include <dlfcn.h>
#endif
/*
*
* if you change this enum to add a new callback, be sure
* - that PLUGIN_FUNC_SIZEOF is the last entry
* - that you add PLUGIN_TO_SLOT twice:
* 1. as callback-dispatcher
* 2. in plugins_call_init()
*
*/
typedef struct {
PLUGIN_DATA;
} plugin_data;
typedef enum {
PLUGIN_FUNC_UNSET,
PLUGIN_FUNC_HANDLE_URI_CLEAN,
PLUGIN_FUNC_HANDLE_URI_RAW,
PLUGIN_FUNC_HANDLE_REQUEST_DONE,
PLUGIN_FUNC_HANDLE_CONNECTION_CLOSE,
PLUGIN_FUNC_HANDLE_TRIGGER,
PLUGIN_FUNC_HANDLE_SIGHUP,
PLUGIN_FUNC_HANDLE_SUBREQUEST,
PLUGIN_FUNC_HANDLE_SUBREQUEST_START,
PLUGIN_FUNC_HANDLE_RESPONSE_START,
PLUGIN_FUNC_HANDLE_RESPONSE_FILTER,
PLUGIN_FUNC_HANDLE_JOBLIST,
PLUGIN_FUNC_HANDLE_DOCROOT,
PLUGIN_FUNC_HANDLE_PHYSICAL,
PLUGIN_FUNC_CONNECTION_RESET,
PLUGIN_FUNC_INIT,
PLUGIN_FUNC_CLEANUP,
PLUGIN_FUNC_SET_DEFAULTS,
PLUGIN_FUNC_SIZEOF
} plugin_t;
static plugin *plugin_init(void) {
plugin *p;
p = calloc(1, sizeof(*p));
return p;
}
static void plugin_free(plugin *p) {
int use_dlclose = 1;
if (p->name) buffer_free(p->name);
#ifdef HAVE_VALGRIND_VALGRIND_H
/*if (RUNNING_ON_VALGRIND) use_dlclose = 0;*/
#endif
#ifndef LIGHTTPD_STATIC
if (use_dlclose && p->lib) {
#ifdef __WIN32
FreeLibrary(p->lib);
#else
dlclose(p->lib);
#endif
}
#endif
free(p);
}
static int plugins_register(server *srv, plugin *p) {
plugin **ps;
if (0 == srv->plugins.size) {
srv->plugins.size = 4;
srv->plugins.ptr = malloc(srv->plugins.size * sizeof(*ps));
srv->plugins.used = 0;
} else if (srv->plugins.used == srv->plugins.size) {
srv->plugins.size += 4;
srv->plugins.ptr = realloc(srv->plugins.ptr, srv->plugins.size * sizeof(*ps));
}
ps = srv->plugins.ptr;
ps[srv->plugins.used++] = p;
return 0;
}
/**
*
*
*
*/
#ifdef LIGHTTPD_STATIC
int plugins_load(server *srv) {
plugin *p;
#define PLUGIN_INIT(x)\
p = plugin_init(); \
if (x ## _plugin_init(p)) { \
log_error_write(srv, __FILE__, __LINE__, "ss", #x, "plugin init failed" ); \
plugin_free(p); \
return -1;\
}\
plugins_register(srv, p);
#include "plugin-static.h"
return 0;
}
#else
int plugins_load(server *srv) {
plugin *p;
int (*init)(plugin *pl);
const char *error;
size_t i;
for (i = 0; i < srv->srvconf.modules->used; i++) {
data_string *d = (data_string *)srv->srvconf.modules->data[i];
char *modules = d->value->ptr;
buffer_copy_string_buffer(srv->tmp_buf, srv->srvconf.modules_dir);
buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("/"));
buffer_append_string(srv->tmp_buf, modules);
#if defined(__WIN32) || defined(__CYGWIN__)
buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN(".dll"));
#else
buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN(".so"));
#endif
p = plugin_init();
#ifdef __WIN32
if (NULL == (p->lib = LoadLibrary(srv->tmp_buf->ptr))) {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
log_error_write(srv, __FILE__, __LINE__, "ssb", "LoadLibrary() failed",
lpMsgBuf, srv->tmp_buf);
plugin_free(p);
return -1;
}
#else
if (NULL == (p->lib = dlopen(srv->tmp_buf->ptr, RTLD_NOW|RTLD_GLOBAL))) {
log_error_write(srv, __FILE__, __LINE__, "sbs", "dlopen() failed for:",
srv->tmp_buf, dlerror());
plugin_free(p);
return -1;
}
#endif
buffer_reset(srv->tmp_buf);
buffer_copy_string(srv->tmp_buf, modules);
buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("_plugin_init"));
#ifdef __WIN32
init = GetProcAddress(p->lib, srv->tmp_buf->ptr);
if (init == NULL) {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
log_error_write(srv, __FILE__, __LINE__, "sbs", "getprocaddress failed:", srv->tmp_buf, lpMsgBuf);
plugin_free(p);
return -1;
}
#else
#if 1
init = (int (*)(plugin *))(intptr_t)dlsym(p->lib, srv->tmp_buf->ptr);
#else
*(void **)(&init) = dlsym(p->lib, srv->tmp_buf->ptr);
#endif
if ((error = dlerror()) != NULL) {
log_error_write(srv, __FILE__, __LINE__, "s", error);
plugin_free(p);
return -1;
}
#endif
if ((*init)(p)) {
log_error_write(srv, __FILE__, __LINE__, "ss", modules, "plugin init failed" );
plugin_free(p);
return -1;
}
#if 0
log_error_write(srv, __FILE__, __LINE__, "ss", modules, "plugin loaded" );
#endif
plugins_register(srv, p);
}
return 0;
}
#endif
#define PLUGIN_TO_SLOT(x, y) \
handler_t plugins_call_##y(server *srv, connection *con) {\
plugin **slot;\
size_t j;\
if (!srv->plugin_slots) return HANDLER_GO_ON;\
slot = ((plugin ***)(srv->plugin_slots))[x];\
if (!slot) return HANDLER_GO_ON;\
for (j = 0; j < srv->plugins.used && slot[j]; j++) { \
plugin *p = slot[j];\
handler_t r;\
switch(r = p->y(srv, con, p->data)) {\
case HANDLER_GO_ON:\
break;\
case HANDLER_FINISHED:\
case HANDLER_COMEBACK:\
case HANDLER_WAIT_FOR_EVENT:\
case HANDLER_WAIT_FOR_FD:\
case HANDLER_ERROR:\
return r;\
default:\
log_error_write(srv, __FILE__, __LINE__, "sbs", #x, p->name, "unknown state");\
return HANDLER_ERROR;\
}\
}\
return HANDLER_GO_ON;\
}
/**
* plugins that use
*
* - server *srv
* - connection *con
* - void *p_d (plugin_data *)
*/
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_URI_CLEAN, handle_uri_clean)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_URI_RAW, handle_uri_raw)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_REQUEST_DONE, handle_request_done)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_CONNECTION_CLOSE, handle_connection_close)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_SUBREQUEST, handle_subrequest)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_SUBREQUEST_START, handle_subrequest_start)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_RESPONSE_START, handle_response_start)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_RESPONSE_FILTER, handle_response_filter)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_JOBLIST, handle_joblist)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_DOCROOT, handle_docroot)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_PHYSICAL, handle_physical)
PLUGIN_TO_SLOT(PLUGIN_FUNC_CONNECTION_RESET, connection_reset)
#undef PLUGIN_TO_SLOT
#define PLUGIN_TO_SLOT(x, y) \
handler_t plugins_call_##y(server *srv) {\
plugin **slot;\
size_t j;\
if (!srv->plugin_slots) return HANDLER_GO_ON;\
slot = ((plugin ***)(srv->plugin_slots))[x];\
if (!slot) return HANDLER_GO_ON;\
for (j = 0; j < srv->plugins.used && slot[j]; j++) { \
plugin *p = slot[j];\
handler_t r;\
switch(r = p->y(srv, p->data)) {\
case HANDLER_GO_ON:\
break;\
case HANDLER_FINISHED:\
case HANDLER_COMEBACK:\
case HANDLER_WAIT_FOR_EVENT:\
case HANDLER_WAIT_FOR_FD:\
case HANDLER_ERROR:\
return r;\
default:\
log_error_write(srv, __FILE__, __LINE__, "sbsd", #x, p->name, "unknown state:", r);\
return HANDLER_ERROR;\
}\
}\
return HANDLER_GO_ON;\
}
/**
* plugins that use
*
* - server *srv
* - void *p_d (plugin_data *)
*/
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_TRIGGER, handle_trigger)
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_SIGHUP, handle_sighup)
PLUGIN_TO_SLOT(PLUGIN_FUNC_CLEANUP, cleanup)
PLUGIN_TO_SLOT(PLUGIN_FUNC_SET_DEFAULTS, set_defaults)
#undef PLUGIN_TO_SLOT
#if 0
/**
*
* special handler
*
*/
handler_t plugins_call_handle_fdevent(server *srv, const fd_conn *fdc) {
size_t i;
plugin **ps;
ps = srv->plugins.ptr;
for (i = 0; i < srv->plugins.used; i++) {
plugin *p = ps[i];
if (p->handle_fdevent) {
handler_t r;
switch(r = p->handle_fdevent(srv, fdc, p->data)) {
case HANDLER_GO_ON:
break;
case HANDLER_FINISHED:
case HANDLER_COMEBACK:
case HANDLER_WAIT_FOR_EVENT:
case HANDLER_ERROR:
return r;
default:
log_error_write(srv, __FILE__, __LINE__, "d", r);
break;
}
}
}
return HANDLER_GO_ON;
}
#endif
/**
*
* - call init function of all plugins to init the plugin-internals
* - added each plugin that supports has callback to the corresponding slot
*
* - is only called once.
*/
handler_t plugins_call_init(server *srv) {
size_t i;
plugin **ps;
ps = srv->plugins.ptr;
/* fill slots */
srv->plugin_slots = calloc(PLUGIN_FUNC_SIZEOF, sizeof(ps));
for (i = 0; i < srv->plugins.used; i++) {
size_t j;
/* check which calls are supported */
plugin *p = ps[i];
#define PLUGIN_TO_SLOT(x, y) \
if (p->y) { \
plugin **slot = ((plugin ***)(srv->plugin_slots))[x]; \
if (!slot) { \
slot = calloc(srv->plugins.used, sizeof(*slot));\
((plugin ***)(srv->plugin_slots))[x] = slot; \
} \
for (j = 0; j < srv->plugins.used; j++) { \
if (slot[j]) continue;\
slot[j] = p;\
break;\
}\
}
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_URI_CLEAN, handle_uri_clean);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_URI_RAW, handle_uri_raw);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_REQUEST_DONE, handle_request_done);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_CONNECTION_CLOSE, handle_connection_close);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_TRIGGER, handle_trigger);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_SIGHUP, handle_sighup);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_SUBREQUEST, handle_subrequest);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_SUBREQUEST_START, handle_subrequest_start);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_RESPONSE_START, handle_response_start);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_RESPONSE_FILTER, handle_response_filter);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_JOBLIST, handle_joblist);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_DOCROOT, handle_docroot);
PLUGIN_TO_SLOT(PLUGIN_FUNC_HANDLE_PHYSICAL, handle_physical);
PLUGIN_TO_SLOT(PLUGIN_FUNC_CONNECTION_RESET, connection_reset);
PLUGIN_TO_SLOT(PLUGIN_FUNC_CLEANUP, cleanup);
PLUGIN_TO_SLOT(PLUGIN_FUNC_SET_DEFAULTS, set_defaults);
#undef PLUGIN_TO_SLOT
if (p->init) {
if (NULL == (p->data = p->init())) {
log_error_write(srv, __FILE__, __LINE__, "sb",
"plugin-init failed for module", p->name);
return HANDLER_ERROR;
}
/* used for con->mode, DIRECT == 0, plugins above that */
((plugin_data *)(p->data))->id = i + 1;
if (p->version != LIGHTTPD_VERSION_ID) {
log_error_write(srv, __FILE__, __LINE__, "sb",
"plugin-version doesn't match lighttpd-version for", p->name);
return HANDLER_ERROR;
}
} else {
p->data = NULL;
}
}
return HANDLER_GO_ON;
}
void plugins_free(server *srv) {
size_t i;
plugins_call_cleanup(srv);
for (i = 0; i < srv->plugins.used; i++) {
plugin *p = ((plugin **)srv->plugins.ptr)[i];
plugin_free(p);
}
for (i = 0; srv->plugin_slots && i < PLUGIN_FUNC_SIZEOF; i++) {
plugin **slot = ((plugin ***)(srv->plugin_slots))[i];
if (slot) free(slot);
}
free(srv->plugin_slots);
srv->plugin_slots = NULL;
free(srv->plugins.ptr);
srv->plugins.ptr = NULL;
srv->plugins.used = 0;
}
|
Elbandi/lighttpd
|
src/fdevent_linux_rtsig.c
|
<filename>src/fdevent_linux_rtsig.c
#include "fdevent.h"
#include "buffer.h"
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <limits.h>
#include <fcntl.h>
#ifdef USE_LINUX_SIGIO
static void fdevent_linux_rtsig_free(fdevents *ev) {
free(ev->pollfds);
if (ev->unused.ptr) free(ev->unused.ptr);
bitset_free(ev->sigbset);
}
static int fdevent_linux_rtsig_event_del(fdevents *ev, int fde_ndx, int fd) {
if (fde_ndx < 0) return -1;
if ((size_t)fde_ndx >= ev->used) {
fprintf(stderr, "%s.%d: del! out of range %d %zu\n", __FILE__, __LINE__, fde_ndx, ev->used);
SEGFAULT();
}
if (ev->pollfds[fde_ndx].fd == fd) {
size_t k = fde_ndx;
ev->pollfds[k].fd = -1;
bitset_clear_bit(ev->sigbset, fd);
if (ev->unused.size == 0) {
ev->unused.size = 16;
ev->unused.ptr = malloc(sizeof(*(ev->unused.ptr)) * ev->unused.size);
} else if (ev->unused.size == ev->unused.used) {
ev->unused.size += 16;
ev->unused.ptr = realloc(ev->unused.ptr, sizeof(*(ev->unused.ptr)) * ev->unused.size);
}
ev->unused.ptr[ev->unused.used++] = k;
} else {
fprintf(stderr, "%s.%d: del! %d %d\n", __FILE__, __LINE__, ev->pollfds[fde_ndx].fd, fd);
SEGFAULT();
}
return -1;
}
#if 0
static int fdevent_linux_rtsig_event_compress(fdevents *ev) {
size_t j;
if (ev->used == 0) return 0;
if (ev->unused.used != 0) return 0;
for (j = ev->used - 1; j + 1 > 0; j--) {
if (ev->pollfds[j].fd == -1) ev->used--;
}
return 0;
}
#endif
static int fdevent_linux_rtsig_event_add(fdevents *ev, int fde_ndx, int fd, int events) {
/* known index */
if (fde_ndx != -1) {
if (ev->pollfds[fde_ndx].fd == fd) {
ev->pollfds[fde_ndx].events = events;
return fde_ndx;
}
fprintf(stderr, "%s.%d: add: (%d, %d)\n", __FILE__, __LINE__, fde_ndx, ev->pollfds[fde_ndx].fd);
SEGFAULT();
}
if (ev->unused.used > 0) {
int k = ev->unused.ptr[--ev->unused.used];
ev->pollfds[k].fd = fd;
ev->pollfds[k].events = events;
bitset_set_bit(ev->sigbset, fd);
return k;
} else {
if (ev->size == 0) {
ev->size = 16;
ev->pollfds = malloc(sizeof(*ev->pollfds) * ev->size);
} else if (ev->size == ev->used) {
ev->size += 16;
ev->pollfds = realloc(ev->pollfds, sizeof(*ev->pollfds) * ev->size);
}
ev->pollfds[ev->used].fd = fd;
ev->pollfds[ev->used].events = events;
bitset_set_bit(ev->sigbset, fd);
return ev->used++;
}
}
static int fdevent_linux_rtsig_poll(fdevents *ev, int timeout_ms) {
struct timespec ts;
int r;
#if 0
fdevent_linux_rtsig_event_compress(ev);
#endif
ev->in_sigio = 1;
ts.tv_sec = timeout_ms / 1000;
ts.tv_nsec = (timeout_ms % 1000) * 1000000;
r = sigtimedwait(&(ev->sigset), &(ev->siginfo), &(ts));
if (r == -1) {
if (errno == EAGAIN) return 0;
return r;
} else if (r == SIGIO) {
struct sigaction act;
/* flush the signal queue */
memset(&act, 0, sizeof(act));
act.sa_handler = SIG_IGN;
sigaction(ev->signum, &act, NULL);
/* re-enable the signal queue */
act.sa_handler = SIG_DFL;
sigaction(ev->signum, &act, NULL);
ev->in_sigio = 0;
r = poll(ev->pollfds, ev->used, timeout_ms);
return r;
} else if (r == ev->signum) {
# if 0
fprintf(stderr, "event: %d %02lx\n", ev->siginfo.si_fd, ev->siginfo.si_band);
# endif
return bitset_test_bit(ev->sigbset, ev->siginfo.si_fd);
} else {
/* ? */
return -1;
}
}
static int fdevent_linux_rtsig_event_get_revent(fdevents *ev, size_t ndx) {
if (ev->in_sigio == 1) {
# if 0
if (ev->siginfo.si_band == POLLERR) {
fprintf(stderr, "event: %d %02lx %02x %s\n", ev->siginfo.si_fd, ev->siginfo.si_band, errno, strerror(errno));
}
# endif
if (ndx != 0) {
fprintf(stderr, "+\n");
return 0;
}
return ev->siginfo.si_band & 0x3f;
} else {
if (ndx >= ev->used) {
fprintf(stderr, "%s.%d: event: %zu %zu\n", __FILE__, __LINE__, ndx, ev->used);
return 0;
}
return ev->pollfds[ndx].revents;
}
}
static int fdevent_linux_rtsig_event_get_fd(fdevents *ev, size_t ndx) {
if (ev->in_sigio == 1) {
return ev->siginfo.si_fd;
} else {
return ev->pollfds[ndx].fd;
}
}
static int fdevent_linux_rtsig_fcntl_set(fdevents *ev, int fd) {
static pid_t pid = 0;
if (pid == 0) pid = getpid();
if (-1 == fcntl(fd, F_SETSIG, ev->signum)) return -1;
if (-1 == fcntl(fd, F_SETOWN, (int) pid)) return -1;
return fcntl(fd, F_SETFL, O_ASYNC | O_NONBLOCK | O_RDWR);
}
static int fdevent_linux_rtsig_event_next_fdndx(fdevents *ev, int ndx) {
if (ev->in_sigio == 1) {
if (ndx < 0) return 0;
return -1;
} else {
size_t i;
i = (ndx < 0) ? 0 : ndx + 1;
for (; i < ev->used; i++) {
if (ev->pollfds[i].revents) break;
}
return i;
}
}
int fdevent_linux_rtsig_init(fdevents *ev) {
ev->type = FDEVENT_HANDLER_LINUX_RTSIG;
#define SET(x) \
ev->x = fdevent_linux_rtsig_##x;
SET(free);
SET(poll);
SET(event_del);
SET(event_add);
SET(event_next_fdndx);
SET(fcntl_set);
SET(event_get_fd);
SET(event_get_revent);
ev->signum = SIGRTMIN + 1;
sigemptyset(&(ev->sigset));
sigaddset(&(ev->sigset), ev->signum);
sigaddset(&(ev->sigset), SIGIO);
if (-1 == sigprocmask(SIG_BLOCK, &(ev->sigset), NULL)) {
fprintf(stderr, "%s.%d: sigprocmask failed (%s), try to set server.event-handler = \"poll\" or \"select\"\n",
__FILE__, __LINE__, strerror(errno));
return -1;
}
ev->in_sigio = 1;
ev->sigbset = bitset_init(ev->maxfds);
return 0;
}
#else
int fdevent_linux_rtsig_init(fdevents *ev) {
UNUSED(ev);
fprintf(stderr, "%s.%d: linux-rtsig not supported, try to set server.event-handler = \"poll\" or \"select\"\n",
__FILE__, __LINE__);
return -1;
}
#endif
|
Elbandi/lighttpd
|
src/configfile.c
|
#include "server.h"
#include "log.h"
#include "stream.h"
#include "plugin.h"
#include "configparser.h"
#include "configfile.h"
#include "proc_open.h"
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <assert.h>
static int config_insert(server *srv) {
size_t i;
int ret = 0;
buffer *stat_cache_string;
config_values_t cv[] = {
{ "server.bind", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 0 */
{ "server.errorlog", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 1 */
{ "server.errorfile-prefix", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 2 */
{ "server.chroot", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 3 */
{ "server.username", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 4 */
{ "server.groupname", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 5 */
{ "server.port", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_SERVER }, /* 6 */
{ "server.tag", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
{ "server.use-ipv6", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
{ "server.modules", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_SERVER }, /* 9 */
{ "server.event-handler", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 10 */
{ "server.pid-file", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 11 */
{ "server.max-request-size", NULL, T_CONFIG_INT, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
{ "server.max-worker", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_SERVER }, /* 13 */
{ "server.document-root", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 14 */
{ "server.force-lowercase-filenames", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER },/* 15 */
{ "debug.log-condition-handling", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 16 */
{ "server.max-keep-alive-requests", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },/* 17 */
{ "server.name", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 18 */
{ "server.max-keep-alive-idle", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 19 */
{ "server.max-read-idle", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 20 */
{ "server.max-write-idle", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 21 */
{ "server.error-handler-404", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 22 */
{ "server.max-fds", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_SERVER }, /* 23 */
#ifdef HAVE_LSTAT
{ "server.follow-symlink", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 24 */
#else
{ "server.follow-symlink",
"Your system lacks lstat(). We can not differ symlinks from files."
"Please remove server.follow-symlinks from your config.",
T_CONFIG_UNSUPPORTED, T_CONFIG_SCOPE_UNSET }, /* 24 */
#endif
{ "server.kbytes-per-second", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 25 */
{ "connection.kbytes-per-second", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 26 */
{ "mimetype.use-xattr", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 27 */
{ "mimetype.assign", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 28 */
{ "ssl.pemfile", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 29 */
{ "ssl.engine", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 30 */
{ "debug.log-file-not-found", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 31 */
{ "debug.log-request-handling", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 32 */
{ "debug.log-response-header", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 33 */
{ "debug.log-request-header", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 34 */
{ "debug.log-ssl-noise", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 35 */
{ "server.protocol-http11", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 36 */
{ "debug.log-request-header-on-error", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 37 */
{ "debug.log-state-handling", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 38 */
{ "ssl.ca-file", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 39 */
{ "server.errorlog-use-syslog", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 40 */
{ "server.range-requests", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 41 */
{ "server.stat-cache-engine", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 42 */
{ "server.max-connections", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_SERVER }, /* 43 */
{ "server.network-backend", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 44 */
{ "server.upload-dirs", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 45 */
{ "server.core-files", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 46 */
{ "ssl.cipher-list", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 47 */
{ "ssl.use-sslv2", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 48 */
{ "etag.use-inode", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 49 */
{ "etag.use-mtime", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 50 */
{ "etag.use-size", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 51 */
{ "server.reject-expect-100-with-417", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 52 */
{ "debug.log-timeouts", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 53 */
{ "server.defer-accept", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 54 */
{ "server.breakagelog", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 55 */
{ "ssl.verifyclient.activate", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 56 */
{ "ssl.verifyclient.enforce", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 57 */
{ "ssl.verifyclient.depth", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_SERVER }, /* 58 */
{ "ssl.verifyclient.username", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_SERVER }, /* 59 */
{ "ssl.verifyclient.exportcert", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_SERVER }, /* 60 */
{ "server.use-noatime", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 61 */
{ "server.stat-cache-simple-timeout", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 62 */
{ "server.error-handler-410", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 63 */
{ "server.host", "use server.bind instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ "server.docroot", "use server.document-root instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ "server.virtual-root", "load mod_simple_vhost and use simple-vhost.server-root instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ "server.virtual-default-host", "load mod_simple_vhost and use simple-vhost.default-host instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ "server.virtual-docroot", "load mod_simple_vhost and use simple-vhost.document-root instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ "server.userid", "use server.username instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ "server.groupid", "use server.groupname instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ "server.use-keep-alive", "use server.max-keep-alive-requests = 0 instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ "server.force-lower-case-files", "use server.force-lowercase-filenames instead", T_CONFIG_DEPRECATED, T_CONFIG_SCOPE_UNSET },
{ NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
};
/* 0 */
cv[0].destination = srv->srvconf.bindhost;
cv[1].destination = srv->srvconf.errorlog_file;
cv[3].destination = srv->srvconf.changeroot;
cv[4].destination = srv->srvconf.username;
cv[5].destination = srv->srvconf.groupname;
cv[6].destination = &(srv->srvconf.port);
cv[9].destination = srv->srvconf.modules;
cv[10].destination = srv->srvconf.event_handler;
cv[11].destination = srv->srvconf.pid_file;
cv[13].destination = &(srv->srvconf.max_worker);
cv[23].destination = &(srv->srvconf.max_fds);
cv[37].destination = &(srv->srvconf.log_request_header_on_error);
cv[38].destination = &(srv->srvconf.log_state_handling);
cv[40].destination = &(srv->srvconf.errorlog_use_syslog);
stat_cache_string = buffer_init();
cv[42].destination = stat_cache_string;
cv[44].destination = srv->srvconf.network_backend;
cv[45].destination = srv->srvconf.upload_tempdirs;
cv[46].destination = &(srv->srvconf.enable_cores);
cv[43].destination = &(srv->srvconf.max_conns);
cv[12].destination = &(srv->srvconf.max_request_size);
cv[52].destination = &(srv->srvconf.reject_expect_100_with_417);
cv[55].destination = srv->srvconf.breakagelog_file;
cv[61].destination = &(srv->srvconf.use_noatime);
cv[62].destination = srv->srvconf.stat_cache_simple_timeout;
srv->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *));
assert(srv->config_storage);
for (i = 0; i < srv->config_context->used; i++) {
specific_config *s;
s = calloc(1, sizeof(specific_config));
assert(s);
s->document_root = buffer_init();
s->mimetypes = array_init();
s->server_name = buffer_init();
s->ssl_pemfile = buffer_init();
s->ssl_ca_file = buffer_init();
s->error_handler = buffer_init();
s->error_handler_410 = buffer_init();
s->server_tag = buffer_init();
s->ssl_cipher_list = buffer_init();
s->errorfile_prefix = buffer_init();
s->max_keep_alive_requests = 16;
s->max_keep_alive_idle = 5;
s->max_read_idle = 60;
s->max_write_idle = 360;
s->use_xattr = 0;
s->is_ssl = 0;
s->ssl_use_sslv2 = 0;
s->use_ipv6 = 0;
s->defer_accept = 0;
#ifdef HAVE_LSTAT
s->follow_symlink = 1;
#endif
s->kbytes_per_second = 0;
s->allow_http11 = 1;
s->etag_use_inode = 1;
s->etag_use_mtime = 1;
s->etag_use_size = 1;
s->range_requests = 1;
s->force_lowercase_filenames = 0;
s->global_kbytes_per_second = 0;
s->global_bytes_per_second_cnt = 0;
s->global_bytes_per_second_cnt_ptr = &s->global_bytes_per_second_cnt;
s->ssl_verifyclient = 0;
s->ssl_verifyclient_enforce = 1;
s->ssl_verifyclient_username = buffer_init();
s->ssl_verifyclient_depth = 9;
s->ssl_verifyclient_export_cert = 0;
cv[2].destination = s->errorfile_prefix;
cv[7].destination = s->server_tag;
cv[8].destination = &(s->use_ipv6);
cv[54].destination = &(s->defer_accept);
/* 13 max-worker */
cv[14].destination = s->document_root;
cv[15].destination = &(s->force_lowercase_filenames);
cv[16].destination = &(s->log_condition_handling);
cv[17].destination = &(s->max_keep_alive_requests);
cv[18].destination = s->server_name;
cv[19].destination = &(s->max_keep_alive_idle);
cv[20].destination = &(s->max_read_idle);
cv[21].destination = &(s->max_write_idle);
cv[22].destination = s->error_handler;
cv[63].destination = s->error_handler_410;
#ifdef HAVE_LSTAT
cv[24].destination = &(s->follow_symlink);
#endif
/* 23 -> max-fds */
cv[25].destination = &(s->global_kbytes_per_second);
cv[26].destination = &(s->kbytes_per_second);
cv[27].destination = &(s->use_xattr);
cv[28].destination = s->mimetypes;
cv[29].destination = s->ssl_pemfile;
cv[30].destination = &(s->is_ssl);
cv[31].destination = &(s->log_file_not_found);
cv[32].destination = &(s->log_request_handling);
cv[33].destination = &(s->log_response_header);
cv[34].destination = &(s->log_request_header);
cv[35].destination = &(s->log_ssl_noise);
cv[53].destination = &(s->log_timeouts);
cv[36].destination = &(s->allow_http11);
cv[39].destination = s->ssl_ca_file;
cv[41].destination = &(s->range_requests);
cv[47].destination = s->ssl_cipher_list;
cv[48].destination = &(s->ssl_use_sslv2);
cv[49].destination = &(s->etag_use_inode);
cv[50].destination = &(s->etag_use_mtime);
cv[51].destination = &(s->etag_use_size);
/* ssl.verify */
cv[56].destination = &(s->ssl_verifyclient);
cv[57].destination = &(s->ssl_verifyclient_enforce);
cv[58].destination = &(s->ssl_verifyclient_depth);
cv[59].destination = s->ssl_verifyclient_username;
cv[60].destination = &(s->ssl_verifyclient_export_cert);
srv->config_storage[i] = s;
if (0 != (ret = config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv))) {
break;
}
}
if (buffer_is_empty(stat_cache_string)) {
srv->srvconf.stat_cache_engine = STAT_CACHE_ENGINE_SIMPLE;
} else if (buffer_is_equal_string(stat_cache_string, CONST_STR_LEN("simple"))) {
srv->srvconf.stat_cache_engine = STAT_CACHE_ENGINE_SIMPLE;
#ifdef HAVE_FAM_H
} else if (buffer_is_equal_string(stat_cache_string, CONST_STR_LEN("fam"))) {
srv->srvconf.stat_cache_engine = STAT_CACHE_ENGINE_FAM;
#endif
} else if (buffer_is_equal_string(stat_cache_string, CONST_STR_LEN("disable"))) {
srv->srvconf.stat_cache_engine = STAT_CACHE_ENGINE_NONE;
} else {
log_error_write(srv, __FILE__, __LINE__, "sb",
"server.stat-cache-engine can be one of \"disable\", \"simple\","
#ifdef HAVE_FAM_H
" \"fam\","
#endif
" but not:", stat_cache_string);
ret = HANDLER_ERROR;
}
buffer_free(stat_cache_string);
return ret;
}
#define PATCH(x) con->conf.x = s->x
int config_setup_connection(server *srv, connection *con) {
specific_config *s = srv->config_storage[0];
PATCH(allow_http11);
PATCH(mimetypes);
PATCH(document_root);
PATCH(max_keep_alive_requests);
PATCH(max_keep_alive_idle);
PATCH(max_read_idle);
PATCH(max_write_idle);
PATCH(use_xattr);
PATCH(error_handler);
PATCH(error_handler_410);
PATCH(errorfile_prefix);
#ifdef HAVE_LSTAT
PATCH(follow_symlink);
#endif
PATCH(server_tag);
PATCH(kbytes_per_second);
PATCH(global_kbytes_per_second);
PATCH(global_bytes_per_second_cnt);
con->conf.global_bytes_per_second_cnt_ptr = &s->global_bytes_per_second_cnt;
buffer_copy_string_buffer(con->server_name, s->server_name);
PATCH(log_request_header);
PATCH(log_response_header);
PATCH(log_request_handling);
PATCH(log_condition_handling);
PATCH(log_file_not_found);
PATCH(log_ssl_noise);
PATCH(log_timeouts);
PATCH(range_requests);
PATCH(force_lowercase_filenames);
PATCH(is_ssl);
PATCH(ssl_pemfile);
#ifdef USE_OPENSSL
PATCH(ssl_ctx);
#endif
PATCH(ssl_ca_file);
PATCH(ssl_cipher_list);
PATCH(ssl_use_sslv2);
PATCH(etag_use_inode);
PATCH(etag_use_mtime);
PATCH(etag_use_size);
PATCH(ssl_verifyclient);
PATCH(ssl_verifyclient_enforce);
PATCH(ssl_verifyclient_depth);
PATCH(ssl_verifyclient_username);
PATCH(ssl_verifyclient_export_cert);
return 0;
}
int config_patch_connection(server *srv, connection *con, comp_key_t comp) {
size_t i, j;
con->conditional_is_valid[comp] = 1;
/* skip the first, the global context */
for (i = 1; i < srv->config_context->used; i++) {
data_config *dc = (data_config *)srv->config_context->data[i];
specific_config *s = srv->config_storage[i];
/* condition didn't match */
if (!config_check_cond(srv, con, dc)) continue;
/* merge config */
for (j = 0; j < dc->value->used; j++) {
data_unset *du = dc->value->data[j];
if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.document-root"))) {
PATCH(document_root);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.range-requests"))) {
PATCH(range_requests);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.error-handler-404"))) {
PATCH(error_handler);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.error-handler-410"))) {
PATCH(error_handler_410);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.errorfile-prefix"))) {
PATCH(errorfile_prefix);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("mimetype.assign"))) {
PATCH(mimetypes);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.max-keep-alive-requests"))) {
PATCH(max_keep_alive_requests);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.max-keep-alive-idle"))) {
PATCH(max_keep_alive_idle);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.max-write-idle"))) {
PATCH(max_write_idle);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.max-read-idle"))) {
PATCH(max_read_idle);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("mimetype.use-xattr"))) {
PATCH(use_xattr);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("etag.use-inode"))) {
PATCH(etag_use_inode);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("etag.use-mtime"))) {
PATCH(etag_use_mtime);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("etag.use-size"))) {
PATCH(etag_use_size);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.pemfile"))) {
PATCH(ssl_pemfile);
#ifdef USE_OPENSSL
PATCH(ssl_ctx);
#endif
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ca-file"))) {
PATCH(ssl_ca_file);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.use-sslv2"))) {
PATCH(ssl_use_sslv2);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.cipher-list"))) {
PATCH(ssl_cipher_list);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.engine"))) {
PATCH(is_ssl);
#ifdef HAVE_LSTAT
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.follow-symlink"))) {
PATCH(follow_symlink);
#endif
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.name"))) {
buffer_copy_string_buffer(con->server_name, s->server_name);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.tag"))) {
PATCH(server_tag);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("connection.kbytes-per-second"))) {
PATCH(kbytes_per_second);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-request-handling"))) {
PATCH(log_request_handling);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-request-header"))) {
PATCH(log_request_header);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-response-header"))) {
PATCH(log_response_header);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-condition-handling"))) {
PATCH(log_condition_handling);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-file-not-found"))) {
PATCH(log_file_not_found);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-ssl-noise"))) {
PATCH(log_ssl_noise);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-timeouts"))) {
PATCH(log_timeouts);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.protocol-http11"))) {
PATCH(allow_http11);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.force-lowercase-filenames"))) {
PATCH(force_lowercase_filenames);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("server.kbytes-per-second"))) {
PATCH(global_kbytes_per_second);
PATCH(global_bytes_per_second_cnt);
con->conf.global_bytes_per_second_cnt_ptr = &s->global_bytes_per_second_cnt;
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.activate"))) {
PATCH(ssl_verifyclient);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.enforce"))) {
PATCH(ssl_verifyclient_enforce);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.depth"))) {
PATCH(ssl_verifyclient_depth);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.username"))) {
PATCH(ssl_verifyclient_username);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.exportcert"))) {
PATCH(ssl_verifyclient_export_cert);
}
}
}
con->etag_flags = (con->conf.etag_use_mtime ? ETAG_USE_MTIME : 0) |
(con->conf.etag_use_inode ? ETAG_USE_INODE : 0) |
(con->conf.etag_use_size ? ETAG_USE_SIZE : 0);
return 0;
}
#undef PATCH
typedef struct {
int foo;
int bar;
const buffer *source;
const char *input;
size_t offset;
size_t size;
int line_pos;
int line;
int in_key;
int in_brace;
int in_cond;
} tokenizer_t;
#if 0
static int tokenizer_open(server *srv, tokenizer_t *t, buffer *basedir, const char *fn) {
if (buffer_is_empty(basedir) ||
(fn[0] == '/' || fn[0] == '\\') ||
(fn[0] == '.' && (fn[1] == '/' || fn[1] == '\\'))) {
t->file = buffer_init_string(fn);
} else {
t->file = buffer_init_buffer(basedir);
buffer_append_string(t->file, fn);
}
if (0 != stream_open(&(t->s), t->file)) {
log_error_write(srv, __FILE__, __LINE__, "sbss",
"opening configfile ", t->file, "failed:", strerror(errno));
buffer_free(t->file);
return -1;
}
t->input = t->s.start;
t->offset = 0;
t->size = t->s.size;
t->line = 1;
t->line_pos = 1;
t->in_key = 1;
t->in_brace = 0;
t->in_cond = 0;
return 0;
}
static int tokenizer_close(server *srv, tokenizer_t *t) {
UNUSED(srv);
buffer_free(t->file);
return stream_close(&(t->s));
}
#endif
static int config_skip_newline(tokenizer_t *t) {
int skipped = 1;
assert(t->input[t->offset] == '\r' || t->input[t->offset] == '\n');
if (t->input[t->offset] == '\r' && t->input[t->offset + 1] == '\n') {
skipped ++;
t->offset ++;
}
t->offset ++;
return skipped;
}
static int config_skip_comment(tokenizer_t *t) {
int i;
assert(t->input[t->offset] == '#');
for (i = 1; t->input[t->offset + i] &&
(t->input[t->offset + i] != '\n' && t->input[t->offset + i] != '\r');
i++);
t->offset += i;
return i;
}
static int config_tokenizer(server *srv, tokenizer_t *t, int *token_id, buffer *token) {
int tid = 0;
size_t i;
for (tid = 0; tid == 0 && t->offset < t->size && t->input[t->offset] ; ) {
char c = t->input[t->offset];
const char *start = NULL;
switch (c) {
case '=':
if (t->in_brace) {
if (t->input[t->offset + 1] == '>') {
t->offset += 2;
buffer_copy_string_len(token, CONST_STR_LEN("=>"));
tid = TK_ARRAY_ASSIGN;
} else {
log_error_write(srv, __FILE__, __LINE__, "sbsdsds",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"use => for assignments in arrays");
return -1;
}
} else if (t->in_cond) {
if (t->input[t->offset + 1] == '=') {
t->offset += 2;
buffer_copy_string_len(token, CONST_STR_LEN("=="));
tid = TK_EQ;
} else if (t->input[t->offset + 1] == '~') {
t->offset += 2;
buffer_copy_string_len(token, CONST_STR_LEN("=~"));
tid = TK_MATCH;
} else {
log_error_write(srv, __FILE__, __LINE__, "sbsdsds",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"only =~ and == are allowed in the condition");
return -1;
}
t->in_key = 1;
t->in_cond = 0;
} else if (t->in_key) {
tid = TK_ASSIGN;
buffer_copy_string_len(token, t->input + t->offset, 1);
t->offset++;
t->line_pos++;
} else {
log_error_write(srv, __FILE__, __LINE__, "sbsdsds",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"unexpected equal-sign: =");
return -1;
}
break;
case '!':
if (t->in_cond) {
if (t->input[t->offset + 1] == '=') {
t->offset += 2;
buffer_copy_string_len(token, CONST_STR_LEN("!="));
tid = TK_NE;
} else if (t->input[t->offset + 1] == '~') {
t->offset += 2;
buffer_copy_string_len(token, CONST_STR_LEN("!~"));
tid = TK_NOMATCH;
} else {
log_error_write(srv, __FILE__, __LINE__, "sbsdsds",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"only !~ and != are allowed in the condition");
return -1;
}
t->in_key = 1;
t->in_cond = 0;
} else {
log_error_write(srv, __FILE__, __LINE__, "sbsdsds",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"unexpected exclamation-marks: !");
return -1;
}
break;
case '\t':
case ' ':
t->offset++;
t->line_pos++;
break;
case '\n':
case '\r':
if (t->in_brace == 0) {
int done = 0;
while (!done && t->offset < t->size) {
switch (t->input[t->offset]) {
case '\r':
case '\n':
config_skip_newline(t);
t->line_pos = 1;
t->line++;
break;
case '#':
t->line_pos += config_skip_comment(t);
break;
case '\t':
case ' ':
t->offset++;
t->line_pos++;
break;
default:
done = 1;
}
}
t->in_key = 1;
tid = TK_EOL;
buffer_copy_string_len(token, CONST_STR_LEN("(EOL)"));
} else {
config_skip_newline(t);
t->line_pos = 1;
t->line++;
}
break;
case ',':
if (t->in_brace > 0) {
tid = TK_COMMA;
buffer_copy_string_len(token, CONST_STR_LEN("(COMMA)"));
}
t->offset++;
t->line_pos++;
break;
case '"':
/* search for the terminating " */
start = t->input + t->offset + 1;
buffer_copy_string_len(token, CONST_STR_LEN(""));
for (i = 1; t->input[t->offset + i]; i++) {
if (t->input[t->offset + i] == '\\' &&
t->input[t->offset + i + 1] == '"') {
buffer_append_string_len(token, start, t->input + t->offset + i - start);
start = t->input + t->offset + i + 1;
/* skip the " */
i++;
continue;
}
if (t->input[t->offset + i] == '"') {
tid = TK_STRING;
buffer_append_string_len(token, start, t->input + t->offset + i - start);
break;
}
}
if (t->input[t->offset + i] == '\0') {
/* ERROR */
log_error_write(srv, __FILE__, __LINE__, "sbsdsds",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"missing closing quote");
return -1;
}
t->offset += i + 1;
t->line_pos += i + 1;
break;
case '(':
t->offset++;
t->in_brace++;
tid = TK_LPARAN;
buffer_copy_string_len(token, CONST_STR_LEN("("));
break;
case ')':
t->offset++;
t->in_brace--;
tid = TK_RPARAN;
buffer_copy_string_len(token, CONST_STR_LEN(")"));
break;
case '$':
t->offset++;
tid = TK_DOLLAR;
t->in_cond = 1;
t->in_key = 0;
buffer_copy_string_len(token, CONST_STR_LEN("$"));
break;
case '+':
if (t->input[t->offset + 1] == '=') {
t->offset += 2;
buffer_copy_string_len(token, CONST_STR_LEN("+="));
tid = TK_APPEND;
} else {
t->offset++;
tid = TK_PLUS;
buffer_copy_string_len(token, CONST_STR_LEN("+"));
}
break;
case '{':
t->offset++;
tid = TK_LCURLY;
buffer_copy_string_len(token, CONST_STR_LEN("{"));
break;
case '}':
t->offset++;
tid = TK_RCURLY;
buffer_copy_string_len(token, CONST_STR_LEN("}"));
break;
case '[':
t->offset++;
tid = TK_LBRACKET;
buffer_copy_string_len(token, CONST_STR_LEN("["));
break;
case ']':
t->offset++;
tid = TK_RBRACKET;
buffer_copy_string_len(token, CONST_STR_LEN("]"));
break;
case '#':
t->line_pos += config_skip_comment(t);
break;
default:
if (t->in_cond) {
for (i = 0; t->input[t->offset + i] &&
(isalpha((unsigned char)t->input[t->offset + i])
); i++);
if (i && t->input[t->offset + i]) {
tid = TK_SRVVARNAME;
buffer_copy_string_len(token, t->input + t->offset, i);
t->offset += i;
t->line_pos += i;
} else {
/* ERROR */
log_error_write(srv, __FILE__, __LINE__, "sbsdsds",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"invalid character in condition");
return -1;
}
} else if (isdigit((unsigned char)c)) {
/* take all digits */
for (i = 0; t->input[t->offset + i] && isdigit((unsigned char)t->input[t->offset + i]); i++);
/* was there it least a digit ? */
if (i) {
tid = TK_INTEGER;
buffer_copy_string_len(token, t->input + t->offset, i);
t->offset += i;
t->line_pos += i;
}
} else {
/* the key might consist of [-.0-9a-z] */
for (i = 0; t->input[t->offset + i] &&
(isalnum((unsigned char)t->input[t->offset + i]) ||
t->input[t->offset + i] == '.' ||
t->input[t->offset + i] == '_' || /* for env.* */
t->input[t->offset + i] == '-'
); i++);
if (i && t->input[t->offset + i]) {
buffer_copy_string_len(token, t->input + t->offset, i);
if (strcmp(token->ptr, "include") == 0) {
tid = TK_INCLUDE;
} else if (strcmp(token->ptr, "include_shell") == 0) {
tid = TK_INCLUDE_SHELL;
} else if (strcmp(token->ptr, "global") == 0) {
tid = TK_GLOBAL;
} else if (strcmp(token->ptr, "else") == 0) {
tid = TK_ELSE;
} else {
tid = TK_LKEY;
}
t->offset += i;
t->line_pos += i;
} else {
/* ERROR */
log_error_write(srv, __FILE__, __LINE__, "sbsdsds",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"invalid character in variable name");
return -1;
}
}
break;
}
}
if (tid) {
*token_id = tid;
#if 0
log_error_write(srv, __FILE__, __LINE__, "sbsdsdbdd",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
token, token->used - 1, tid);
#endif
return 1;
} else if (t->offset < t->size) {
fprintf(stderr, "%s.%d: %d, %s\n",
__FILE__, __LINE__,
tid, token->ptr);
}
return 0;
}
static int config_parse(server *srv, config_t *context, tokenizer_t *t) {
void *pParser;
int token_id;
buffer *token, *lasttoken;
int ret;
pParser = configparserAlloc( malloc );
lasttoken = buffer_init();
token = buffer_init();
while((1 == (ret = config_tokenizer(srv, t, &token_id, token))) && context->ok) {
buffer_copy_string_buffer(lasttoken, token);
configparser(pParser, token_id, token, context);
token = buffer_init();
}
buffer_free(token);
if (ret != -1 && context->ok) {
/* add an EOL at EOF, better than say sorry */
configparser(pParser, TK_EOL, buffer_init_string("(EOL)"), context);
if (context->ok) {
configparser(pParser, 0, NULL, context);
}
}
configparserFree(pParser, free);
if (ret == -1) {
log_error_write(srv, __FILE__, __LINE__, "sb",
"configfile parser failed at:", lasttoken);
} else if (context->ok == 0) {
log_error_write(srv, __FILE__, __LINE__, "sbsdsdsb",
"source:", t->source,
"line:", t->line, "pos:", t->line_pos,
"parser failed somehow near here:", lasttoken);
ret = -1;
}
buffer_free(lasttoken);
return ret == -1 ? -1 : 0;
}
static int tokenizer_init(tokenizer_t *t, const buffer *source, const char *input, size_t size) {
t->source = source;
t->input = input;
t->size = size;
t->offset = 0;
t->line = 1;
t->line_pos = 1;
t->in_key = 1;
t->in_brace = 0;
t->in_cond = 0;
return 0;
}
int config_parse_file(server *srv, config_t *context, const char *fn) {
tokenizer_t t;
stream s;
int ret;
buffer *filename;
if (buffer_is_empty(context->basedir) ||
(fn[0] == '/' || fn[0] == '\\') ||
(fn[0] == '.' && (fn[1] == '/' || fn[1] == '\\'))) {
filename = buffer_init_string(fn);
} else {
filename = buffer_init_buffer(context->basedir);
buffer_append_string(filename, fn);
}
if (0 != stream_open(&s, filename)) {
if (s.size == 0) {
/* the file was empty, nothing to parse */
ret = 0;
} else {
log_error_write(srv, __FILE__, __LINE__, "sbss",
"opening configfile ", filename, "failed:", strerror(errno));
ret = -1;
}
} else {
tokenizer_init(&t, filename, s.start, s.size);
ret = config_parse(srv, context, &t);
}
stream_close(&s);
buffer_free(filename);
return ret;
}
static char* getCWD() {
char *s, *s1;
size_t len;
#ifdef PATH_MAX
len = PATH_MAX;
#else
len = 4096;
#endif
s = malloc(len);
if (!s) return NULL;
while (NULL == getcwd(s, len)) {
if (errno != ERANGE || SSIZE_MAX - len < len) return NULL;
len *= 2;
s1 = realloc(s, len);
if (!s1) {
free(s);
return NULL;
}
s = s1;
}
return s;
}
int config_parse_cmd(server *srv, config_t *context, const char *cmd) {
tokenizer_t t;
int ret;
buffer *source;
buffer *out;
char *oldpwd;
if (NULL == (oldpwd = getCWD())) {
log_error_write(srv, __FILE__, __LINE__, "s",
"cannot get cwd", strerror(errno));
return -1;
}
source = buffer_init_string(cmd);
out = buffer_init();
if (!buffer_is_empty(context->basedir)) {
chdir(context->basedir->ptr);
}
if (0 != proc_open_buffer(cmd, NULL, out, NULL)) {
log_error_write(srv, __FILE__, __LINE__, "sbss",
"opening", source, "failed:", strerror(errno));
ret = -1;
} else {
tokenizer_init(&t, source, out->ptr, out->used);
ret = config_parse(srv, context, &t);
}
buffer_free(source);
buffer_free(out);
chdir(oldpwd);
free(oldpwd);
return ret;
}
static void context_init(server *srv, config_t *context) {
context->srv = srv;
context->ok = 1;
context->configs_stack = array_init();
context->configs_stack->is_weakref = 1;
context->basedir = buffer_init();
}
static void context_free(config_t *context) {
array_free(context->configs_stack);
buffer_free(context->basedir);
}
int config_read(server *srv, const char *fn) {
config_t context;
data_config *dc;
data_integer *dpid;
data_string *dcwd;
int ret;
char *pos;
data_array *modules;
context_init(srv, &context);
context.all_configs = srv->config_context;
#ifdef __WIN32
pos = strrchr(fn, '\\');
#else
pos = strrchr(fn, '/');
#endif
if (pos) {
buffer_copy_string_len(context.basedir, fn, pos - fn + 1);
fn = pos + 1;
}
dc = data_config_init();
buffer_copy_string_len(dc->key, CONST_STR_LEN("global"));
assert(context.all_configs->used == 0);
dc->context_ndx = context.all_configs->used;
array_insert_unique(context.all_configs, (data_unset *)dc);
context.current = dc;
/* default context */
srv->config = dc->value;
dpid = data_integer_init();
dpid->value = getpid();
buffer_copy_string_len(dpid->key, CONST_STR_LEN("var.PID"));
array_insert_unique(srv->config, (data_unset *)dpid);
dcwd = data_string_init();
buffer_prepare_copy(dcwd->value, 1024);
if (NULL != getcwd(dcwd->value->ptr, dcwd->value->size - 1)) {
dcwd->value->used = strlen(dcwd->value->ptr) + 1;
buffer_copy_string_len(dcwd->key, CONST_STR_LEN("var.CWD"));
array_insert_unique(srv->config, (data_unset *)dcwd);
}
ret = config_parse_file(srv, &context, fn);
/* remains nothing if parser is ok */
assert(!(0 == ret && context.ok && 0 != context.configs_stack->used));
context_free(&context);
if (0 != ret) {
return ret;
}
if (NULL != (dc = (data_config *)array_get_element(srv->config_context, "global"))) {
srv->config = dc->value;
} else {
return -1;
}
if (NULL != (modules = (data_array *)array_get_element(srv->config, "server.modules"))) {
data_string *ds;
data_array *prepends;
if (modules->type != TYPE_ARRAY) {
fprintf(stderr, "server.modules must be an array");
return -1;
}
prepends = data_array_init();
/* prepend default modules */
if (NULL == array_get_element(modules->value, "mod_indexfile")) {
ds = data_string_init();
buffer_copy_string_len(ds->value, CONST_STR_LEN("mod_indexfile"));
array_insert_unique(prepends->value, (data_unset *)ds);
}
prepends = (data_array *)configparser_merge_data((data_unset *)prepends, (data_unset *)modules);
buffer_copy_string_buffer(prepends->key, modules->key);
array_replace(srv->config, (data_unset *)prepends);
modules->free((data_unset *)modules);
modules = prepends;
/* append default modules */
if (NULL == array_get_element(modules->value, "mod_dirlisting")) {
ds = data_string_init();
buffer_copy_string_len(ds->value, CONST_STR_LEN("mod_dirlisting"));
array_insert_unique(modules->value, (data_unset *)ds);
}
if (NULL == array_get_element(modules->value, "mod_staticfile")) {
ds = data_string_init();
buffer_copy_string_len(ds->value, CONST_STR_LEN("mod_staticfile"));
array_insert_unique(modules->value, (data_unset *)ds);
}
} else {
data_string *ds;
modules = data_array_init();
/* server.modules is not set */
ds = data_string_init();
buffer_copy_string_len(ds->value, CONST_STR_LEN("mod_indexfile"));
array_insert_unique(modules->value, (data_unset *)ds);
ds = data_string_init();
buffer_copy_string_len(ds->value, CONST_STR_LEN("mod_dirlisting"));
array_insert_unique(modules->value, (data_unset *)ds);
ds = data_string_init();
buffer_copy_string_len(ds->value, CONST_STR_LEN("mod_staticfile"));
array_insert_unique(modules->value, (data_unset *)ds);
buffer_copy_string_len(modules->key, CONST_STR_LEN("server.modules"));
array_insert_unique(srv->config, (data_unset *)modules);
}
if (0 != config_insert(srv)) {
return -1;
}
return 0;
}
int config_set_defaults(server *srv) {
size_t i;
specific_config *s = srv->config_storage[0];
struct stat st1, st2;
struct ev_map { fdevent_handler_t et; const char *name; } event_handlers[] =
{
/* - poll is most reliable
* - select works everywhere
* - linux-* are experimental
*/
#ifdef USE_LINUX_EPOLL
{ FDEVENT_HANDLER_LINUX_SYSEPOLL, "linux-sysepoll" },
#endif
#ifdef USE_POLL
{ FDEVENT_HANDLER_POLL, "poll" },
#endif
#ifdef USE_SELECT
{ FDEVENT_HANDLER_SELECT, "select" },
#endif
#ifdef USE_LINUX_SIGIO
{ FDEVENT_HANDLER_LINUX_RTSIG, "linux-rtsig" },
#endif
#ifdef USE_SOLARIS_DEVPOLL
{ FDEVENT_HANDLER_SOLARIS_DEVPOLL,"solaris-devpoll" },
#endif
#ifdef USE_FREEBSD_KQUEUE
{ FDEVENT_HANDLER_FREEBSD_KQUEUE, "freebsd-kqueue" },
{ FDEVENT_HANDLER_FREEBSD_KQUEUE, "kqueue" },
#endif
{ FDEVENT_HANDLER_UNSET, NULL }
};
if (buffer_is_empty(s->document_root)) {
log_error_write(srv, __FILE__, __LINE__, "s",
"a default document-root has to be set");
return -1;
}
if (buffer_is_empty(srv->srvconf.changeroot)) {
if (-1 == stat(s->document_root->ptr, &st1)) {
log_error_write(srv, __FILE__, __LINE__, "sb",
"base-docroot doesn't exist:",
s->document_root);
return -1;
}
} else {
buffer_copy_string_buffer(srv->tmp_buf, srv->srvconf.changeroot);
buffer_append_string_buffer(srv->tmp_buf, s->document_root);
if (-1 == stat(srv->tmp_buf->ptr, &st1)) {
log_error_write(srv, __FILE__, __LINE__, "sb",
"base-docroot doesn't exist:",
srv->tmp_buf);
return -1;
}
}
buffer_copy_string_buffer(srv->tmp_buf, s->document_root);
buffer_to_lower(srv->tmp_buf);
if (0 == stat(srv->tmp_buf->ptr, &st1)) {
int is_lower = 0;
is_lower = buffer_is_equal(srv->tmp_buf, s->document_root);
/* lower-case existed, check upper-case */
buffer_copy_string_buffer(srv->tmp_buf, s->document_root);
buffer_to_upper(srv->tmp_buf);
/* we have to handle the special case that upper and lower-casing results in the same filename
* as in server.document-root = "/" or "/12345/" */
if (is_lower && buffer_is_equal(srv->tmp_buf, s->document_root)) {
/* lower-casing and upper-casing didn't result in
* an other filename, no need to stat(),
* just assume it is case-sensitive. */
s->force_lowercase_filenames = 0;
} else if (0 == stat(srv->tmp_buf->ptr, &st2)) {
/* upper case exists too, doesn't the FS handle this ? */
/* upper and lower have the same inode -> case-insensitve FS */
if (st1.st_ino == st2.st_ino) {
/* upper and lower have the same inode -> case-insensitve FS */
s->force_lowercase_filenames = 1;
}
}
}
if (srv->srvconf.port == 0) {
srv->srvconf.port = s->is_ssl ? 443 : 80;
}
if (srv->srvconf.event_handler->used == 0) {
/* choose a good default
*
* the event_handler list is sorted by 'goodness'
* taking the first available should be the best solution
*/
srv->event_handler = event_handlers[0].et;
if (FDEVENT_HANDLER_UNSET == srv->event_handler) {
log_error_write(srv, __FILE__, __LINE__, "s",
"sorry, there is no event handler for this system");
return -1;
}
} else {
/*
* User override
*/
for (i = 0; event_handlers[i].name; i++) {
if (0 == strcmp(event_handlers[i].name, srv->srvconf.event_handler->ptr)) {
srv->event_handler = event_handlers[i].et;
break;
}
}
if (FDEVENT_HANDLER_UNSET == srv->event_handler) {
log_error_write(srv, __FILE__, __LINE__, "sb",
"the selected event-handler in unknown or not supported:",
srv->srvconf.event_handler );
return -1;
}
}
if (s->is_ssl) {
if (buffer_is_empty(s->ssl_pemfile)) {
/* PEM file is require */
log_error_write(srv, __FILE__, __LINE__, "s",
"ssl.pemfile has to be set");
return -1;
}
#ifndef USE_OPENSSL
log_error_write(srv, __FILE__, __LINE__, "s",
"ssl support is missing, recompile with --with-openssl");
return -1;
#endif
}
return 0;
}
|
Elbandi/lighttpd
|
src/network_linux_sendfile.c
|
#include "network_backends.h"
#ifdef USE_LINUX_SENDFILE
#include "network.h"
#include "fdevent.h"
#include "log.h"
#include "stat_cache.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
/* on linux 2.4.29 + debian/ubuntu we have crashes if this is enabled */
#undef HAVE_POSIX_FADVISE
int network_write_chunkqueue_linuxsendfile(server *srv, connection *con, int fd, chunkqueue *cq) {
chunk *c;
size_t chunks_written = 0;
for(c = cq->first; c; c = c->next, chunks_written++) {
int chunk_finished = 0;
switch(c->type) {
case MEM_CHUNK: {
char * offset;
size_t toSend;
ssize_t r;
size_t num_chunks, i;
struct iovec chunks[UIO_MAXIOV];
chunk *tc;
size_t num_bytes = 0;
/* we can't send more then SSIZE_MAX bytes in one chunk */
/* build writev list
*
* 1. limit: num_chunks < UIO_MAXIOV
* 2. limit: num_bytes < SSIZE_MAX
*/
for (num_chunks = 0, tc = c;
tc && tc->type == MEM_CHUNK && num_chunks < UIO_MAXIOV;
tc = tc->next, num_chunks++);
for (tc = c, i = 0; i < num_chunks; tc = tc->next, i++) {
if (tc->mem->used == 0) {
chunks[i].iov_base = tc->mem->ptr;
chunks[i].iov_len = 0;
} else {
offset = tc->mem->ptr + tc->offset;
toSend = tc->mem->used - 1 - tc->offset;
chunks[i].iov_base = offset;
/* protect the return value of writev() */
if (toSend > SSIZE_MAX ||
num_bytes + toSend > SSIZE_MAX) {
chunks[i].iov_len = SSIZE_MAX - num_bytes;
num_chunks = i + 1;
break;
} else {
chunks[i].iov_len = toSend;
}
num_bytes += toSend;
}
}
if ((r = writev(fd, chunks, num_chunks)) < 0) {
switch (errno) {
case EAGAIN:
case EINTR:
r = 0;
break;
case EPIPE:
case ECONNRESET:
return -2;
default:
log_error_write(srv, __FILE__, __LINE__, "ssd",
"writev failed:", strerror(errno), fd);
return -1;
}
}
/* check which chunks have been written */
cq->bytes_out += r;
for(i = 0, tc = c; i < num_chunks; i++, tc = tc->next) {
if (r >= (ssize_t)chunks[i].iov_len) {
/* written */
r -= chunks[i].iov_len;
tc->offset += chunks[i].iov_len;
if (chunk_finished) {
/* skip the chunks from further touches */
chunks_written++;
c = c->next;
} else {
/* chunks_written + c = c->next is done in the for()*/
chunk_finished++;
}
} else {
/* partially written */
tc->offset += r;
chunk_finished = 0;
break;
}
}
break;
}
case FILE_CHUNK: {
ssize_t r;
off_t offset;
size_t toSend;
stat_cache_entry *sce = NULL;
offset = c->file.start + c->offset;
/* limit the toSend to 2^31-1 bytes in a chunk */
toSend = c->file.length - c->offset > ((1 << 30) - 1) ?
((1 << 30) - 1) : c->file.length - c->offset;
/* open file if not already opened */
if (-1 == c->file.fd) {
if (-1 == (c->file.fd = open(c->file.name->ptr, O_RDONLY | (srv->srvconf.use_noatime ? O_NOATIME : 0)))) {
log_error_write(srv, __FILE__, __LINE__, "ss", "open failed: ", strerror(errno));
return -1;
}
#ifdef FD_CLOEXEC
fcntl(c->file.fd, F_SETFD, FD_CLOEXEC);
#endif
#ifdef HAVE_POSIX_FADVISE
/* tell the kernel that we want to stream the file */
if (-1 == posix_fadvise(c->file.fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
if (ENOSYS != errno) {
log_error_write(srv, __FILE__, __LINE__, "ssd",
"posix_fadvise failed:", strerror(errno), c->file.fd);
}
}
#endif
}
if (-1 == (r = sendfile(fd, c->file.fd, &offset, toSend))) {
switch (errno) {
case EAGAIN:
case EINTR:
/* ok, we can't send more, let's try later again */
r = 0;
break;
case EPIPE:
case ECONNRESET:
return -2;
default:
log_error_write(srv, __FILE__, __LINE__, "ssd",
"sendfile failed:", strerror(errno), fd);
return -1;
}
} else if (r == 0) {
int oerrno = errno;
/* We got an event to write but we wrote nothing
*
* - the file shrinked -> error
* - the remote side closed inbetween -> remote-close */
if (HANDLER_ERROR == stat_cache_get_entry(srv, con, c->file.name, &sce)) {
/* file is gone ? */
return -1;
}
if (offset > sce->st.st_size) {
/* file shrinked, close the connection */
errno = oerrno;
return -1;
}
errno = oerrno;
return -2;
}
#ifdef HAVE_POSIX_FADVISE
#if 0
#define K * 1024
#define M * 1024 K
#define READ_AHEAD 4 M
/* check if we need a new chunk */
if ((c->offset & ~(READ_AHEAD - 1)) != ((c->offset + r) & ~(READ_AHEAD - 1))) {
/* tell the kernel that we want to stream the file */
if (-1 == posix_fadvise(c->file.fd, (c->offset + r) & ~(READ_AHEAD - 1), READ_AHEAD, POSIX_FADV_NOREUSE)) {
log_error_write(srv, __FILE__, __LINE__, "ssd",
"posix_fadvise failed:", strerror(errno), c->file.fd);
}
}
#endif
#endif
c->offset += r;
cq->bytes_out += r;
if (c->offset == c->file.length) {
chunk_finished = 1;
/* chunk_free() / chunk_reset() will cleanup for us but it is a ok to be faster :) */
if (c->file.fd != -1) {
close(c->file.fd);
c->file.fd = -1;
}
}
break;
}
default:
log_error_write(srv, __FILE__, __LINE__, "ds", c, "type not known");
return -1;
}
if (!chunk_finished) {
/* not finished yet */
break;
}
}
return chunks_written;
}
#endif
#if 0
network_linuxsendfile_init(void) {
p->write = network_linuxsendfile_write_chunkset;
}
#endif
|
Elbandi/lighttpd
|
src/version.h
|
#ifndef _VERSION_H_
#define _VERSION_H_
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* check lighttpd version */
#if LIGHTTPD_VERSION_ID < 0x10500
#define LIGHTTPD_V14 1
#else
#define LIGHTTPD_V15 1
#endif
#ifdef HAVE_VERSION_H
# include "versionstamp.h"
#else
# define REPO_VERSION ""
#endif
#define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
#endif
|
Elbandi/lighttpd
|
src/chunk.c
|
/**
* the network chunk-API
*
*
*/
#include "chunk.h"
#include "server.h"
#include "log.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
chunkqueue *chunkqueue_init(void) {
chunkqueue *cq;
cq = calloc(1, sizeof(*cq));
cq->first = NULL;
cq->last = NULL;
cq->unused = NULL;
return cq;
}
static chunk *chunk_init(void) {
chunk *c;
c = calloc(1, sizeof(*c));
c->mem = buffer_init();
c->file.name = buffer_init();
c->file.fd = -1;
c->file.mmap.start = MAP_FAILED;
c->next = NULL;
return c;
}
static void chunk_free(chunk *c) {
if (!c) return;
buffer_free(c->mem);
buffer_free(c->file.name);
if (c->file.fd > 0) close(c->file.fd);
free(c);
}
void chunkqueue_free(chunkqueue *cq) {
chunk *c, *pc;
if (!cq) return;
for (c = cq->first; c; ) {
pc = c;
c = c->next;
chunk_free(pc);
}
for (c = cq->unused; c; ) {
pc = c;
c = c->next;
chunk_free(pc);
}
free(cq);
}
static chunk *chunkqueue_get_unused_chunk(chunkqueue *cq) {
chunk *c;
/* check if we have a unused chunk */
if (!cq->unused) {
c = chunk_init();
} else {
/* take the first element from the list (a stack) */
c = cq->unused;
cq->unused = c->next;
c->next = NULL;
cq->unused_chunks--;
}
return c;
}
static int chunkqueue_prepend_chunk(chunkqueue *cq, chunk *c) {
c->next = cq->first;
cq->first = c;
if (cq->last == NULL) {
cq->last = c;
}
return 0;
}
static int chunkqueue_append_chunk(chunkqueue *cq, chunk *c) {
if (cq->last) {
cq->last->next = c;
}
cq->last = c;
if (cq->first == NULL) {
cq->first = c;
}
return 0;
}
void chunkqueue_reset(chunkqueue *cq) {
chunk *c;
/* mark all read written */
for (c = cq->first; c; c = c->next) {
switch(c->type) {
case MEM_CHUNK:
c->offset = c->mem->used - 1;
break;
case FILE_CHUNK:
c->offset = c->file.length;
break;
default:
break;
}
}
chunkqueue_remove_finished_chunks(cq);
cq->bytes_in = 0;
cq->bytes_out = 0;
}
int chunkqueue_append_file(chunkqueue *cq, buffer *fn, off_t offset, off_t len) {
chunk *c;
if (len == 0) return 0;
c = chunkqueue_get_unused_chunk(cq);
c->type = FILE_CHUNK;
buffer_copy_string_buffer(c->file.name, fn);
c->file.start = offset;
c->file.length = len;
c->offset = 0;
chunkqueue_append_chunk(cq, c);
return 0;
}
int chunkqueue_append_shared_buffer(chunkqueue *cq, buffer *mem) {
chunk *c;
if (mem->used == 0) return 0;
c = chunkqueue_get_unused_chunk(cq);
c->type = MEM_CHUNK;
c->offset = 0;
buffer_free(c->mem); // free just allocated buffer
c->mem = mem; // use shared buffer
mem->ref_count ++;
chunkqueue_append_chunk(cq, c);
return 0;
}
int chunkqueue_append_buffer(chunkqueue *cq, buffer *mem) {
chunk *c;
if (mem->used == 0) return 0;
c = chunkqueue_get_unused_chunk(cq);
c->type = MEM_CHUNK;
c->offset = 0;
buffer_copy_string_buffer(c->mem, mem);
chunkqueue_append_chunk(cq, c);
return 0;
}
int chunkqueue_append_buffer_weak(chunkqueue *cq, buffer *mem) {
chunk *c;
c = chunkqueue_get_unused_chunk(cq);
c->type = MEM_CHUNK;
c->offset = 0;
if (c->mem) buffer_free(c->mem);
c->mem = mem;
chunkqueue_append_chunk(cq, c);
return 0;
}
int chunkqueue_prepend_buffer(chunkqueue *cq, buffer *mem) {
chunk *c;
if (mem->used == 0) return 0;
c = chunkqueue_get_unused_chunk(cq);
c->type = MEM_CHUNK;
c->offset = 0;
buffer_copy_string_buffer(c->mem, mem);
chunkqueue_prepend_chunk(cq, c);
return 0;
}
int chunkqueue_append_mem(chunkqueue *cq, const char * mem, size_t len) {
chunk *c;
if (len == 0) return 0;
c = chunkqueue_get_unused_chunk(cq);
c->type = MEM_CHUNK;
c->offset = 0;
buffer_copy_string_len(c->mem, mem, len - 1);
chunkqueue_append_chunk(cq, c);
return 0;
}
int chunkqueue_append_chunkqueue(chunkqueue *cq, chunkqueue *src) {
if(src == NULL) return 0;
chunkqueue_append_chunk(cq, src->first);
cq->last = src->last;
src->first = NULL;
src->last = NULL;
return 0;
}
buffer * chunkqueue_get_prepend_buffer(chunkqueue *cq) {
chunk *c;
c = chunkqueue_get_unused_chunk(cq);
c->type = MEM_CHUNK;
c->offset = 0;
buffer_reset(c->mem);
chunkqueue_prepend_chunk(cq, c);
return c->mem;
}
buffer *chunkqueue_get_append_buffer(chunkqueue *cq) {
chunk *c;
c = chunkqueue_get_unused_chunk(cq);
c->type = MEM_CHUNK;
c->offset = 0;
buffer_reset(c->mem);
chunkqueue_append_chunk(cq, c);
return c->mem;
}
int chunkqueue_set_tempdirs(chunkqueue *cq, array *tempdirs) {
if (!cq) return -1;
cq->tempdirs = tempdirs;
return 0;
}
chunk *chunkqueue_get_append_tempfile(chunkqueue *cq) {
chunk *c;
buffer *template = buffer_init_string("/var/tmp/lighttpd-upload-XXXXXX");
c = chunkqueue_get_unused_chunk(cq);
c->type = FILE_CHUNK;
c->offset = 0;
if (cq->tempdirs && cq->tempdirs->used) {
size_t i;
/* we have several tempdirs, only if all of them fail we jump out */
for (i = 0; i < cq->tempdirs->used; i++) {
data_string *ds = (data_string *)cq->tempdirs->data[i];
buffer_copy_string_buffer(template, ds->value);
BUFFER_APPEND_SLASH(template);
buffer_append_string_len(template, CONST_STR_LEN("lighttpd-upload-XXXXXX"));
if (-1 != (c->file.fd = mkstemp(template->ptr))) {
/* only trigger the unlink if we created the temp-file successfully */
c->file.is_temp = 1;
break;
}
}
} else {
if (-1 != (c->file.fd = mkstemp(template->ptr))) {
/* only trigger the unlink if we created the temp-file successfully */
c->file.is_temp = 1;
}
}
buffer_copy_string_buffer(c->file.name, template);
c->file.length = 0;
chunkqueue_append_chunk(cq, c);
buffer_free(template);
return c;
}
off_t chunkqueue_length(chunkqueue *cq) {
off_t len = 0;
chunk *c;
for (c = cq->first; c; c = c->next) {
switch (c->type) {
case MEM_CHUNK:
len += c->mem->used ? c->mem->used - 1 : 0;
break;
case FILE_CHUNK:
len += c->file.length;
break;
default:
break;
}
}
return len;
}
off_t chunkqueue_written(chunkqueue *cq) {
off_t len = 0;
chunk *c;
for (c = cq->first; c; c = c->next) {
switch (c->type) {
case MEM_CHUNK:
case FILE_CHUNK:
len += c->offset;
break;
default:
break;
}
}
return len;
}
int chunkqueue_is_empty(chunkqueue *cq) {
return cq->first ? 0 : 1;
}
int chunkqueue_remove_finished_chunks(chunkqueue *cq) {
chunk *c;
for (c = cq->first; c; c = cq->first) {
int is_finished = 0;
switch (c->type) {
case MEM_CHUNK:
if (c->mem->used == 0 || (c->offset == (off_t)c->mem->used - 1)) is_finished = 1;
break;
case FILE_CHUNK:
if (c->offset == c->file.length) is_finished = 1;
break;
default:
break;
}
if (!is_finished) break;
cq->first = c->next;
if (c == cq->last) cq->last = NULL;
#if 0
/* keep at max 4 chunks in the 'unused'-cache */
if (cq->unused_chunks > 1) {
chunk_free(c);
} else {
c->next = cq->unused;
cq->unused = c;
cq->unused_chunks++;
}
#else
chunk_free(c);
#endif
}
return 0;
}
static int chunk_encode_append_len(chunkqueue *cq, size_t len) {
size_t i, olen = len, j;
buffer *b;
/*b = srv->tmp_chunk_len;*/
/*b = buffer_init();*/
b = chunkqueue_get_append_buffer(cq);
if (len == 0) {
buffer_copy_string_len(b, CONST_STR_LEN("0"));
} else {
for (i = 0; i < 8 && len; i++) {
len >>= 4;
}
/* i is the number of hex digits we have */
buffer_prepare_copy(b, i + 1);
for (j = i-1, len = olen; j+1 > 0; j--) {
b->ptr[j] = (len & 0xf) + (((len & 0xf) <= 9) ? '0' : 'a' - 10);
len >>= 4;
}
b->used = i;
b->ptr[b->used++] = '\0';
}
buffer_append_string_len(b, CONST_STR_LEN("\r\n"));
/*
chunkqueue_append_buffer(cq, b);
buffer_free(b);
*/
return 0;
}
int chunk_encode_append_file(chunkqueue *cq, buffer *fn, off_t offset, off_t len) {
if (!cq) return -1;
if (len == 0) return 0;
chunk_encode_append_len(cq, len);
chunkqueue_append_file(cq, fn, offset, len);
chunkqueue_append_mem(cq, "\r\n", 2 + 1);
return 0;
}
int chunk_encode_append_buffer(chunkqueue *cq, buffer *mem) {
if (!cq) return -1;
if (mem->used <= 1) return 0;
chunk_encode_append_len(cq, mem->used - 1);
chunkqueue_append_buffer(cq, mem);
chunkqueue_append_mem(cq, "\r\n", 2 + 1);
return 0;
}
int chunk_encode_append_mem(chunkqueue *cq, const char * mem, size_t len) {
if (!cq) return -1;
if (len <= 1) return 0;
chunk_encode_append_len(cq, len - 1);
chunkqueue_append_mem(cq, mem, len);
chunkqueue_append_mem(cq, "\r\n", 2 + 1);
return 0;
}
int chunk_encode_append_queue(chunkqueue *cq, chunkqueue *src) {
int len = chunkqueue_length(src);
if (!cq) return -1;
if (len == 0) return 0;
chunk_encode_append_len(cq, len);
chunkqueue_append_chunkqueue(cq, src);
chunkqueue_append_mem(cq, "\r\n", 2 + 1);
return 0;
}
int chunk_encode_end(chunkqueue *cq) {
chunk_encode_append_len(cq, 0);
chunkqueue_append_mem(cq, "\r\n", 2 + 1);
return 0;
}
|
Elbandi/lighttpd
|
src/mod_ssi_expr.c
|
#include "buffer.h"
#include "log.h"
#include "mod_ssi.h"
#include "mod_ssi_expr.h"
#include "mod_ssi_exprparser.h"
#include <ctype.h>
#include <string.h>
typedef struct {
const char *input;
size_t offset;
size_t size;
int line_pos;
int in_key;
int in_brace;
int in_cond;
} ssi_tokenizer_t;
ssi_val_t *ssi_val_init() {
ssi_val_t *s;
s = calloc(1, sizeof(*s));
return s;
}
void ssi_val_free(ssi_val_t *s) {
if (s->str) buffer_free(s->str);
free(s);
}
int ssi_val_tobool(ssi_val_t *B) {
if (B->type == SSI_TYPE_STRING) {
return B->str->used > 1 ? 1 : 0;
} else {
return B->bo;
}
}
static int ssi_expr_tokenizer(server *srv, connection *con, plugin_data *p,
ssi_tokenizer_t *t, int *token_id, buffer *token) {
int tid = 0;
size_t i;
UNUSED(con);
for (tid = 0; tid == 0 && t->offset < t->size && t->input[t->offset] ; ) {
char c = t->input[t->offset];
data_string *ds;
switch (c) {
case '=':
tid = TK_EQ;
t->offset++;
t->line_pos++;
buffer_copy_string_len(token, CONST_STR_LEN("(=)"));
break;
case '>':
if (t->input[t->offset + 1] == '=') {
t->offset += 2;
t->line_pos += 2;
tid = TK_GE;
buffer_copy_string_len(token, CONST_STR_LEN("(>=)"));
} else {
t->offset += 1;
t->line_pos += 1;
tid = TK_GT;
buffer_copy_string_len(token, CONST_STR_LEN("(>)"));
}
break;
case '<':
if (t->input[t->offset + 1] == '=') {
t->offset += 2;
t->line_pos += 2;
tid = TK_LE;
buffer_copy_string_len(token, CONST_STR_LEN("(<=)"));
} else {
t->offset += 1;
t->line_pos += 1;
tid = TK_LT;
buffer_copy_string_len(token, CONST_STR_LEN("(<)"));
}
break;
case '!':
if (t->input[t->offset + 1] == '=') {
t->offset += 2;
t->line_pos += 2;
tid = TK_NE;
buffer_copy_string_len(token, CONST_STR_LEN("(!=)"));
} else {
t->offset += 1;
t->line_pos += 1;
tid = TK_NOT;
buffer_copy_string_len(token, CONST_STR_LEN("(!)"));
}
break;
case '&':
if (t->input[t->offset + 1] == '&') {
t->offset += 2;
t->line_pos += 2;
tid = TK_AND;
buffer_copy_string_len(token, CONST_STR_LEN("(&&)"));
} else {
log_error_write(srv, __FILE__, __LINE__, "sds",
"pos:", t->line_pos,
"missing second &");
return -1;
}
break;
case '|':
if (t->input[t->offset + 1] == '|') {
t->offset += 2;
t->line_pos += 2;
tid = TK_OR;
buffer_copy_string_len(token, CONST_STR_LEN("(||)"));
} else {
log_error_write(srv, __FILE__, __LINE__, "sds",
"pos:", t->line_pos,
"missing second |");
return -1;
}
break;
case '\t':
case ' ':
t->offset++;
t->line_pos++;
break;
case '\'':
/* search for the terminating " */
for (i = 1; t->input[t->offset + i] && t->input[t->offset + i] != '\''; i++);
if (t->input[t->offset + i]) {
tid = TK_VALUE;
buffer_copy_string_len(token, t->input + t->offset + 1, i-1);
t->offset += i + 1;
t->line_pos += i + 1;
} else {
/* ERROR */
log_error_write(srv, __FILE__, __LINE__, "sds",
"pos:", t->line_pos,
"missing closing quote");
return -1;
}
break;
case '(':
t->offset++;
t->in_brace++;
tid = TK_LPARAN;
buffer_copy_string_len(token, CONST_STR_LEN("("));
break;
case ')':
t->offset++;
t->in_brace--;
tid = TK_RPARAN;
buffer_copy_string_len(token, CONST_STR_LEN(")"));
break;
case '$':
if (t->input[t->offset + 1] == '{') {
for (i = 2; t->input[t->offset + i] && t->input[t->offset + i] != '}'; i++);
if (t->input[t->offset + i] != '}') {
log_error_write(srv, __FILE__, __LINE__, "sds",
"pos:", t->line_pos,
"missing closing quote");
return -1;
}
buffer_copy_string_len(token, t->input + t->offset + 2, i-3);
} else {
for (i = 1; isalpha(t->input[t->offset + i]) || t->input[t->offset + i] == '_'; i++);
buffer_copy_string_len(token, t->input + t->offset + 1, i-1);
}
tid = TK_VALUE;
if (NULL != (ds = (data_string *)array_get_element(p->ssi_cgi_env, token->ptr))) {
buffer_copy_string_buffer(token, ds->value);
} else if (NULL != (ds = (data_string *)array_get_element(p->ssi_vars, token->ptr))) {
buffer_copy_string_buffer(token, ds->value);
} else {
buffer_copy_string_len(token, CONST_STR_LEN(""));
}
t->offset += i;
t->line_pos += i;
break;
default:
for (i = 0; isgraph(t->input[t->offset + i]); i++) {
char d = t->input[t->offset + i];
switch(d) {
case ' ':
case '\t':
case ')':
case '(':
case '\'':
case '=':
case '!':
case '<':
case '>':
case '&':
case '|':
break;
}
}
tid = TK_VALUE;
buffer_copy_string_len(token, t->input + t->offset, i);
t->offset += i;
t->line_pos += i;
break;
}
}
if (tid) {
*token_id = tid;
return 1;
} else if (t->offset < t->size) {
log_error_write(srv, __FILE__, __LINE__, "sds",
"pos:", t->line_pos,
"foobar");
}
return 0;
}
int ssi_eval_expr(server *srv, connection *con, plugin_data *p, const char *expr) {
ssi_tokenizer_t t;
void *pParser;
int token_id;
buffer *token;
ssi_ctx_t context;
int ret;
t.input = expr;
t.offset = 0;
t.size = strlen(expr);
t.line_pos = 1;
t.in_key = 1;
t.in_brace = 0;
t.in_cond = 0;
context.ok = 1;
context.srv = srv;
/* default context */
pParser = ssiexprparserAlloc( malloc );
token = buffer_init();
while((1 == (ret = ssi_expr_tokenizer(srv, con, p, &t, &token_id, token))) && context.ok) {
ssiexprparser(pParser, token_id, token, &context);
token = buffer_init();
}
ssiexprparser(pParser, 0, token, &context);
ssiexprparserFree(pParser, free );
buffer_free(token);
if (ret == -1) {
log_error_write(srv, __FILE__, __LINE__, "s",
"expr parser failed");
return -1;
}
if (context.ok == 0) {
log_error_write(srv, __FILE__, __LINE__, "sds",
"pos:", t.line_pos,
"parser failed somehow near here");
return -1;
}
#if 0
log_error_write(srv, __FILE__, __LINE__, "ssd",
"expr: ",
expr,
context.val.bo);
#endif
return context.val.bo;
}
|
Elbandi/lighttpd
|
src/network_backends.h
|
#ifndef _NETWORK_BACKENDS_H_
#define _NETWORK_BACKENDS_H_
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "settings.h"
#include <sys/types.h>
/* on linux 2.4.x you get either sendfile or LFS */
#if defined HAVE_SYS_SENDFILE_H && defined HAVE_SENDFILE && (!defined _LARGEFILE_SOURCE || defined HAVE_SENDFILE64) && defined HAVE_WRITEV && defined(__linux__) && !defined HAVE_SENDFILE_BROKEN
# define USE_LINUX_SENDFILE
# include <sys/sendfile.h>
# include <sys/uio.h>
#endif
#if defined HAVE_SYS_UIO_H && defined HAVE_SENDFILE && defined HAVE_WRITEV && (defined(__FreeBSD__) || defined(__DragonFly__))
# define USE_FREEBSD_SENDFILE
# include <sys/uio.h>
#endif
#if defined HAVE_SYS_SENDFILE_H && defined HAVE_SENDFILEV && defined HAVE_WRITEV && defined(__sun)
# define USE_SOLARIS_SENDFILEV
# include <sys/sendfile.h>
# include <sys/uio.h>
#endif
#if defined HAVE_SYS_UIO_H && defined HAVE_WRITEV
# define USE_WRITEV
# include <sys/uio.h>
#endif
#if defined HAVE_SYS_MMAN_H && defined HAVE_MMAP
# define USE_MMAP
# include <sys/mman.h>
/* NetBSD 1.3.x needs it */
# ifndef MAP_FAILED
# define MAP_FAILED -1
# endif
#endif
#if defined HAVE_SYS_UIO_H && defined HAVE_WRITEV && defined HAVE_SEND_FILE && defined(__aix)
# define USE_AIX_SENDFILE
#endif
#include "base.h"
/* return values:
* >= 0 : chunks completed
* -1 : error (on our side)
* -2 : remote close
*/
int network_write_chunkqueue_write(server *srv, connection *con, int fd, chunkqueue *cq);
int network_write_chunkqueue_writev(server *srv, connection *con, int fd, chunkqueue *cq);
int network_write_chunkqueue_linuxsendfile(server *srv, connection *con, int fd, chunkqueue *cq);
int network_write_chunkqueue_freebsdsendfile(server *srv, connection *con, int fd, chunkqueue *cq);
int network_write_chunkqueue_solarissendfilev(server *srv, connection *con, int fd, chunkqueue *cq);
#ifdef USE_OPENSSL
int network_write_chunkqueue_openssl(server *srv, connection *con, SSL *ssl, chunkqueue *cq);
#endif
#endif
|
Elbandi/lighttpd
|
src/mod_staticfile.c
|
<filename>src/mod_staticfile.c<gh_stars>0
#include "base.h"
#include "log.h"
#include "buffer.h"
#include "plugin.h"
#include "stat_cache.h"
#include "etag.h"
#include "http_chunk.h"
#include "response.h"
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/**
* this is a staticfile for a lighttpd plugin
*
*/
/* plugin config for all request/connections */
typedef struct {
array *exclude_ext;
unsigned short etags_used;
} plugin_config;
typedef struct {
PLUGIN_DATA;
buffer *range_buf;
plugin_config **config_storage;
plugin_config conf;
} plugin_data;
/* init the plugin data */
INIT_FUNC(mod_staticfile_init) {
plugin_data *p;
p = calloc(1, sizeof(*p));
p->range_buf = buffer_init();
return p;
}
/* detroy the plugin data */
FREE_FUNC(mod_staticfile_free) {
plugin_data *p = p_d;
UNUSED(srv);
if (!p) return HANDLER_GO_ON;
if (p->config_storage) {
size_t i;
for (i = 0; i < srv->config_context->used; i++) {
plugin_config *s = p->config_storage[i];
array_free(s->exclude_ext);
free(s);
}
free(p->config_storage);
}
buffer_free(p->range_buf);
free(p);
return HANDLER_GO_ON;
}
/* handle plugin config and check values */
SETDEFAULTS_FUNC(mod_staticfile_set_defaults) {
plugin_data *p = p_d;
size_t i = 0;
config_values_t cv[] = {
{ "static-file.exclude-extensions", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
{ "static-file.etags", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
{ NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
};
if (!p) return HANDLER_ERROR;
p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *));
for (i = 0; i < srv->config_context->used; i++) {
plugin_config *s;
s = calloc(1, sizeof(plugin_config));
s->exclude_ext = array_init();
s->etags_used = 1;
cv[0].destination = s->exclude_ext;
cv[1].destination = &(s->etags_used);
p->config_storage[i] = s;
if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) {
return HANDLER_ERROR;
}
}
return HANDLER_GO_ON;
}
#define PATCH(x) \
p->conf.x = s->x;
static int mod_staticfile_patch_connection(server *srv, connection *con, plugin_data *p) {
size_t i, j;
plugin_config *s = p->config_storage[0];
PATCH(exclude_ext);
PATCH(etags_used);
/* skip the first, the global context */
for (i = 1; i < srv->config_context->used; i++) {
data_config *dc = (data_config *)srv->config_context->data[i];
s = p->config_storage[i];
/* condition didn't match */
if (!config_check_cond(srv, con, dc)) continue;
/* merge config */
for (j = 0; j < dc->value->used; j++) {
data_unset *du = dc->value->data[j];
if (buffer_is_equal_string(du->key, CONST_STR_LEN("static-file.exclude-extensions"))) {
PATCH(exclude_ext);
} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("static-file.etags"))) {
PATCH(etags_used);
}
}
}
return 0;
}
#undef PATCH
static int http_response_parse_range(server *srv, connection *con, plugin_data *p) {
int multipart = 0;
int error;
off_t start, end;
const char *s, *minus;
char *boundary = "fkj49sn38dcn3";
data_string *ds;
stat_cache_entry *sce = NULL;
buffer *content_type = NULL;
if (HANDLER_ERROR == stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
SEGFAULT();
}
start = 0;
end = sce->st.st_size - 1;
con->response.content_length = 0;
if (NULL != (ds = (data_string *)array_get_element(con->response.headers, "Content-Type"))) {
content_type = ds->value;
}
for (s = con->request.http_range, error = 0;
!error && *s && NULL != (minus = strchr(s, '-')); ) {
char *err;
off_t la, le;
if (s == minus) {
/* -<stop> */
le = strtoll(s, &err, 10);
if (le == 0) {
/* RFC 2616 - 14.35.1 */
con->http_status = 416;
error = 1;
} else if (*err == '\0') {
/* end */
s = err;
end = sce->st.st_size - 1;
start = sce->st.st_size + le;
} else if (*err == ',') {
multipart = 1;
s = err + 1;
end = sce->st.st_size - 1;
start = sce->st.st_size + le;
} else {
error = 1;
}
} else if (*(minus+1) == '\0' || *(minus+1) == ',') {
/* <start>- */
la = strtoll(s, &err, 10);
if (err == minus) {
/* ok */
if (*(err + 1) == '\0') {
s = err + 1;
end = sce->st.st_size - 1;
start = la;
} else if (*(err + 1) == ',') {
multipart = 1;
s = err + 2;
end = sce->st.st_size - 1;
start = la;
} else {
error = 1;
}
} else {
/* error */
error = 1;
}
} else {
/* <start>-<stop> */
la = strtoll(s, &err, 10);
if (err == minus) {
le = strtoll(minus+1, &err, 10);
/* RFC 2616 - 14.35.1 */
if (la > le) {
error = 1;
}
if (*err == '\0') {
/* ok, end*/
s = err;
end = le;
start = la;
} else if (*err == ',') {
multipart = 1;
s = err + 1;
end = le;
start = la;
} else {
/* error */
error = 1;
}
} else {
/* error */
error = 1;
}
}
if (!error) {
if (start < 0) start = 0;
/* RFC 2616 - 14.35.1 */
if (end > sce->st.st_size - 1) end = sce->st.st_size - 1;
if (start > sce->st.st_size - 1) {
error = 1;
con->http_status = 416;
}
}
if (!error) {
if (multipart) {
/* write boundary-header */
buffer *b;
b = chunkqueue_get_append_buffer(con->write_queue);
buffer_copy_string_len(b, CONST_STR_LEN("\r\n--"));
buffer_append_string(b, boundary);
/* write Content-Range */
buffer_append_string_len(b, CONST_STR_LEN("\r\nContent-Range: bytes "));
buffer_append_off_t(b, start);
buffer_append_string_len(b, CONST_STR_LEN("-"));
buffer_append_off_t(b, end);
buffer_append_string_len(b, CONST_STR_LEN("/"));
buffer_append_off_t(b, sce->st.st_size);
buffer_append_string_len(b, CONST_STR_LEN("\r\nContent-Type: "));
buffer_append_string_buffer(b, content_type);
/* write END-OF-HEADER */
buffer_append_string_len(b, CONST_STR_LEN("\r\n\r\n"));
con->response.content_length += b->used - 1;
}
chunkqueue_append_file(con->write_queue, con->physical.path, start, end - start + 1);
con->response.content_length += end - start + 1;
}
}
/* something went wrong */
if (error) return -1;
if (multipart) {
/* add boundary end */
buffer *b;
b = chunkqueue_get_append_buffer(con->write_queue);
buffer_copy_string_len(b, "\r\n--", 4);
buffer_append_string(b, boundary);
buffer_append_string_len(b, "--\r\n", 4);
con->response.content_length += b->used - 1;
/* set header-fields */
buffer_copy_string_len(p->range_buf, CONST_STR_LEN("multipart/byteranges; boundary="));
buffer_append_string(p->range_buf, boundary);
/* overwrite content-type */
response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(p->range_buf));
} else {
/* add Content-Range-header */
buffer_copy_string_len(p->range_buf, CONST_STR_LEN("bytes "));
buffer_append_off_t(p->range_buf, start);
buffer_append_string_len(p->range_buf, CONST_STR_LEN("-"));
buffer_append_off_t(p->range_buf, end);
buffer_append_string_len(p->range_buf, CONST_STR_LEN("/"));
buffer_append_off_t(p->range_buf, sce->st.st_size);
response_header_insert(srv, con, CONST_STR_LEN("Content-Range"), CONST_BUF_LEN(p->range_buf));
}
/* ok, the file is set-up */
return 0;
}
URIHANDLER_FUNC(mod_staticfile_subrequest) {
plugin_data *p = p_d;
size_t k;
int s_len;
stat_cache_entry *sce = NULL;
buffer *mtime = NULL;
data_string *ds;
int allow_caching = 1;
/* someone else has done a decision for us */
if (con->http_status != 0) return HANDLER_GO_ON;
if (con->uri.path->used == 0) return HANDLER_GO_ON;
if (con->physical.path->used == 0) return HANDLER_GO_ON;
/* someone else has handled this request */
if (con->mode != DIRECT) return HANDLER_GO_ON;
/* we only handle GET, POST and HEAD */
switch(con->request.http_method) {
case HTTP_METHOD_GET:
case HTTP_METHOD_POST:
case HTTP_METHOD_HEAD:
break;
default:
return HANDLER_GO_ON;
}
mod_staticfile_patch_connection(srv, con, p);
s_len = con->uri.path->used - 1;
/* ignore certain extensions */
for (k = 0; k < p->conf.exclude_ext->used; k++) {
ds = (data_string *)p->conf.exclude_ext->data[k];
if (ds->value->used == 0) continue;
if (buffer_is_equal_right_len(con->physical.path, ds->value, ds->value->used - 1)) {
return HANDLER_GO_ON;
}
}
if (con->conf.log_request_handling) {
log_error_write(srv, __FILE__, __LINE__, "s", "-- handling file as static file");
}
if (HANDLER_ERROR == stat_cache_get_entry(srv, con, con->physical.path, &sce)) {
con->http_status = 403;
log_error_write(srv, __FILE__, __LINE__, "sbsb",
"not a regular file:", con->uri.path,
"->", con->physical.path);
return HANDLER_FINISHED;
}
/* we only handline regular files */
#ifdef HAVE_LSTAT
if ((sce->is_symlink == 1) && !con->conf.follow_symlink) {
con->http_status = 403;
if (con->conf.log_request_handling) {
log_error_write(srv, __FILE__, __LINE__, "s", "-- access denied due symlink restriction");
log_error_write(srv, __FILE__, __LINE__, "sb", "Path :", con->physical.path);
}
buffer_reset(con->physical.path);
return HANDLER_FINISHED;
}
#endif
if (!S_ISREG(sce->st.st_mode)) {
con->http_status = 404;
if (con->conf.log_file_not_found) {
log_error_write(srv, __FILE__, __LINE__, "sbsb",
"not a regular file:", con->uri.path,
"->", sce->name);
}
return HANDLER_FINISHED;
}
/* mod_compress might set several data directly, don't overwrite them */
/* set response content-type, if not set already */
if (NULL == array_get_element(con->response.headers, "Content-Type")) {
if (buffer_is_empty(sce->content_type)) {
/* we are setting application/octet-stream, but also announce that
* this header field might change in the seconds few requests
*
* This should fix the aggressive caching of FF and the script download
* seen by the first installations
*/
response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("application/octet-stream"));
allow_caching = 0;
} else {
response_header_overwrite(srv, con, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(sce->content_type));
}
}
if (con->conf.range_requests) {
response_header_overwrite(srv, con, CONST_STR_LEN("Accept-Ranges"), CONST_STR_LEN("bytes"));
}
if (allow_caching) {
if (p->conf.etags_used && con->etag_flags != 0 && !buffer_is_empty(sce->etag)) {
if (con->use_cache_file == 0 && NULL == array_get_element(con->response.headers, "ETag")) {
/* generate e-tag */
etag_mutate(con->physical.etag, sce->etag);
response_header_overwrite(srv, con, CONST_STR_LEN("ETag"), CONST_BUF_LEN(con->physical.etag));
}
}
/* prepare header */
if (NULL == (ds = (data_string *)array_get_element(con->response.headers, "Last-Modified"))) {
mtime = strftime_cache_get(srv, sce->st.st_mtime);
if (con->use_cache_file == 0)
response_header_overwrite(srv, con, CONST_STR_LEN("Last-Modified"), CONST_BUF_LEN(mtime));
} else {
mtime = ds->value;
}
if (HANDLER_FINISHED == http_response_handle_cachable(srv, con, mtime, con->physical.etag)) {
return HANDLER_FINISHED;
}
}
if (con->request.http_range && con->conf.range_requests) {
int do_range_request = 1;
/* check if we have a conditional GET */
if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "If-Range"))) {
/* if the value is the same as our ETag, we do a Range-request,
* otherwise a full 200 */
if (ds->value->ptr[0] == '"') {
/**
* client wants a ETag
*/
if (!con->physical.etag) {
do_range_request = 0;
} else if (con->use_cache_file == 0 && !buffer_is_equal(ds->value, con->physical.etag)) {
do_range_request = 0;
}
} else if (!mtime) {
/**
* we don't have a Last-Modified and can match the If-Range:
*
* sending all
*/
do_range_request = 0;
} else if (!buffer_is_equal(ds->value, mtime)) {
do_range_request = 0;
}
}
if (do_range_request) {
/* content prepared, I'm done */
con->file_finished = 1;
if (0 == http_response_parse_range(srv, con, p)) {
con->http_status = 206;
}
return HANDLER_FINISHED;
}
}
/* if we are still here, prepare body */
/* we add it here for all requests
* the HEAD request will drop it afterwards again
*/
http_chunk_append_file(srv, con, con->physical.path, 0, sce->st.st_size);
con->http_status = 200;
con->file_finished = 1;
return HANDLER_FINISHED;
}
/* this function is called at dlopen() time and inits the callbacks */
int mod_staticfile_plugin_init(plugin *p);
int mod_staticfile_plugin_init(plugin *p) {
p->version = LIGHTTPD_VERSION_ID;
p->name = buffer_init_string("staticfile");
p->init = mod_staticfile_init;
p->handle_subrequest_start = mod_staticfile_subrequest;
p->set_defaults = mod_staticfile_set_defaults;
p->cleanup = mod_staticfile_free;
p->data = NULL;
return 0;
}
|
Evgeniy29/GOF
|
MyTools.h
|
#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
namespace MyTools {
// Палитра цветов от 0 до 15
enum ConsoleColor
{
CC_Black = 0,
CC_Blue,
CC_Green,
CC_Cyan,
CC_Red,
CC_Magenta,
CC_Brown,
CC_LightGray,
CC_DarkGray,
CC_LightBlue,
CC_LightGreen,
CC_LightCyan,
CC_LightRed,
CC_LightMagenta,
CC_Yellow,
CC_White
};
//=============================================================================================
void ClrScr();
void __fastcall GotoXY(double x, double y);
uint16_t GetMaxX();
uint16_t GetMaxY();
void SetColor(ConsoleColor color);
//=============================================================================================
//void __fastcall OpenLogFile(const std::string& FN);
//void CloseLogFile();
//void __fastcall WriteToLog(const std::string& str);
//void __fastcall WriteToLog(const std::string& str, int n);
//void __fastcall WriteToLog(const std::string& str, double d);
//=============================================================================================
class Logger
{
public:
virtual void OpenLogFile(const std::string& FN) = 0;
virtual void CloseLogFile() = 0;
virtual void WriteToLog(const std::string& str) = 0;
virtual void WriteToLog(const std::string& str, int n) = 0;
virtual void WriteToLog(const std::string& str, double d) = 0;
virtual ~Logger() {}
};
class FileLoggerSingleton : public Logger
{
public:
static FileLoggerSingleton& getInstance()
{
static FileLoggerSingleton _instance;
return _instance;
}
void OpenLogFile(const std::string& FN) override;
void CloseLogFile() override;
void WriteToLog(const std::string& str) override;
void WriteToLog(const std::string& str, int n) override;
void WriteToLog(const std::string& str, double d) override;
~FileLoggerSingleton();
private:
FileLoggerSingleton() {}
FileLoggerSingleton(const FileLoggerSingleton&) = delete;
FileLoggerSingleton& operator=(const FileLoggerSingleton&) = delete;
FileLoggerSingleton& operator=(FileLoggerSingleton&&) = delete;
};
/* class LoggerSingleton : public Logger
{
public:
static LoggerSingleton& getInstance()
{
static LoggerSingleton _instance;
return _instance;
}
void OpenLogFile(const std::string& FN) override;
void CloseLogFile() override;
void WriteToLog(const std::string& str) override;
void WriteToLog(const std::string& str, int n) override;
void WriteToLog(const std::string& str, double d) override;
~LoggerSingleton();
private:
LoggerSingleton() {}
LoggerSingleton(const LoggerSingleton&) = delete;
LoggerSingleton& operator=(const LoggerSingleton&) = delete;
LoggerSingleton& operator=(LoggerSingleton&&) = delete;
};*/
};
|
collin80/FlexCAN_T4
|
isotp.h
|
/*
MIT License
Copyright (c) 2018 <NAME> (tonton81) - https://github.com/tonton81
Designed and tested for PJRC Teensy 4.0.
Forum link : https://forum.pjrc.com/threads/56035-isotp-FlexCAN-for-Teensy-4?highlight=isotp
Thanks goes to skpang, mjs513, and collin for tech/testing support
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#if !defined(_ISOTP_H_)
#define _ISOTP_H_
#include "Arduino.h"
#include "circular_buffer.h"
#include "isotp.h"
#if defined(TEENSYDUINO) // Teensy
#include "FlexCAN_T4.h"
#elif defined(ARDUINO_ARCH_ESP32) //ESP32
#include "ESP32_CAN.h"
#endif
enum ISOTP_FLOW
{
FLOW_CTS = 0,
FLOW_WAIT= 1,
FLOW_ABORT = 2
};
typedef struct ISOTP_data {
uint32_t id = 0; /* can identifier */
struct {
bool extended = 0; /* identifier is extended (29-bit) */
bool usePadding = 0; /* padd and use all 8 bytes instead of truncating len */
bool separation_uS = 0; /* separation time in uS (100-900uS only) */
} flags;
uint16_t len = 8; /* length of CAN message or callback payload */
uint16_t blockSize = 0; /* used for flow control, specify how many frame blocks per frame control request */
uint16_t blockNum = 0; /* used with blockSize. This tracks how many blocks we're at. Redo flow control afterward */
ISOTP_FLOW flow_control_type = FLOW_CTS; /* flow control type */
uint16_t separation_time = 0; /* time between frames */
} ISOTP_data;
typedef enum ISOTP_RXBANKS_TABLE {
RX_BANKS_2 = (uint16_t)2,
RX_BANKS_4 = (uint16_t)4,
RX_BANKS_8 = (uint16_t)8,
RX_BANKS_16 = (uint16_t)16,
RX_BANKS_32 = (uint16_t)32,
RX_BANKS_64 = (uint16_t)64,
RX_BANKS_128 = (uint16_t)128,
RX_BANKS_256 = (uint16_t)256,
RX_BANKS_512 = (uint16_t)512,
RX_BANKS_1024 = (uint16_t)1024
} ISOTP_RXBANKS_TABLE;
#define ISOTP_CLASS template<ISOTP_RXBANKS_TABLE _rxBanks = RX_BANKS_16, size_t _max_length = 32>
#define ISOTP_FUNC template<ISOTP_RXBANKS_TABLE _rxBanks, size_t _max_length>
#define ISOTP_OPT isotp<_rxBanks, _max_length>
typedef void (*_isotp_cb_ptr)(const ISOTP_data &config, const uint8_t *buf);
#if defined(TEENSYDUINO) // Teensy
static FlexCAN_T4_Base* _isotp_busToWrite = nullptr;
#elif defined(ARDUINO_ARCH_ESP32) //ESP32
static ESP32_CAN_Base* _isotp_busToWrite = nullptr;
#endif
class isotp_Base {
public:
virtual void _process_frame_data(const CAN_message_t &msg) = 0;
virtual void write(const ISOTP_data &config, const uint8_t *buf, uint16_t size) = 0;
void setBoundID(int32_t newID) { boundID = newID; }
void setBoundBus(int32_t bus) { boundBus = bus; }
_isotp_cb_ptr _isotp_handler = nullptr;
static int buffer_hosts;
int thisBufferHost = 0;
int boundBus = -1;
int boundID = -1;
};
static isotp_Base* _ISOTP_OBJ[16] = { nullptr };
ISOTP_CLASS class isotp : public isotp_Base {
public:
isotp();
#if defined(TEENSYDUINO) // Teensy
void setWriteBus(FlexCAN_T4_Base* _busWritePtr) {
_isotp_busToWrite = _busWritePtr;
#if defined(__IMXRT1062__)
if ( _isotp_busToWrite == _CAN1 ) readBus = 1;
if ( _isotp_busToWrite == _CAN2 ) readBus = 2;
if ( _isotp_busToWrite == _CAN3 ) readBus = 3;
#endif
#if defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__)
if ( _isotp_busToWrite == _CAN0 ) readBus = 0;
if ( _isotp_busToWrite == _CAN1 ) readBus = 1;
#endif
}
#elif defined(ARDUINO_ARCH_ESP32) //ESP32
void setWriteBus(ESP32_CAN_Base* _busWritePtr) { _isotp_busToWrite = _busWritePtr; }
#endif
void begin() { enable(); }
void enable(bool yes = 1) { isotp_enabled = yes; }
void setPadding(uint8_t _byte) { padding_value = _byte; }
void onReceive(_isotp_cb_ptr handler) { _ISOTP_OBJ[thisBufferHost]->_isotp_handler = handler; }
void write(const ISOTP_data &config, const uint8_t *buf, uint16_t size);
void write(const ISOTP_data &config, const char *buf, uint16_t size) { write(config, (const uint8_t*)buf, size); }
void sendFlowControl(const ISOTP_data &config);
private:
void _process_frame_data(const CAN_message_t &msg);
Circular_Buffer<uint8_t, _rxBanks, _max_length> _rx_slots;
uint8_t padding_value = 0xA5;
volatile bool isotp_enabled = 0;
uint8_t readBus = 1;
};
#include "isotp.tpp"
#endif
|
wy1433/BaikalDB
|
include/protocol/show_helper.h
|
<filename>include/protocol/show_helper.h
// Copyright (c) 2018-present Baidu, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include "common.h"
#include "network_socket.h"
#include "meta_server_interact.hpp"
#include "mysql_wrapper.h"
const std::string SQL_SHOW_ABNORMAL_REGIONS = "abnormal"; // show abnormal regions;
const std::string SQL_SHOW_CREATE_TABLE = "create"; // show create table test;
const std::string SQL_SHOW_COLLATION = "collation"; // show collation;
const std::string SQL_SHOW_DATABASES = "databases"; // show databases;
const std::string SQL_SHOW_NAMESPACE = "namespace"; // show namespace
const std::string SQL_SHOW_META = "meta"; // show meta;
const std::string SQL_SHOW_TABLE_STATUS = "table"; // show table status;
const std::string SQL_SHOW_TABLES = "tables"; // show tables;
const std::string SQL_SHOW_SOCKET = "socket"; // show socket;
const std::string SQL_SHOW_WARNINGS = "warnings"; // show warnings;
const std::string SQL_SHOW_PROCESSLIST = "processlist"; // show processlist;
const std::string SQL_SHOW_COST = "cost"; // show cost switch;
const std::string SQL_SHOW_FULL_TABLES = "full_tables"; // show full tables;
const std::string SQL_SHOW_FULL_COLUMNS = "full_columns"; // show full columns;
const std::string SQL_SHOW_SCHEMA_CONF = "schema_conf"; // show schema_conf database_table;
const std::string SQL_SHOW_VIRTUAL_INDEX = "virtual"; // show virtual index;
const std::string SQL_SHOW_SESSION_VARIABLES = "show session variables";
const std::string SQL_DISABLE_INDEXS = "disable"; // show disable indexs;
const std::string SQL_SHOW_REGION = "region"; // show region tableID regionID
const std::string SQL_SHOW_STORE_REGION = "store"; // show store region storeAddress regionID
const std::string SQL_SHOW_VARIABLES = "variables"; // show variables;
const std::string SQL_SHOW_USER = "user"; // show user username;
const std::string SQL_SHOW_STORE_TXN = "store_txn"; // show store_txn storeAddress regionID;
const std::string SQL_SHOW_DDL_WORK = "ddlwork"; // show ddlwork tableID;
const std::string SQL_SHOW_GLOBAL_DDL_WORK = "global_ddlwork"; // show global_ddlwork tableID;
const std::string SQL_SHOW_PRIVILEGE = "privilege"; // show privilege username;
const std::string SQL_SHOW_DIFF_REGION_SIZE = "diff_region_size"; // show diff_region_size tableID
const std::string SQL_SHOW_NETWORK_SEGMENT = "network_segment"; // show network_segment resourceTag;
const std::string SQL_SHOW_SWITCH = "switch"; // show switch
const std::string SQL_SHOW_ALL_TABLES = "all_tables"; // show all_tables [ttl/binlog/...]
namespace baikaldb {
typedef std::shared_ptr<NetworkSocket> SmartSocket;
class ShowHelper {
public:
static ShowHelper* get_instance() {
static ShowHelper _instance;
return &_instance;
}
void init();
bool execute(const SmartSocket& client);
bool _handle_client_query_template(const SmartSocket& client, const std::string& field_name, int32_t data_type,
const std::vector<std::string>& values);
private:
ShowHelper() {
}
virtual ~ShowHelper() {
}
// Key -> function
std::unordered_map<std::string, std::function<
bool(const SmartSocket& client, const std::vector<std::string>& split_vec)>
> _calls;
// sql: show abnormal regions [ resource_tag ];
bool _show_abnormal_regions(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show databases;
bool _show_databases(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show tables;
bool _show_tables(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show create table tableName;
bool _show_create_table(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show collation
bool _show_collation(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show socket
bool _show_socket(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show warnings;
bool _show_warnings(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show processlist;
bool _show_processlist(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show cost switch;
bool _show_cost(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show full tables;
bool _show_full_tables(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show full columns from tableName;
bool _show_full_columns(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show schema_conf database_table;
bool _show_schema_conf(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show all_tables ttl/binlog;
bool _show_all_tables(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show table status;
bool _show_table_status(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show virtual index
bool _show_virtual_index(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show region tableID regionID;
bool _show_region(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show store region storeAddress regionID;
bool _show_store_region(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show variables;
bool _show_variables(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show privilege username;
bool _show_privilege(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show store_txn storeAddress regionID;
bool _show_store_txn(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show ddlwork tableID;
bool _show_ddl_work(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show global_ddlwork tableID;
bool _show_global_ddl_work(const SmartSocket& client, const std::vector<std::string>& split_vec);
bool _show_diff_region_size(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show user username
bool _show_user(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show network ResourceTag;
bool _show_network_segment(const SmartSocket& client, const std::vector<std::string>& split_vec);
// sql: show switch
bool _show_switch(const SmartSocket& client, const std::vector<std::string>& split_vec);
bool _handle_client_query_template_dispatch(const SmartSocket& client, const std::vector<std::string>& split_vec);
int _make_common_resultset_packet(const SmartSocket& sock,
std::vector<ResultField>& fields,
std::vector< std::vector<std::string> >& rows);
void _parse_sample_sql(std::string sample_sql, std::string& database, std::string& table, std::string& sql);
MysqlWrapper* _wrapper = nullptr;
};
}
|
wy1433/BaikalDB
|
include/store/region.h
|
// Copyright (c) 2018-present Baidu, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <stdint.h>
#include <fstream>
#include <atomic>
#include <boost/lexical_cast.hpp>
#ifdef BAIDU_INTERNAL
#include <base/iobuf.h>
#include <base/containers/bounded_queue.h>
#include <base/time.h>
#include <raft/raft.h>
#include <raft/util.h>
#include <raft/storage.h>
#include <raft/snapshot_throttle.h>
#else
#include <butil/iobuf.h>
#include <butil/containers/bounded_queue.h>
#include <butil/time.h>
#include <braft/raft.h>
#include <braft/util.h>
#include <braft/storage.h>
#include <braft/snapshot_throttle.h>
#endif
#include "common.h"
#include "schema_factory.h"
#include "table_key.h"
#include "mut_table_key.h"
#include "rocks_wrapper.h"
#include "split_compaction_filter.h"
#include "proto/common.pb.h"
#include "proto/meta.interface.pb.h"
#include "proto/store.interface.pb.h"
#include "reverse_index.h"
#include "transaction_pool.h"
//#include "region_resource.h"
#include "runtime_state.h"
#include "runtime_state_pool.h"
#include "rapidjson/document.h"
#include "rocksdb_file_system_adaptor.h"
#include "region_control.h"
#include "meta_writer.h"
#include "rpc_sender.h"
#include "exec_node.h"
#include "concurrency.h"
#include "backup.h"
#ifdef BAIDU_INTERNAL
#else
//开源编译,等raft learner开源后删除
#include <braft/raft.h>
namespace braft {
class Learner {
public:
Learner(const GroupId& group_id, const PeerId& peer_id) {
}
int init(const NodeOptions& options) {
return 0;
}
void shutdown(Closure* done) {
}
void join() {
}
void snapshot(Closure* done) {
}
void get_status(NodeStatus* status) {
}
};
}
#endif
using google::protobuf::Message;
using google::protobuf::RepeatedPtrField;
namespace baikaldb {
DECLARE_int64(disable_write_wait_timeout_us);
DECLARE_int32(prepare_slow_down_wait);
static std::atomic<int64_t> ttl_remove_rows = { 0 }; // ttl删除行数计数
static const int32_t RECV_QUEUE_SIZE = 128;
struct StatisticsInfo {
int64_t time_cost_sum;
int64_t end_time_us;
};
enum BinlogType {
PREWRITE_BINLOG,
COMMIT_BINLOG,
ROLLBACK_BINLOG,
FAKE_BINLOG
};
inline const char* binlog_type_name(const BinlogType type) {
if (type == PREWRITE_BINLOG) {
return "PREWRITE_BINLOG";
} else if (type == COMMIT_BINLOG) {
return "COMMIT_BINLOG";
} else if (type == ROLLBACK_BINLOG) {
return "ROLLBACK_BINLOG";
} else {
return "FAKE_BINLOG";
}
}
struct BinlogDesc {
int64_t primary_region_id = 0;
int64_t txn_id;
BinlogType binlog_type;
TimeCost time;
};
struct ApproximateInfo {
int64_t table_lines = 0;
uint64_t region_size = 0;
TimeCost time_cost;
//上次分裂的大小,分裂后不做compaction,则新的大小不会变化
//TODO:是否持久化存储,重启后,新老大小差不多则可以做compaction
uint64_t last_version_region_size = 0;
uint64_t last_version_table_lines = 0;
TimeCost last_version_time_cost;
};
class region;
class ScopeProcStatus {
public:
ScopeProcStatus(Region* region) : _region(region) {}
~ScopeProcStatus();
void reset() {
_region = NULL;
}
private:
Region* _region;
};
class ScopeMergeStatus {
public:
ScopeMergeStatus(Region* region) : _region(region) {}
~ScopeMergeStatus();
void reset() {
_region = NULL;
}
private:
Region* _region;
};
class TransactionPool;
typedef std::shared_ptr<Region> SmartRegion;
class Region : public braft::StateMachine, public std::enable_shared_from_this<Region> {
friend class RegionControl;
friend class Backup;
public:
static const uint8_t PRIMARY_INDEX_FLAG;
static const uint8_t SECOND_INDEX_FLAG;
virtual ~Region() {
shutdown();
join();
for (auto& pair : _reverse_index_map) {
delete pair.second;
}
}
void wait_async_apply_log_queue_empty() {
BthreadCond cond;
cond.increase();
_async_apply_log_queue.run([&cond]() {
cond.decrease_signal();
});
cond.wait();
}
void shutdown() {
if (get_version() == 0) {
wait_async_apply_log_queue_empty();
_async_apply_param.stop_adjust_stall();
}
if (_need_decrease) {
_need_decrease = false;
Concurrency::get_instance()->recieve_add_peer_concurrency.decrease_broadcast();
}
bool expected_status = false;
if (_shutdown.compare_exchange_strong(expected_status, true)) {
is_learner() ? _learner->shutdown(NULL) : _node.shutdown(NULL);
_init_success = false;
DB_WARNING("raft node was shutdown, region_id: %ld", _region_id);
}
}
void join() {
is_learner() ? _learner->join() : _node.join();
DB_WARNING("raft node join completely, region_id: %ld", _region_id);
_real_writing_cond.wait();
_disable_write_cond.wait();
_multi_thread_cond.wait();
DB_WARNING("_multi_thread_cond wait success, region_id: %ld", _region_id);
_txn_pool.close();
}
void get_node_status(braft::NodeStatus* status) {
is_learner() ? _learner->get_status(status) : _node.get_status(status);
}
Region(RocksWrapper* rocksdb,
SchemaFactory* factory,
const std::string& address,
const braft::GroupId& groupId,
const braft::PeerId& peerId,
const pb::RegionInfo& region_info,
int64_t region_id,
bool is_learner = false) :
_rocksdb(rocksdb),
_factory(factory),
_address(address),
_region_info(region_info),
_region_id(region_id),
_node(groupId, peerId),
_is_leader(false),
_shutdown(false),
_num_table_lines(0),
_num_delete_lines(0),
_region_control(this, region_id),
_snapshot_adaptor(new RocksdbFileSystemAdaptor(region_id)), _is_learner(is_learner),
_not_leader_alarm(region_id, peerId) {
//create table and add peer请求状态初始化都为IDLE, 分裂请求状态初始化为DOING
_region_control.store_status(_region_info.status());
_version = _region_info.version();
_is_global_index = _region_info.has_main_table_id() &&
_region_info.main_table_id() != 0 &&
_region_info.table_id() != _region_info.main_table_id();
_global_index_id = _region_info.table_id();
_table_id = _is_global_index ? _region_info.main_table_id() : _region_info.table_id();
if (_region_info.has_is_binlog_region()) {
_is_binlog_region = _region_info.is_binlog_region();
}
if (_is_learner) {
_learner.reset(new braft::Learner(groupId, peerId));
}
}
int init(bool new_region, int32_t snapshot_times);
void wait_table_info() {
while (!SchemaFactory::get_instance()->exist_tableid(get_table_id())) {
DB_WARNING("region_id: %ld wait for table_info: %ld", _region_id, get_table_id());
bthread_usleep(1000 * 1000);
}
}
void raft_control(google::protobuf::RpcController* controller,
const pb::RaftControlRequest* request,
pb::RaftControlResponse* response,
google::protobuf::Closure* done) {
_region_control.raft_control(controller, request, response, done);
};
void async_apply_log_entry(google::protobuf::RpcController* controller,
const pb::BatchStoreReq* request,
pb::BatchStoreRes* response,
google::protobuf::Closure* done);
void query(google::protobuf::RpcController* controller,
const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
void query_binlog(google::protobuf::RpcController* controller,
const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
void dml(const pb::StoreReq& request,
pb::StoreRes& response,
int64_t applied_index,
int64_t term, bool need_txn_limit);
void dml_2pc(const pb::StoreReq& request,
pb::OpType op_type,
const pb::Plan& plan,
const RepeatedPtrField<pb::TupleDescriptor>& tuples,
pb::StoreRes& response,
int64_t applied_index,
int64_t term,
int seq_id, bool need_txn_limit);
void dml_1pc(const pb::StoreReq& request,
pb::OpType op_type,
const pb::Plan& plan,
const RepeatedPtrField<pb::TupleDescriptor>& tuples,
pb::StoreRes& response,
int64_t applied_index,
int64_t term,
braft::Closure* done);
int select(const pb::StoreReq& request, pb::StoreRes& response);
int select(const pb::StoreReq& request,
const pb::Plan& plan,
const RepeatedPtrField<pb::TupleDescriptor>& tuples,
pb::StoreRes& response);
int select_normal(RuntimeState& state, ExecNode* root, pb::StoreRes& response);
int select_sample(RuntimeState& state, ExecNode* root, const pb::AnalyzeInfo& analyze_info, pb::StoreRes& response);
void do_apply(int64_t term, int64_t index, const pb::StoreReq& request, braft::Closure* done);
virtual void on_apply(braft::Iterator& iter);
virtual void on_shutdown();
virtual void on_leader_start(int64_t term);
virtual void on_snapshot_save(braft::SnapshotWriter* writer, braft::Closure* done);
virtual int on_snapshot_load(braft::SnapshotReader* reader);
virtual void on_leader_stop();
virtual void on_leader_stop(const butil::Status& status);
virtual void on_error(const ::braft::Error& e);
virtual void on_configuration_committed(const ::braft::Configuration& conf);
virtual void on_configuration_committed(const ::braft::Configuration& conf, int64_t index);
void snapshot(braft::Closure* done);
void on_snapshot_load_for_restart(braft::SnapshotReader* reader,
std::map<int64_t, std::string>& prepared_log_entrys);
void construct_heart_beat_request(pb::StoreHeartBeatRequest& request, bool need_peer_balance);
void construct_peers_status(pb::LeaderHeartBeat* leader_heart);
void set_can_add_peer();
//leader收到从metaServer心跳包中的解析出来的add_peer请求
void add_peer(const pb::AddPeer& add_peer, SmartRegion region, ExecutionQueue& queue) {
_region_control.add_peer(add_peer, region, queue);
}
RegionControl& get_region_control() {
return _region_control;
}
void add_peer(const pb::AddPeer* request,
pb::StoreRes* response,
google::protobuf::Closure* done) {
_region_control.add_peer(request, response, done);
}
void do_snapshot() {
_region_control.sync_do_snapshot();
}
int transfer_leader(const pb::TransLeaderRequest& trans_leader_request,
SmartRegion region, ExecutionQueue& queue) {
return _region_control.transfer_leader(trans_leader_request, region, queue);
}
void reset_region_status () {
_region_control.reset_region_status();
}
void reset_snapshot_status();
pb::RegionStatus get_status() const {
return _region_control.get_status();
}
//int clear_data();
void compact_data_in_queue();
int ingest_snapshot_sst(const std::string& dir);
int ingest_sst(const std::string& data_sst_file, const std::string& meta_sst_file);
// other thread
void reverse_merge();
// other thread
void ttl_remove_expired_data();
// dump the the tuples in this region in format {{k1:v1},{k2:v2},{k3,v3}...}
// used for debug
std::string dump_hex();
//on_apply里调用的方法
void start_split(braft::Closure* done, int64_t applied_index, int64_t term);
void start_split_for_tail(braft::Closure* done, int64_t applied_index, int64_t term);
void validate_and_add_version(const pb::StoreReq& request, braft::Closure* done, int64_t applied_index, int64_t term);
void add_version_for_split_region(const pb::StoreReq& request, braft::Closure* done, int64_t applied_index, int64_t term);
void apply_txn_request(const pb::StoreReq& request, braft::Closure* done, int64_t index, int64_t term);
void adjustkey_and_add_version(const pb::StoreReq& request,
braft::Closure* done,
int64_t applied_index,
int64_t term);
void exec_update_primary_timestamp(const pb::StoreReq& request,
braft::Closure* done, int64_t applied_index, int64_t term);
void adjustkey_and_add_version_query(google::protobuf::RpcController* controller,
const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
//开始做merge操作
void start_process_merge(const pb::RegionMergeResponse& merge_response);
//开始做split操作
//第一步通过raft状态机,创建迭代器,取出当前的index,自此之后的log不能再删除
void start_process_split(const pb::RegionSplitResponse& split_response,
bool tail_split,
const std::string& split_key,
int64_t key_term);
void get_split_key_for_tail_split();
void adjust_num_table_lines();
//split第二步,发送迭代器数据
void write_local_rocksdb_for_split();
int replay_txn_for_recovery(
const std::unordered_map<uint64_t, pb::TransactionInfo>& prepared_txn);
int replay_applied_txn_for_recovery(
int64_t region_id,
const std::string& instance,
std::string start_key,
const std::unordered_map<uint64_t, pb::TransactionInfo>& applied_txn);
void send_log_entry_to_new_region_for_split();
int split_region_add_peer(std::string& new_region_leader);
void split_remove_new_region_peers() {
start_thread_to_remove_region(_split_param.new_region_id, _split_param.instance);
for (auto& peer : _split_param.add_peer_instances) {
start_thread_to_remove_region(_split_param.new_region_id, peer);
}
}
//split 第三步, 通知被分裂出来的region分裂完成, 增加old_region的version, update end_key
void send_complete_to_new_region_for_split();
//分裂第四步完成
void complete_split();
void transfer_leader_after_split();
//从split开始之后所有的entry数据作为分裂的增量部分
// 1说明还有数据,0说明到头了
int get_log_entry_for_split(const int64_t start_index,
const int64_t expected_term,
std::vector<pb::BatchStoreReq>& requests,
std::vector<butil::IOBuf>& req_datas, // cntl attachment的数据
int64_t& split_end_index);
int get_split_key(std::string& split_key, int64_t& split_key_term);
int64_t get_region_id() const {
return _region_id;
}
void update_average_cost(int64_t request_time_cost);
void reset_split_status() {
if (_split_param.snapshot != nullptr) {
_rocksdb->get_db()->ReleaseSnapshot(_split_param.snapshot);
}
_split_param.reset_status();
}
void real_writing_decrease() {
_real_writing_cond.decrease_signal();
}
void reset_allow_write() {
_disable_write_cond.decrease_broadcast();
}
void set_disable_write() {
_disable_write_cond.increase();
}
int32_t num_prepared() {
return _txn_pool.num_prepared();
}
int32_t num_began() {
return _txn_pool.num_began();
}
int64_t get_split_index() {
return _split_param.split_start_index;
}
void set_used_size(int64_t used_size) {
std::lock_guard<std::mutex> lock(_region_lock);
_region_info.set_used_size(used_size);
}
std::string get_start_key() {
std::lock_guard<std::mutex> lock(_region_lock);
return _region_info.start_key();
}
std::string get_end_key() {
std::lock_guard<std::mutex> lock(_region_lock);
return _region_info.end_key();
}
int64_t get_partition_num() {
std::lock_guard<std::mutex> lock(_region_lock);
if (_region_info.has_partition_num()) {
return _region_info.partition_num();
}
return 1;
}
rocksdb::Range get_rocksdb_range() {
return rocksdb::Range(_rocksdb_start, _rocksdb_end);
}
bool is_merged() {
std::lock_guard<std::mutex> lock(_region_lock);
if (!_region_info.start_key().empty()) {
return _region_info.start_key() == _region_info.end_key();
}
return false;
}
int64_t get_log_index() const {
return _applied_index;
}
int64_t get_data_index() const {
return _data_index;
}
int64_t get_log_index_lastcycle() const {
return _applied_index_lastcycle;
}
void reset_log_index_lastcycle() {
_applied_index_lastcycle = _applied_index;
_lastcycle_time_cost.reset();
}
int64_t get_lastcycle_timecost() const {
return _lastcycle_time_cost.get_time();
}
int64_t get_last_split_time_cost() const {
return _last_split_time_cost.get_time();
}
rocksdb::ColumnFamilyHandle* get_data_cf() const {
return _data_cf;
}
butil::EndPoint get_leader() {
if (is_learner()) {
butil::EndPoint leader;
butil::str2endpoint(region_info().leader().c_str(), &leader);
return leader;
}
return _node.leader_id().addr;
}
int64_t get_used_size() {
std::lock_guard<std::mutex> lock(_region_lock);
return _region_info.used_size();
}
int64_t get_table_id() {
return _table_id;
}
int64_t get_global_index_id() {
return _global_index_id;
}
bool is_leader() {
return (_is_leader.load());
}
void leader_start(int64_t term) {
_is_leader.store(true);
_not_leader_alarm.reset();
_expected_term = term;
DB_WARNING("leader real start, region_id: %ld term: %ld", _region_id, term);
}
int64_t get_version() {
return _version;
}
int64_t get_dml_latency() {
return _dml_time_cost.latency();
}
pb::RegionInfo& region_info() {
return _region_info;
}
std::shared_ptr<RegionResource> get_resource() {
BAIDU_SCOPED_LOCK(_ptr_mutex);
return _resource;
}
bool check_region_legal_complete();
bool compare_and_set_illegal() {
std::unique_lock<std::mutex> lock(_legal_mutex);
std::lock_guard<std::mutex> lock_region(_region_lock);
if (_region_info.version() <= 0) {
_legal_region = false;
return true;
}
return false;
}
bool compare_and_set_legal_for_split() {
std::unique_lock<std::mutex> lock(_legal_mutex);
if (_legal_region) {
std::lock_guard<std::mutex> lock_region(_region_lock);
_region_info.set_version(1);
DB_WARNING("compare and set split verison to 1, region_id: %ld", _region_id);
return true;
}
return false;
}
bool compare_and_set_legal() {
std::unique_lock<std::mutex> lock(_legal_mutex);
if (_legal_region) {
return true;
}
return false;
}
int64_t get_num_table_lines() {
return _num_table_lines.load();
}
bool is_tail() {
std::lock_guard<std::mutex> lock(_region_lock);
return (_region_info.end_key().empty());
}
bool is_head() {
std::lock_guard<std::mutex> lock(_region_lock);
return (_region_info.start_key().empty());
}
bool empty() {
std::lock_guard<std::mutex> lock(_region_lock);
return (_region_info.start_key() == _region_info.end_key()
&& !_region_info.end_key().empty()
&& !_region_info.start_key().empty());
}
int64_t get_timecost() {
return _time_cost.get_time();
}
void reset_timecost() {
return _time_cost.reset();
}
void set_num_table_lines(int64_t table_line) {
MetaWriter::get_instance()->update_num_table_lines(_region_id, table_line);
_num_table_lines.store(table_line);
DB_WARNING("region_id: %ld, table_line:%ld", _region_id, _num_table_lines.load());
}
bool removed() const {
return _removed;
}
bool is_binlog_region() const { return _is_binlog_region; }
void set_removed(bool removed) {
_removed = removed;
_removed_time_cost.reset();
}
int64_t removed_time_cost() const {
return _removed_time_cost.get_time();
}
int64_t get_split_wait_time() {
int64_t wait_time = FLAGS_disable_write_wait_timeout_us;
if (FLAGS_disable_write_wait_timeout_us < _split_param.split_slow_down_cost * 10) {
wait_time = _split_param.split_slow_down_cost * 10;
}
if (wait_time > 30 * 1000 * 1000LL) {
//DB_WARNING("split wait time exceed 30s, region_id: %ld", _region_id);
wait_time = 30 * 1000 * 1000LL;
}
return wait_time;
}
void exec_in_txn_query(google::protobuf::RpcController* controller,
const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
void exec_out_txn_query(google::protobuf::RpcController* controller,
const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
void exec_txn_query_primary_region(google::protobuf::RpcController* controller,
const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
void exec_txn_complete(google::protobuf::RpcController* controller,
const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
void exec_txn_query_state(google::protobuf::RpcController* controller,
const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
void exec_dml_out_txn_query(const pb::StoreReq* request,
pb::StoreRes* response,
google::protobuf::Closure* done);
int execute_cached_cmd(const pb::StoreReq& request, pb::StoreRes& response,
uint64_t txn_id,
SmartTransaction& txn,
int64_t applied_index,
int64_t term,
uint64_t log_id);
void clear_transactions() {
if (_shutdown || !_init_success || get_version() <= 0) {
return;
}
_multi_thread_cond.increase();
_txn_pool.clear_transactions(this);
_multi_thread_cond.decrease_signal();
}
void update_ttl_info() {
if (_shutdown || !_init_success || get_version() <= 0) {
return;
}
TTLInfo ttl_info = _factory->get_ttl_duration(get_table_id());
if (ttl_info.ttl_duration_s > 0 && ttl_info.online_ttl_expire_time_us > 0) {
// online TTL
if (ttl_info.online_ttl_expire_time_us != _online_ttl_base_expire_time_us) {
_online_ttl_base_expire_time_us = ttl_info.online_ttl_expire_time_us;
_use_ttl = true;
_txn_pool.update_ttl_info(_use_ttl, _online_ttl_base_expire_time_us);
DB_WARNING("table_id: %ld, region_id: %ld, ttl_duration_s: %ld, online_ttl_expire_time_us: %ld, %s",
get_table_id(), _region_id, ttl_info.ttl_duration_s,
ttl_info.online_ttl_expire_time_us, timestamp_to_str(ttl_info.online_ttl_expire_time_us/1000000).c_str());
}
}
}
void clear_orphan_transactions(braft::Closure* done, int64_t applied_index, int64_t term);
void apply_clear_transactions_log();
TransactionPool& get_txn_pool() {
return _txn_pool;
}
void rollback_txn_before(int64_t timeout) {
return _txn_pool.rollback_txn_before(timeout);
}
void start_thread_to_remove_region(int64_t drop_region_id, std::string instance_address) {
Bthread bth(&BTHREAD_ATTR_SMALL);
std::function<void()> remove_region_function =
[this, drop_region_id, instance_address]() {
_multi_thread_cond.increase();
RpcSender::send_remove_region_method(drop_region_id, instance_address);
_multi_thread_cond.decrease_signal();
};
bth.run(remove_region_function);
}
void set_restart(bool restart) {
_restart = restart;
}
//现在支持replica_num的修改,从region_info里去replica_num已经不准确
//bool peers_stable() {
// std::vector<braft::PeerId> peers;
// return _node.list_peers(&peers).ok() && peers.size() >= (size_t)_region_info.replica_num();
//}
void copy_region(pb::RegionInfo* region_info) {
std::lock_guard<std::mutex> lock(_region_lock);
region_info->CopyFrom(_region_info);
}
void kv_apply_raft(RuntimeState* state, SmartTransaction txn);
void set_separate_switch(bool is_separate) {
_storage_compute_separate = is_separate;
}
void lock_commit_meta_mutex() {
_commit_meta_mutex.lock();
}
void unlock_commit_meta_mutex() {
_commit_meta_mutex.unlock();
}
void put_commit_ts(const uint64_t txn_id, int64_t commit_ts) {
std::unique_lock<bthread::Mutex> lck(_commit_ts_map_lock);
_commit_ts_map[txn_id] = commit_ts;
if (_commit_ts_map.size() > 100000) {
// 一天阈值
int64_t threshold_value = commit_ts - 86400000LL;
auto iter = _commit_ts_map.begin();
while (iter != _commit_ts_map.end()) {
if (iter->second < threshold_value) {
iter = _commit_ts_map.erase(iter);
} else {
++iter;
}
}
}
}
int64_t get_commit_ts(uint64_t txn_id, int64_t start_ts) {
std::unique_lock<bthread::Mutex> lck(_commit_ts_map_lock);
if (_commit_ts_map.count(txn_id) == 0) {
return -1;
}
return _commit_ts_map[txn_id];
}
void remove_local_index_data();
void delete_local_rocksdb_for_ddl(int64_t table_id, int64_t index_id);
int add_reverse_index(int64_t table_id, int64_t index_id);
void process_download_sst(brpc::Controller* controller,
std::vector<std::string>& req_vec, SstBackupType type);
void process_upload_sst(brpc::Controller* controller, bool is_ingest);
void process_download_sst_streaming(brpc::Controller* controller,
const pb::BackupRequest* request,
pb::BackupResponse* response);
void process_upload_sst_streaming(brpc::Controller* controller, bool is_ingest,
const pb::BackupRequest* request,
pb::BackupResponse* response);
std::shared_ptr<Region> get_ptr() {
return shared_from_this();
}
uint64_t snapshot_data_size() const {
return _snapshot_data_size;
}
void set_snapshot_data_size(size_t size) {
_snapshot_data_size = size;
}
uint64_t snapshot_meta_size() const {
return _snapshot_meta_size;
}
void set_snapshot_meta_size(size_t size) {
_snapshot_meta_size = size;
}
bool is_addpeer() const {
return _region_info.can_add_peer();
}
uint64_t get_approx_size() {
//分裂后一段时间每超过10分钟,或者超过10%的数据量diff则需要重新获取
if (_approx_info.time_cost.get_time() > 10 * 60 * 1000 * 1000LL &&
_approx_info.last_version_time_cost.get_time() < 2 * 60 * 60 * 1000 * 1000LL) {
return UINT64_MAX;
} else {
int64_t diff_lines = abs(_num_table_lines.load() - _approx_info.table_lines);
if (diff_lines * 10 > _num_table_lines.load()) {
// adjust_num_table_lines();
return UINT64_MAX;
}
}
return _approx_info.region_size;
}
void set_approx_size(uint64_t region_size) {
_approx_info.time_cost.reset();
_approx_info.table_lines = _num_table_lines.load();
_approx_info.region_size = region_size;
}
bool can_use_approximate_split();
int binlog_scan_when_restart();
void binlog_timeout_check(int64_t rollback_ts);
void binlog_fake(int64_t ts, BthreadCond& cond);
pb::PeerStatus region_status() const {
return _region_status;
}
int64_t snapshot_index() const {
return _snapshot_index;
}
bool is_learner() const {
return _is_learner;
}
bool is_disable_write() {
return _disable_write_cond.count() > 0;
}
bool is_dml_op_type(const pb::OpType& op_type) {
if (op_type == pb::OP_INSERT
|| op_type == pb::OP_DELETE
|| op_type == pb::OP_UPDATE
|| op_type == pb::OP_SELECT_FOR_UPDATE) {
return true;
}
return false;
}
private:
struct SplitParam {
int64_t split_start_index = INT_FAST64_MAX;
int64_t split_end_index = 0;
int64_t split_term = 0;
int64_t new_region_id = 0;
int64_t reduce_num_lines = 0; //非精确,todo需要精确计数
bool split_slow_down = false;
int64_t split_slow_down_cost = 0;
int err_code = 0;
std::string split_key;
//std::string old_end_key;
std::string instance;
std::vector<std::string> add_peer_instances;
TimeCost total_cost;
TimeCost no_write_time_cost;
int64_t new_region_cost;
TimeCost op_start_split;
int64_t op_start_split_cost;
TimeCost op_start_split_for_tail;
int64_t op_start_split_for_tail_cost;
TimeCost op_snapshot;
TimeCost add_peer_cost;
int64_t op_snapshot_cost;
int64_t write_sst_cost;
int64_t send_first_log_entry_cost;
int64_t write_wait_cost;
int64_t send_second_log_entry_cost;
int64_t send_complete_to_new_region_cost;
TimeCost op_add_version;
int64_t op_add_version_cost;
const rocksdb::Snapshot* snapshot = nullptr;
bool tail_split = false;
std::unordered_map<uint64_t, pb::TransactionInfo> applied_txn;
void reset_status() {
split_start_index = INT_FAST64_MAX;
split_end_index = 0;
split_term = 0;
new_region_id = 0;
split_slow_down = false;
split_slow_down_cost = 0;
err_code = 0;
split_key = "";
instance = "";
reduce_num_lines = 0;
tail_split = false;
snapshot = nullptr;
applied_txn.clear();
add_peer_instances.clear();
};
};
struct BinlogParam {
std::map<int64_t, BinlogDesc> ts_binlog_map; // 用于缓存prewrite binlog元数据,便于收到commit binlog时快速反查
int64_t min_ts_in_map = -1; // ts_binlog_map中最小ts,每一轮扫描之后更新
int64_t max_ts_in_map = -1; // ts_binlog_map中最大ts,如果收到比max ts还大的binlog,则直接写rocksdb不更新map,map靠之后定时线程更新
int64_t check_point_ts = -1; // 检查点,检查点之前的binlog都已经commit,重启之后从检查点开始扫描
int64_t oldest_ts = -1; // rocksdb中最小ts,如果region 某个peer迁移,binlog数据不迁移则oldest_ts改为当前ts
std::map<int64_t, bool> timeout_start_ts_done; // 标记超时反查的start_ts, 仅用来避免重复commit导致的报警,不用于严格一致性场景
};
//binlog function
void recover_binlog();
void read_binlog(const pb::StoreReq* request, pb::StoreRes* response);
void apply_binlog(const pb::StoreReq& request, braft::Closure* done);
int write_binlog_record(SmartRecord record);
int write_binlog_value(const std::map<std::string, ExprValue>& field_value_map);
int64_t binlog_get_int64_val(const std::string& name, const std::map<std::string, ExprValue>& field_value_map);
std::string binlog_get_str_val(const std::string& name, const std::map<std::string, ExprValue>& field_value_map);
void binlog_get_scan_fields(std::map<int32_t, FieldInfo*>& field_ids, std::vector<int32_t>& field_slot);
void binlog_get_field_values(std::map<std::string, ExprValue>& field_value_map, SmartRecord record);
int binlog_reset_on_snapshot_load_restart();
int binlog_reset_on_snapshot_load();
void binlog_update_map_when_scan(const std::map<std::string, ExprValue>& field_value_map);
int binlog_update_map_when_apply(const std::map<std::string, ExprValue>& field_value_map, const std::string& remote_side);
int binlog_update_check_point();
int get_primary_region_info(int64_t primary_region_id, pb::RegionInfo& region_info);
void binlog_query_primary_region(const int64_t& start_ts, const int64_t& txn_id, pb::RegionInfo& region_info, int64_t rollback_ts);
void binlog_fill_exprvalue(const pb::BinlogDesc& binlog_desc, pb::OpType op_type, std::map<std::string, ExprValue>& field_value_map);
//binlog end
void apply_kv_in_txn(const pb::StoreReq& request, braft::Closure* done,
int64_t index, int64_t term);
void apply_kv_out_txn(const pb::StoreReq& request, braft::Closure* done,
int64_t index, int64_t term);
void apply_kv_split(const pb::StoreReq& request, braft::Closure* done,
int64_t index, int64_t term);
bool validate_version(const pb::StoreReq* request, pb::StoreRes* response);
void print_log_entry(const int64_t start_index, const int64_t end_index);
void set_region(const pb::RegionInfo& region_info) {
std::lock_guard<std::mutex> lock(_region_lock);
_region_info.CopyFrom(region_info);
_version = _region_info.version();
}
void set_region_with_update_range(const pb::RegionInfo& region_info) {
std::lock_guard<std::mutex> lock(_region_lock);
_region_info.CopyFrom(region_info);
_version = _region_info.version();
// region_info更新range,替换resource
std::shared_ptr<RegionResource> new_resource(new RegionResource);
*new_resource = *_resource;
new_resource->region_info = region_info;
{
BAIDU_SCOPED_LOCK(_ptr_mutex);
_resource = new_resource;
}
//compaction时候删掉多余的数据
if (_is_binlog_region) {
//binlog region把start key和end key设置为空,防止filter把数据删掉
SplitCompactionFilter::get_instance()->set_filter_region_info(
_region_id, "", false, 0);
} else {
SplitCompactionFilter::get_instance()->set_filter_region_info(
_region_id, region_info.end_key(),
_use_ttl, _online_ttl_base_expire_time_us);
}
DB_WARNING("region_id: %ld, start_key: %s, end_key: %s", _region_id,
rocksdb::Slice(region_info.start_key()).ToString(true).c_str(),
rocksdb::Slice(region_info.end_key()).ToString(true).c_str());
}
// if seek_table_lines != nullptr, seek all sst for seek_table_lines
bool has_sst_data(int64_t* seek_table_lines);
bool ingest_has_sst_data();
bool wait_rocksdb_normal(int64_t timeout = -1) {
TimeCost cost;
TimeCost total_cost;
while (_rocksdb->is_any_stall()) {
if (timeout > 0 && total_cost.get_time() > timeout) {
return false;
}
if (cost.get_time() > 60 * 1000 * 1000) {
DB_WARNING("region_id: %ld wait for rocksdb stall", _region_id);
cost.reset();
}
reset_timecost();
bthread_usleep(1 * 1000 * 1000);
}
return true;
}
int check_learner_snapshot();
int check_follower_snapshot(const std::string& peer);
bool learner_ready_for_read() const {
return _learner_ready_for_read;
}
void update_binlog_read_max_ts(int64_t ts) {
int64_t max_ts = _binlog_read_max_ts.load();
while (max_ts < ts) {
if (_binlog_read_max_ts.compare_exchange_strong(max_ts, ts)) {
break;
}
max_ts = _binlog_read_max_ts.load();
}
}
private:
//Singleton
RocksWrapper* _rocksdb;
SchemaFactory* _factory;
rocksdb::ColumnFamilyHandle* _data_cf;
rocksdb::ColumnFamilyHandle* _meta_cf;
std::string _address; //ip:port
//region metainfo
pb::RegionInfo _region_info;
std::mutex _region_lock;
//split后缓存分裂出去的region信息供baikaldb使用
std::vector<pb::RegionInfo> _new_region_infos;
size_t _snapshot_data_size = 0;
size_t _snapshot_meta_size = 0;
pb::RegionInfo _new_region_info;
int64_t _region_id = 0;
int64_t _version = 0;
int64_t _table_id = 0; // region.main_table_id
int64_t _global_index_id = 0; //region.table_id
//merge后该region为空,记录目标region,供baikaldb使用,只会merge一次,不必使用vector
pb::RegionInfo _merge_region_info;
// 倒排索引需要
// todo liguoqiang 如何初始化这个
std::map<int64_t, ReverseIndexBase*> _reverse_index_map;
// todo 是否可以改成无锁的
BthreadCond _disable_write_cond;
BthreadCond _real_writing_cond;
SplitParam _split_param;
std::mutex _legal_mutex;
bool _legal_region = true;
TimeCost _time_cost; //上次收到请求的时间,每次收到请求都重置一次
LatencyOnly _dml_time_cost;
bool _restart = false;
//计算存储分离开关,在store定时任务中更新,避免每次dml都访问schema factory
bool _storage_compute_separate = false;
bool _use_ttl = false; // online TTL会更新,只会false 变为true
int64_t _online_ttl_base_expire_time_us = 0; // 存量数据过期时间,仅online TTL的表使用
bool _reverse_remove_range = false; //split的数据,把拉链过滤一遍
//raft node
braft::Node _node;
std::atomic<bool> _is_leader;
// 一般情况下,_braft_apply_index和_applied_index是一致的
// 只有在加速分裂进行异步发送logEntry的时候,_braft_apply_index > _applied_index
// 两者diff值即为executionQueue里面排队的请求数
int64_t _braft_apply_index = 0;
int64_t _applied_index = 0; //current log index
// 表示数据版本,conf_change,no_op等不影响数据时版本不变
int64_t _data_index = 0;
int64_t _expected_term = -1;
// bthread cycle: set _applied_index_lastcycle = _applied_index when _num_table_lines == 0
int64_t _applied_index_lastcycle = 0;
TimeCost _lastcycle_time_cost; //定时线程上次循环的时间,更新_applied_index_lastcycle时更新
TimeCost _last_split_time_cost; //上次分裂时间戳
ApproximateInfo _approx_info;
bool _report_peer_info = false;
std::atomic<bool> _shutdown;
bool _init_success = false;
bool _need_decrease = false; // addpeer时候从init到on_snapshot_load整体限制
bool _can_heartbeat = false;
BthreadCond _multi_thread_cond;
// region stat variables
// TODO:num_table_lines维护太麻烦,后续要考虑使用预估的方式获取
std::atomic<int64_t> _num_table_lines; //total number of pk record in this region
std::atomic<int64_t> _num_delete_lines; //total number of delete rows after last compact
int64_t _snapshot_num_table_lines = 0; //last snapshot number
TimeCost _snapshot_time_cost;
int64_t _snapshot_index = 0; //last snapshot log index
bool _removed = false;
TimeCost _removed_time_cost;
TransactionPool _txn_pool;
RuntimeStatePool _state_pool;
// shared_ptr is not thread safe when assign
std::mutex _ptr_mutex;
std::shared_ptr<RegionResource> _resource;
RegionControl _region_control;
MetaWriter* _meta_writer = nullptr;
bthread::Mutex _commit_meta_mutex;
scoped_refptr<braft::FileSystemAdaptor> _snapshot_adaptor = nullptr;
bool _is_global_index = false; //是否是全局索引的region
std::mutex _reverse_index_map_lock;
std::mutex _backup_lock;
Backup _backup;
//binlog
bool _is_binlog_region = false; //是否为binlog region
std::atomic<int64_t> _binlog_read_max_ts = { 0 }; // 读取binlog的最大ts
// txn_id:commit_ts
std::map<uint64_t, int64_t> _commit_ts_map;
bthread::Mutex _commit_ts_map_lock;
bthread::Mutex _binlog_param_mutex;
BinlogParam _binlog_param;
std::string _rocksdb_start;
std::string _rocksdb_end;
pb::PeerStatus _region_status = pb::STATUS_NORMAL;
//learner
std::unique_ptr<braft::Learner> _learner;
bool _is_learner = false;
bool _learner_ready_for_read = false;
TimeCost _learner_time;
//NOT_LEADER分类报警
struct NotLeaderAlarm {
enum AlarmType {
ALARM_INIT = 0,
LEADER_INVALID = 1,
LEADER_RAFT_FALL_BEHIND = 2,
LEADER_NOT_REAL_START = 3
};
NotLeaderAlarm (int64_t region_id, const braft::PeerId& node_id) :
type(ALARM_INIT), region_id(region_id), node_id(node_id) { }
void reset() {
leader_start = false;
alarm_begin_time.reset();
last_print_time.reset();
total_count = 0;
interval_count = 0;
type = ALARM_INIT;
}
void set_leader_start() { leader_start = true; }
void not_leader_alarm(const braft::PeerId& leader_id);
AlarmType type;
std::atomic<bool> leader_start = { false };
std::atomic<int> total_count = { 0 };
std::atomic<int> interval_count = { 0 };
TimeCost alarm_begin_time;
TimeCost last_print_time; // 每隔一段时间打印报警日志
const int64_t region_id;
const braft::PeerId node_id;
};
NotLeaderAlarm _not_leader_alarm;
struct AsyncApplyParam {
std::atomic<bool> has_adjust_stall = { false };
// 异步apply如果失败了,置标记,下次async_apply_log rpc会返回error
// 以及在add_version会检查这个标记
bool apply_log_failed = false;
void start_adjust_stall() {
if (!has_adjust_stall) {
RocksWrapper::get_instance()->begin_split_adjust_option();
has_adjust_stall = true;
}
}
void stop_adjust_stall() {
if (has_adjust_stall) {
RocksWrapper::get_instance()->stop_split_adjust_option();
has_adjust_stall = false;
}
}
};
AsyncApplyParam _async_apply_param;
ExecutionQueue _async_apply_log_queue;
};
} // end of namespace
|
wy1433/BaikalDB
|
include/store/closure.h
|
// Copyright (c) 2018-present Baidu, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "common.h"
#include "region.h"
namespace baikaldb {
struct DMLClosure : public braft::Closure {
DMLClosure() : cond(nullptr) {};
DMLClosure(BthreadCond* cond) : cond(cond) {};
virtual void Run();
brpc::Controller* cntl = nullptr;
pb::OpType op_type;
pb::StoreRes* response = nullptr;
google::protobuf::Closure* done = nullptr;
Region* region = nullptr;
SmartTransaction transaction = nullptr;
TimeCost cost;
std::string remote_side;
BthreadCond* cond;
bool is_sync = false;
int64_t txn_num_increase_rows = 0;
int64_t applied_index = 0;
};
struct BinlogClosure : public braft::Closure {
BinlogClosure() : cond(nullptr) { };
BinlogClosure(BthreadCond* cond) : cond(cond) { };
virtual void Run() {
if (cond) {
cond->decrease_broadcast();
}
if (done) {
done->Run();
}
delete this;
}
std::string remote_side;
BthreadCond* cond;
TimeCost cost;
pb::StoreRes* response = nullptr;
google::protobuf::Closure* done = nullptr;
};
struct AddPeerClosure : public braft::Closure {
AddPeerClosure(BthreadCond& cond) : cond(cond) {};
virtual void Run();
Region* region;
std::string new_instance;
TimeCost cost;
google::protobuf::Closure* done = nullptr;
pb::StoreRes* response = nullptr;
BthreadCond& cond;
bool is_split = false;
};
struct MergeClosure : public braft::Closure {
virtual void Run();
pb::StoreRes* response = nullptr;
google::protobuf::Closure* done = nullptr;
Region* region = nullptr;
bool is_dst_region = false;
TimeCost cost;
};
struct SplitClosure : public braft::Closure {
virtual void Run();
std::function<void()> next_step;
Region* region;
std::string new_instance; // 第一个init region的instance
std::vector<std::string> add_peer_instance; // 后面add peer补齐副本数的instance
int64_t split_region_id;
std::string step_message;
pb::OpType op_type;
int ret = 0;
TimeCost cost;
};
struct ConvertToSyncClosure : public braft::Closure {
ConvertToSyncClosure(BthreadCond& _sync_sign,int64_t _region_id) :
sync_sign(_sync_sign), region_id(_region_id) {};
virtual void Run();
BthreadCond& sync_sign;
TimeCost cost;
int64_t region_id = 0;
};
struct SnapshotClosure : public braft::Closure {
virtual void Run() {
if (!status().ok()) {
DB_WARNING("region_id: %ld status:%s, snapshot failed.",
region->get_region_id(), status().error_cstr());
}
// 遇到部分请求报has no applied logs since last snapshot
// 不调用on_snapshot_save导致不更新_snapshot_time_cost等信息
if (region != nullptr) {
region->reset_snapshot_status();
}
cond.decrease_signal();
delete this;
}
SnapshotClosure(BthreadCond& cond, Region* reg) : cond(cond), region(reg) {}
BthreadCond& cond;
Region* region = nullptr;
int ret = 0;
//int retry = 0;
};
struct Dml1pcClosure : public braft::Closure {
Dml1pcClosure(BthreadCond& _txn_cond) : txn_cond(_txn_cond) {};
virtual void Run();
RuntimeState* state = nullptr;
SmartTransaction txn = nullptr;
BthreadCond& txn_cond;
google::protobuf::Closure* done = nullptr;
TimeCost cost;
};
} // end of namespace
|
wy1433/BaikalDB
|
include/meta_server/query_table_manager.h
|
// Copyright (c) 2018-present Baidu, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "table_manager.h"
namespace baikaldb {
class QueryTableManager {
public:
~QueryTableManager() {}
static QueryTableManager* get_instance() {
static QueryTableManager instance;
return &instance;
}
void get_schema_info(const pb::QueryRequest* request, pb::QueryResponse* response);
void get_flatten_schema(const pb::QueryRequest* request, pb::QueryResponse* response);
void get_flatten_table(const pb::QueryRequest* request, pb::QueryResponse* response);
void get_primary_key_string(int64_t table_id, std::string& primary_key_string);
void decode_key(int64_t table_id, const TableKey& start_key, std::string& start_key_string);
pb::PrimitiveType get_field_type(int64_t table_id,
int32_t field_id,
const pb::SchemaInfo& table_info);
void process_console_heartbeat(const pb::ConsoleHeartBeatRequest* request,
pb::ConsoleHeartBeatResponse* response, uint64_t log_id);
void get_ddlwork_info(const pb::QueryRequest* request, pb::QueryResponse* response);
void get_virtual_index_influence_info(const pb::QueryRequest* request, pb::QueryResponse* response);
private:
QueryTableManager() {}
void check_table_and_update(
const std::unordered_map<int64_t, std::tuple<pb::SchemaInfo, int64_t, int64_t>> table_schema_map,
std::unordered_map<int64_t, int64_t>& report_table_map,
pb::ConsoleHeartBeatResponse* response, uint64_t log_id);
void construct_query_table(const TableMem& table, pb::QueryTable* query_table);
}; //class
}//namespace
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
|
deguilardi/dacapobench
|
benchmarks/agent/c/src/dacapolog.c
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/time.h>
#include <jni.h>
#include "dacapolog.h"
#include "dacapooptions.h"
#include "dacapotag.h"
#include "dacapolock.h"
#include "dacapoallocation.h"
#include "dacapoexception.h"
#include "dacapomethod.h"
#include "dacapomonitor.h"
#include "dacapothread.h"
#include "dacapocallchain.h"
#include "zlib.h"
MonitorLockType lockLog;
MonitorLockType gcLock;
#define FILE_TYPE int
#define FILE_IS_CLOSED -1
#ifdef O_LARGEFILE
#define FILE_FLAGS (O_WRONLY | O_CREAT | O_LARGEFILE)
#else
#define FILE_FLAGS (O_WRONLY | O_CREAT)
#endif
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
#define GZ_FILE_MODE "w"
#define GZ_BUFFER_SIZE (128*1024)
FILE_TYPE logFile = FILE_IS_CLOSED;
gzFile gzLogFile;
jboolean gzLog = FALSE;
jboolean logState = TRUE;
jboolean localInitDone = FALSE;
struct timeval startTime;
jclass log_java_class = NULL;
jmethodID reportHeapID;
jfieldID firstReportSinceForceGCID;
jfieldID agentIntervalTimeID;
jfieldID callChainCountID;
jfieldID callChainFrequencyID;
jfieldID callChainEnableID;
#define LOG_FILE_NAME_MAX 10000
#define LOG_FILE_EXT_MAX 10000
#define SEQUENCE_MAX 100
#define LOG_FILE_LIMIT (1<<30)
char baseLogFileName[LOG_FILE_NAME_MAX];
char baseLogFileExt[LOG_FILE_EXT_MAX];
int fileNameSequence = 0;
long logFileSequenceLength = 0;
jboolean check_limit = FALSE;
#define BUFFER_SIZE 16384
struct buffer_s {
struct buffer_s* next;
char* buffer;
int buffer_len;
int buffer_pos;
} *buffer_head = NULL;
static void log_close() {
if (gzLog)
gzclose(gzLogFile);
close(logFile);
logFile = FILE_IS_CLOSED;
}
static void log_open(const char* f) {
FILE_TYPE tmp = logFile;
gzFile tmpgz = gzLogFile;
logFile = open(f,FILE_FLAGS,FILE_MODE);
if (gzLog) {
gzFile localtmpgz = gzdopen(logFile,GZ_FILE_MODE);
gzbuffer(localtmpgz, GZ_BUFFER_SIZE);
gzLogFile = localtmpgz;
}
if (tmp != FILE_IS_CLOSED) {
if (gzLog) gzclose(tmpgz);
close(tmp);
}
}
static void log_flush() {
return;
}
static void log_write(struct buffer_s* b) {
if (gzLog) {
logFileSequenceLength += gzwrite(gzLogFile,b->buffer,sizeof(char)*(b->buffer_pos));
} else {
logFileSequenceLength += write(logFile,b->buffer,sizeof(char)*(b->buffer_pos));
}
}
static void openLogFile() {
char logFileName[LOG_FILE_NAME_MAX+SEQUENCE_MAX];
int fileSeq = fileNameSequence++;
if (strlen(baseLogFileExt)==0) {
if (gzLog)
sprintf(logFileName,"%s-%d.gz",baseLogFileName,fileSeq);
else
sprintf(logFileName,"%s-%d",baseLogFileName,fileSeq);
} else {
if (gzLog)
sprintf(logFileName,"%s-%d.%s.gz",baseLogFileName,fileSeq,baseLogFileExt);
else
sprintf(logFileName,"%s-%d.%s",baseLogFileName,fileSeq,baseLogFileExt);
}
log_open(logFileName);
logFileSequenceLength = 0;
}
_Bool logFileOpen() {
return logFile != FILE_IS_CLOSED;
}
void dacapo_log_stop() {
if (logFile != FILE_IS_CLOSED)
log_close();
}
void setLogFileName(const char* log_file) {
dacapo_log_stop();
int ext = strlen(log_file);
while (0<ext && log_file[ext]!='.') ext--;
if (0<ext) {
strncpy(baseLogFileName,log_file,(ext<(LOG_FILE_NAME_MAX-1))?ext:(LOG_FILE_NAME_MAX-1));
strncpy(baseLogFileExt,log_file+ext+1,SEQUENCE_MAX-1);
baseLogFileExt[SEQUENCE_MAX-1] = '\0';
} else {
strcpy(baseLogFileName,log_file);
baseLogFileExt[0]='\0';
}
fileNameSequence = 0;
logFileSequenceLength = 0;
openLogFile(log_file);
}
void callReportHeap(JNIEnv *env) {
(*env)->CallStaticVoidMethod(env,log_java_class,reportHeapID);
}
void setReportHeap(JNIEnv *env, jboolean flag) {
rawMonitorEnter(&gcLock);
if (localInitDone)
(*env)->SetStaticBooleanField(env,log_java_class,firstReportSinceForceGCID,flag);
rawMonitorExit(&gcLock);
}
void setReportCallChain(JNIEnv *env, jlong frequency, jboolean enable) {
if (localInitDone) {
if (enable) {
(*env)->SetStaticLongField(env,log_java_class,callChainFrequencyID,frequency);
(*env)->SetStaticLongField(env,log_java_class,callChainCountID,(jlong)0);
}
(*env)->SetStaticBooleanField(env,log_java_class,callChainEnableID,enable);
}
}
_Bool dacapo_log_init() {
if (!rawMonitorInit(baseEnv,"agent data",&lockLog)) {
/* JVMTI_FUNC_PTR(baseEnv,CreateRawMonitor)(baseEnv, "agent data", &(lockLog)) != JNI_OK) */
return FALSE;
}
if (!rawMonitorInit(baseEnv,"gc lock",&gcLock)) {
/* JVMTI_FUNC_PTR(baseEnv,CreateRawMonitor)(baseEnv, "gc lock", &(gcLock)) != JNI_OK) { */
return FALSE;
}
if (isSelected(OPT_LOG_FILE_LIMIT,NULL)) {
check_limit = TRUE;
}
if (isSelected(OPT_LOG_FILE_GZIP,NULL)) {
gzLog = TRUE;
}
/* make log file */
char* tmpFile = NULL;
if (isSelected(OPT_LOG_FILE,&tmpFile)) {
setLogFileName(tmpFile);
if (tmpFile != NULL) {
free(tmpFile);
tmpFile = NULL;
}
}
gettimeofday(&startTime, NULL);
return TRUE;
}
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_internalLocalInit
(JNIEnv *env, jclass klass)
{
reportHeapID = (*env)->GetStaticMethodID(env,klass,"reportHeap","()V");
firstReportSinceForceGCID = (*env)->GetStaticFieldID(env,klass,"firstReportSinceForceGC","Z");
agentIntervalTimeID = (*env)->GetStaticFieldID(env,klass,"agentIntervalTime","J");
callChainCountID = (*env)->GetStaticFieldID(env,klass,"callChainCount","J");
callChainFrequencyID = (*env)->GetStaticFieldID(env,klass,"callChainFrequency","J");
callChainEnableID = (*env)->GetStaticFieldID(env,klass,"callChainEnable","Z");
log_java_class = (*env)->NewGlobalRef(env, klass);
char* tmp = NULL;
if (isSelected(OPT_INTERVAL,&tmp)) {
int value = atoi(tmp);
if (value > 0)
(*env)->SetStaticLongField(env,log_java_class,agentIntervalTimeID,(jlong)value);
free(tmp);
}
localInitDone = !FALSE;
}
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_wierd
(JNIEnv *env, jclass klass)
{
fprintf(stderr,"Agent_wierd[start]\n");
callReportHeap(env);
fprintf(stderr,"Agent_wierd[stop]\n");
}
/*
* Class: org_dacapo_instrument_Agent
* Method: available
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_org_dacapo_instrument_Agent_internalAvailable
(JNIEnv *env, jclass klass)
{
return !FALSE;
}
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_internalLogThread
(JNIEnv *env, jclass klass, jobject thread)
{
thread_agent_log(env, klass, thread);
}
/*
* Class: org_dacapo_instrument_Agent
* Method: log
* Signature: (Ljava/lang/Thread;Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_internalLog
(JNIEnv *env, jclass klass, jobject thread, jstring e, jstring m)
{
if (logState) {
jniNativeInterface* jni_table = JNIFunctionTable();
jboolean iscopy_e;
jboolean iscopy_m;
jlong thread_tag = 0;
jlong thread_klass_tag = 0;
jclass thread_klass = JVM_FUNC_PTR(jni_table,GetObjectClass)(env,thread);
jboolean new_thread_tag;
rawMonitorEnter(&lockTag);
jboolean thread_has_new_tag = getTag(thread, &thread_tag);
jboolean thread_klass_has_new_tag = getTag(thread_klass, &thread_klass_tag);
rawMonitorExit(&lockTag);
const char *c_e = JVMTI_FUNC_PTR(env,GetStringUTFChars)(env, e, &iscopy_e);
const char *c_m = JVMTI_FUNC_PTR(env,GetStringUTFChars)(env, m, &iscopy_m);
rawMonitorEnter(&lockLog);
void* buffer = log_buffer_get();
log_field_string(buffer, c_e);
log_field_current_time(buffer);
log_thread(buffer, thread, thread_tag, thread_has_new_tag, thread_klass, thread_klass_tag, thread_klass_has_new_tag);
log_field_string(buffer, c_m);
log_eol(buffer);
rawMonitorExit(&lockLog);
JVMTI_FUNC_PTR(env,ReleaseStringUTFChars)(env, e, c_e);
JVMTI_FUNC_PTR(env,ReleaseStringUTFChars)(env, m, c_m);
}
}
/*
* Class: org_dacapo_instrument_Agent
* Method: setLogFileName
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_internalSetLogFileName
(JNIEnv *env, jclass klass, jstring s)
{
jboolean iscopy;
const char *m = JVMTI_FUNC_PTR(env,GetStringUTFChars)(env, s, &iscopy);
setLogFileName(m);
JVMTI_FUNC_PTR(env,ReleaseStringUTFChars)(env, s, m);
}
/*
* Class: org_dacapo_instrument_Agent
* Method: start
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_internalStart
(JNIEnv *env, jclass klass)
{
if (!logState) {
logState = logFile != FILE_IS_CLOSED;
if (logState) {
rawMonitorEnter(&lockLog);
void* buffer = log_buffer_get();
log_field_string(buffer, LOG_PREFIX_START);
log_field_current_time(buffer);
log_eol(buffer);
rawMonitorExit(&lockLog);
allocation_logon(env);
exception_logon(env);
method_logon(env);
monitor_logon(env);
thread_logon(env);
call_chain_logon(env);
}
}
}
/*
* Class: org_dacapo_instrument_Agent
* Method: stop
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_internalStop
(JNIEnv *env, jclass klass)
{
jboolean tmp = logState;
logState = FALSE;
if (tmp) {
rawMonitorEnter(&lockLog);
void* buffer = log_buffer_get();
log_field_string(buffer, LOG_PREFIX_STOP);
log_field_current_time(buffer);
log_eol(buffer);
rawMonitorExit(&lockLog);
}
}
/*
* Class: org_dacapo_instrument_Agent
* Method: logCallChain
* Signature: (Ljava/lang/Thread;)V
*/
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_internalLogCallChain
(JNIEnv *env, jclass klass, jobject thread) {
log_call_chain(env, klass, thread);
}
/*
* Class: org_dacapo_instrument_Agent
* Method: writeHeapReport
* Signature: (JJJJ)V
*/
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_internalHeapReport(JNIEnv *local_env, jclass klass, jobject thread, jlong used, jlong free, jlong total, jlong max) {
jniNativeInterface* jni_table = JNIFunctionTable();
jlong thread_tag = 0;
jclass thread_klass = JVM_FUNC_PTR(jni_table,GetObjectClass)(local_env,thread);
jlong thread_klass_tag = 0;
rawMonitorEnter(&lockTag);
jboolean thread_has_new_tag = getTag(thread, &thread_tag);
jboolean thread_klass_has_new_tag = getTag(thread_klass, &thread_klass_tag);
rawMonitorExit(&lockTag);
rawMonitorEnter(&lockLog);
void* buffer = log_buffer_get();
log_field_string(buffer, LOG_PREFIX_HEAP_REPORT);
log_field_current_time(buffer);
log_thread(buffer, thread, thread_tag, thread_has_new_tag, thread_klass, thread_klass_tag, thread_klass_has_new_tag);
log_field_jlong(buffer, used);
log_field_jlong(buffer, free);
log_field_jlong(buffer, total);
log_field_jlong(buffer, max);
log_eol(buffer);
rawMonitorExit(&lockLog);
return;
}
/*
*/
static _Bool first_field = TRUE;
static char field_separator = ',';
static char field_delimiter = '\"';
static char end_of_line = '\n';
/* */
void* log_buffer_get() {
struct buffer_s* buffer = NULL;
if (buffer_head == NULL) {
buffer = (struct buffer_s*)malloc(sizeof(struct buffer_s));
buffer->buffer = (char*)malloc(sizeof(char)*BUFFER_SIZE);
buffer->buffer_len = BUFFER_SIZE;
} else {
buffer = buffer_head;
buffer_head = buffer_head->next;
}
buffer->buffer_pos = 0;
return buffer;
}
void log_buffer_put(void* buffer) {
((struct buffer_s*)buffer)->next = buffer_head;
buffer_head = (struct buffer_s*)buffer;
}
void log_buffer_ensure_space(struct buffer_s* b, int size) {
if ((b->buffer_len - b->buffer_pos) < 0) {
char* tmp = (char*)malloc(sizeof(char)*(2*b->buffer_len));
memcpy(tmp, b->buffer, sizeof(char)*b->buffer_len);
free(b->buffer);
b->buffer = tmp;
}
}
static void write_field(struct buffer_s* buffer, const char* text, int text_length, _Bool use_delimiter) {
if (first_field) {
first_field = FALSE;
} else {
log_buffer_ensure_space(buffer, 1);
buffer->buffer[buffer->buffer_pos++] = field_separator;
}
if (use_delimiter) {
log_buffer_ensure_space(buffer, 1);
buffer->buffer[buffer->buffer_pos++] = field_delimiter;
if (text!=NULL) {
int i;
for(i=0; i<text_length;++i) {
log_buffer_ensure_space(buffer, 2);
if (text[i]==field_delimiter)
buffer->buffer[buffer->buffer_pos++] = field_delimiter;
buffer->buffer[buffer->buffer_pos++] = text[i];
}
}
log_buffer_ensure_space(buffer, 1);
buffer->buffer[buffer->buffer_pos++] = field_delimiter;
} else {
if(text!=NULL && 0<text_length) {
log_buffer_ensure_space(buffer, text_length);
strncpy(buffer->buffer+buffer->buffer_pos,text,text_length);
buffer->buffer_pos += text_length;
}
}
}
void log_field_string(void* buffer, const char* text) {
if (text==NULL)
write_field((struct buffer_s*)buffer,NULL,0,TRUE);
else {
int text_length = 0;
_Bool use_delimiter = FALSE;
while(text[text_length]!='\0') {
use_delimiter = text[text_length]==field_delimiter || text[text_length]==field_separator;
++text_length;
}
write_field((struct buffer_s*)buffer, text,text_length,use_delimiter);
}
}
void log_field_jboolean(void* buffer, jboolean v) {
log_field_string(buffer, v?"true":"false");
}
void log_field_int(void* buffer, int v) {
char tmp[32];
sprintf(tmp,"%d",v);
log_field_string(buffer, tmp);
}
void log_field_jint(void* buffer, jint v) {
char tmp[32];
sprintf(tmp,"%" FORMAT_JINT,v);
log_field_string(buffer, tmp);
}
void log_field_jlong(void* buffer, jlong v) {
char tmp[64];
sprintf(tmp,"%" FORMAT_JLONG,v);
log_field_string(buffer, tmp);
}
void log_field_long(void* buffer, long v) {
char tmp[64];
sprintf(tmp,"%ld",v);
log_field_string(buffer, tmp);
}
void log_field_pointer(void* buffer, const void* p) {
char tmp[64];
sprintf(tmp,"%" FORMAT_PTR, PTR_CAST(p));
log_field_string(buffer, tmp);
}
void log_field_string_n(void* buffer, const char* text, int field_length) {
int i;
_Bool use_delimiter = FALSE;
for(i=0; i<field_length && !use_delimiter; ++i) {
use_delimiter = text[i]==field_delimiter || text[i]==field_separator;
}
write_field((struct buffer_s*)buffer,text,field_length,use_delimiter);
}
void log_thread(void* buffer, jthread thread, jlong thread_tag, jboolean thread_has_new_tag, jobject klass, jlong klass_tag, jboolean klass_has_new_tag) {
log_field_jlong(buffer, thread_tag);
if (thread_has_new_tag) {
jniNativeInterface* jni_table = JNIFunctionTable();
// get thread name.
jvmtiThreadInfo info;
JVMTI_FUNC_PTR(baseEnv,GetThreadInfo)(baseEnv, thread, &info);
log_field_string(buffer, info.name);
if (info.name!=NULL) JVMTI_FUNC_PTR(baseEnv,Deallocate)(baseEnv,(unsigned char*)info.name);
} else {
log_field_string(buffer, NULL);
}
log_class(buffer, klass, klass_tag, klass_has_new_tag);
}
void log_class(void* buffer, jobject klass, jlong klass_tag, jboolean klass_has_new_tag) {
log_field_jlong(buffer, klass_tag);
if (klass_has_new_tag) {
jniNativeInterface* jni_table = JNIFunctionTable();
char* signature = NULL;
char* generic = NULL;
JVMTI_FUNC_PTR(baseEnv,GetClassSignature)(baseEnv,klass,&signature,&generic);
log_field_string(buffer, signature);
if (signature!=NULL) JVMTI_FUNC_PTR(baseEnv,Deallocate)(baseEnv,(unsigned char*)signature);
if (generic!=NULL) JVMTI_FUNC_PTR(baseEnv,Deallocate)(baseEnv,(unsigned char*)generic);
} else {
log_field_string(buffer, NULL);
}
}
void log_field_time(void* buffer, struct timeval* tv) {
jlong t = ((jlong)(tv->tv_sec - startTime.tv_sec)) * (jlong)1000000 + (tv->tv_usec - startTime.tv_usec);
log_field_jlong(buffer, t);
}
void log_field_current_time(void* buffer) {
struct timeval tv;
gettimeofday(&tv, NULL);
log_field_time(buffer, &tv);
}
void log_eol(void* buffer) {
if (logFile == FILE_IS_CLOSED) {
fprintf(stderr,"LOG_FILE IS CLOSED\n");
exit(10);
}
struct buffer_s* b = buffer;
log_buffer_ensure_space(b, 1);
b->buffer[b->buffer_pos++] = end_of_line;
log_write(b);
first_field = TRUE;
log_flush();
log_buffer_put(b);
if (check_limit && LOG_FILE_LIMIT <= logFileSequenceLength) {
openLogFile();
}
}
/*
* Class: org_dacapo_instrument_Agent
* Method: agentThread
* Signature: (Ljava/lang/Thread;)V
*/
JNIEXPORT void JNICALL Java_org_dacapo_instrument_Agent_agentThread(JNIEnv *env, jclass klass, jobject thread) {
threads_states(env);
}
|
chidanta-shu/stitching
|
mosaic/mosaic.h
|
#pragma once
#ifdef MOSAIC_EXPORTS
#define MOSAIC_API __declspec(dllexport)
#else
#define MOSAIC_API __declspec(dllimport)
#endif
#define PI (3.1415926535897932384626)
#define TO_ANG(x) (180.0*x/PI)
#define TO_RAD(x) (PI*x/180.0)
|
chidanta-shu/stitching
|
mosaic/ColorCorrection.h
|
<gh_stars>0
#pragma once
#include <iostream>
#include <opencv2/opencv.hpp>
#include <cassert>
#include <vector>
#include <cmath>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define num_img 2 /*6*/ // 更新2
//#define gr = 2
using namespace cv;
using namespace std;
struct GOMY
{
vector<float> Bi;
vector<float> Sicb;
vector<float> Sicr;
//待定值
int w = 0;
int h = 0;
};
struct minhang
{
float mindiff = 0;
int seamindex = 0;
};
GOMY get_overlap_mean_yuv(Mat img1, Mat img2, int shift_x, int shift_y);
vector<float> getCorrParameters(vector<vector<float> > B);
minhang minhh(vector<vector<float> > a, int m);
Mat RGB2YUV0(Mat src);
Mat YUV2RGB0(Mat src);
void Color_correction(Mat *im1, Mat *im2);
|
chidanta-shu/stitching
|
mosaic/CameraCalib.h
|
#pragma once
#include <iostream>
#include"mosaic.h"
class MOSAIC_API CameraCalib
{
public:
static int initcalibfile(std::string calibconfigpath, std::string imagelistpath,int outid=0);
static int calibmain(std::string name, int winsize = 11, float dsize = -1);
};
|
Ex05/herder
|
src/que.c
|
#ifndef QUE_C
#define QUE_C
#include "que.h"
local void que_initQueElement(QueElement*, void*);
local void que_freeQueElement(QueElement*);
inline ERROR_CODE que_init(Que* que){
memset(que, 0, sizeof(*que));
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE que_enque(Que* que, void* value){
if(value == NULL){
return -1;
}
if(que->tail == NULL){
QueElement* queElement = malloc(sizeof(*queElement));
if(queElement == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
que_initQueElement(queElement, value);
que->tail = que->head = queElement;
}
else{
QueElement* queElement = malloc(sizeof(*queElement));
if(queElement == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
que_initQueElement(queElement, value);
QueElement* next = queElement;
que->head->next = next;
que->head = next;
}
que->len++;
return ERROR(ERROR_NO_ERROR);
}
inline void* que_deque(Que* que){
if(que->tail == NULL){
return NULL;
}
QueElement* tail = que->tail;
void* value = tail->value;
que->tail = tail->next;
que_freeQueElement(tail);
que->len--;
return value;
}
inline void que_initQueElement(QueElement* queElement, void* value){
queElement->next = NULL;
queElement->value = value;
}
inline void que_freeQueElement(QueElement* queElement){
free(queElement);
}
inline void que_clear(Que* que){
while(que_deque(que));
}
#endif
|
Ex05/herder
|
src/arrayList.h
|
<filename>src/arrayList.h
#ifndef ARRAY_LIST_H
#define ARRAY_LIST_H
#include "util.h"
#define ARRAY_LIST_IS_EMPTY(list)(list->length == 0)
#define ARRAY_LIST_LENGTH(list)((list)->length)
#define ARRAY_LIST_ITERATOR_HAS_NEXT(it)(arrayList_iteratorHasNext(it))
#define ARRAY_LIST_INIT_FIXED_SIZE_STACK_LIST(list, initialSize, stride) do{ \
arrayList_init_(list, initialSize, stride, NULL);\
list->elements = alloca(stride * list->maxLength);\
} while(0)
#define ARRAY_LIST_GET(list, index, type) ((type*) (list)->elements)[index]
#define ARRAY_LIST_GET_PTR(list, index, type) &(((type*)(list)->elements)[index])
#define ARRAY_LIST_ADD(list, value, type) do{ \
if((list)->length == (list)->maxLength){ \
ERROR_CODE error; \
if((error = arrayList_expandList((list))) != ERROR_NO_ERROR){ \
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error)); \
} \
} \
\
((type*)(list)->elements)[(list)->length] = value; \
(list)->length++; \
\
ERROR(ERROR_NO_ERROR); \
} while(0)
#define ARRAY_LIST_ADD_PTR(list, value, type) do{ \
if((list)->length == (list)->maxLength){ \
ERROR_CODE error; \
if((error = arrayList_expandList((list))) != ERROR_NO_ERROR){ \
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error)); \
} \
} \
\
memcpy(&((type*)(list)->elements)[(list)->length], value, sizeof(type)); \
(list)->length++; \
\
ERROR(ERROR_NO_ERROR); \
} while(0)
#define ARRAY_LIST_ITERATOR_NEXT(it, type) ARRAY_LIST_GET((it)->list, (it)->index++, type)
#define ARRAY_LIST_EXPAND_FUNCTION(functionName) uint_fast64_t functionName(const uint_fast16_t expansions, const uint_fast64_t previousSize)
typedef ARRAY_LIST_EXPAND_FUNCTION(ArrayList_ExpandFunction);
typedef struct{
void* elements;
uint_fast64_t stride;
uint_fast64_t length;
uint_fast64_t maxLength;
uint_fast64_t expansions;
ArrayList_ExpandFunction* expandFunction;
}ArrayList;
typedef struct{
ArrayList* list;
uint_fast64_t index;
}ArrayListIterator;
ERROR_CODE arrayList_init(ArrayList*, const uint_fast64_t, const uint_fast64_t, ArrayList_ExpandFunction*);
ERROR_CODE arrayList_initFixedSizeList(ArrayList*, const uint_fast64_t, const uint_fast64_t);
void arrayList_initIterator(ArrayListIterator*, ArrayList*);
void arrayList_iteratorSetBeginIndex(ArrayListIterator*, const uint_fast64_t);
int_fast32_t arrayList_iteratorHasNext(ArrayListIterator*);
void* arrayList_iteratorNext(ArrayListIterator*);
void arrayList_free(ArrayList*);
#endif
|
Ex05/herder
|
src/argumentParser.c
|
<reponame>Ex05/herder
#ifndef ARGUMENT_PARSER_C
#define ARGUMENT_PARSER_C
#include "argumentParser.h"
#include "linkedList.c"
// Note:(jan) If the value of an argument points to this flag, then the Argument was present, but had no value assosiatet with it. e.g: ('--help', '-?') as opposed to ("--setImportDirectory '/herder/import'")
char ARGUMENT_PARSER_ARGUMENT_PRESENT_FLAG = {0};
local ERROR_CODE argumentParser_initArgument(Argument*, const uint_fast8_t);
local bool argumentParser_isArgument(const char*);
inline ERROR_CODE argumentParser_init(ArgumentParser* parser){
int_fast32_t error;
if((error = linkedList_init(&parser->arguments)) != 0){
UTIL_LOG_ERROR_("Failed to initialise argument list [%" PRIdFAST32 "]", error);
return ERROR(error);
}
return ERROR(error);
}
inline ERROR_CODE argumentParser_initArgument(Argument* argument, const uint_fast8_t numArguments){
memset(argument, 0, sizeof(*argument));
argument->numArguments = numArguments;
argument->arguments = malloc(sizeof(*argument->arguments) * numArguments);
if(argument->arguments == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE argumentParser_addArgument(ArgumentParser* parser, Argument* argument, const uint_fast8_t numArguments, ...){
argumentParser_initArgument(argument, numArguments);
va_list args;
va_start(args, numArguments);
register uint_fast8_t i;
for(i = 0; i < numArguments; i++){
const char* s = va_arg(args, char*);
const uint_fast64_t strLength = strlen(s);
argument->arguments[i] = malloc(sizeof(*argument->arguments[i]) * (strLength + 1));
if(argument->arguments[i] == NULL){
va_end(args);
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(argument->arguments[i], s, strLength + 1);
}
linkedList_add(&parser->arguments, argument);
va_end(args);
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE argumentParser_parse(ArgumentParser* parser, const int numArguments, const char** arguments){
if(numArguments <= 1){
return ERROR(ERROR_NO_VALID_ARGUMENT);
}
LinkedListIterator it;
register int i;
for(i = 0; i < numArguments; i++){
linkedList_initIterator(&it, &parser->arguments);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Argument* argument = LINKED_LIST_ITERATOR_NEXT(&it);
register uint_fast8_t j;
for(j = 0; j < argument->numArguments; j++){
if(strcmp(arguments[i], argument->arguments[j]) == 0){
if(argument->numValues != 0 || (argument->values != NULL && argument->values[0] == &ARGUMENT_PARSER_ARGUMENT_PRESENT_FLAG)){
return ERROR(ERROR_DUPLICATE_ENTRY);
}
void* values = realloc(argument->values, sizeof(*argument->values) * (argument->numValues + 1));
if(values == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
argument->values = values;
void* valueLengths = realloc(argument->valueLengths, sizeof(*argument->valueLengths) * (argument->numValues + 1));
if(valueLengths == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
argument->valueLengths = valueLengths;
// No more arguments.
if(i + 1 >= numArguments){
argument->values[argument->numValues] = &ARGUMENT_PARSER_ARGUMENT_PRESENT_FLAG;
argument->valueLengths[argument->numValues] = 0;
}else{
// As long as we have arguments.
while(i + 1 < numArguments){
// If the next argument is actually not an argument.
if(!argumentParser_isArgument(arguments[i + 1])){
argument->values[argument->numValues] = arguments[i + 1];
argument->valueLengths[argument->numValues] = strlen(arguments[i + 1]);
argument->numValues += 1;
i += 1;
// Continue if we have more than one value to an argument, e.g. '--rename "/home/29a" "/home/ex05"'
if(i + 1 < numArguments && !argumentParser_isArgument(arguments[i + 1])){
void* values = realloc(argument->values, sizeof(*argument->values) * (argument->numValues + 1));
if(values == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
argument->values = values;
void* valueLengths = realloc(argument->valueLengths, sizeof(*argument->valueLengths) * (argument->numValues + 1));
if(valueLengths == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
argument->valueLengths = valueLengths;
}else{
break;
}
}else{
argument->values[argument->numValues] = &ARGUMENT_PARSER_ARGUMENT_PRESENT_FLAG;
argument->valueLengths[argument->numValues] = 0;
break;
}
}
}
}
}
}
}
return ERROR(ERROR_NO_ERROR);
}
inline bool argumentParser_contains(ArgumentParser* parser, Argument* argument){
LinkedListIterator it;
linkedList_initIterator(&it, &parser->arguments);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
const Argument* _argument = LINKED_LIST_ITERATOR_NEXT(&it);
if(argument == _argument && (_argument->numValues != 0 || ( _argument->values != NULL &&_argument->values[0] == &ARGUMENT_PARSER_ARGUMENT_PRESENT_FLAG))){
return true;
}
}
return false;
}
inline bool argumentParser_isArgument(const char* s){
return s[0] == '-' || (s[0] == '-' && s[1] == '-');
}
void argumentParser_free(ArgumentParser* parser){
LinkedListIterator it;
linkedList_initIterator(&it, &parser->arguments);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Argument* argument = LINKED_LIST_ITERATOR_NEXT(&it);
register uint_fast8_t i;
for(i = 0; i < argument->numArguments; i++){
free(argument->arguments[i]);
}
free(argument->arguments);
free(argument->values);
free(argument->valueLengths);
}
linkedList_free(&parser->arguments);
}
#endif
|
Ex05/herder
|
src/herder.h
|
<gh_stars>0
#ifndef HERDER_H
#define HERDER_H
#include "util.h"
#include "mediaLibrary.h"
#define HERDER_CONSTRUCT_RELATIVE_FILE_PATH(path, stringLength, episodeInfo) \
char* _noWhiteSpaceShowName = alloca(sizeof(*_noWhiteSpaceShowName) * ((episodeInfo)->showNameLength + 1)); \
strncpy(_noWhiteSpaceShowName, (episodeInfo)->showName, (episodeInfo)->showNameLength + 1); \
util_replaceAllChars(_noWhiteSpaceShowName, ' ', '_'); \
*stringLength = ((episodeInfo)->showNameLength * 3) + ((episodeInfo)->nameLength) + (3/*" - "*/ + 7/*"Season_"*/ + 2/*"/"*/) + (UTIL_UINT16_STRING_LENGTH * 3) + 1/*.*/ + (episodeInfo)->fileExtensionLength; \
\
*(path) = alloca(sizeof(**(path)) * (*stringLength + 1)); \
*stringLength = snprintf(*path, *stringLength, "%s/%s - Season_%02" PRIdFAST16 "/%s_s%02" PRIdFAST16 "e%02" PRIdFAST16 "_%s.%s", _noWhiteSpaceShowName, _noWhiteSpaceShowName, (episodeInfo)->season, _noWhiteSpaceShowName, (episodeInfo)->season, (episodeInfo)->episode, (episodeInfo)->name, (episodeInfo)->fileExtension); \
\
util_replaceAllChars(*path + (*stringLength - ((episodeInfo)->showNameLength + (2 * UTIL_UINT16_STRING_LENGTH) + (episodeInfo)->nameLength + 4)), ' ', '_')
ERROR_CODE herder_removeShow(Property*, Property*, const char*, const uint_fast64_t);
ERROR_CODE herder_pullShowList(LinkedList*, Property*, Property*);
ERROR_CODE herder_addShow(Property*, Property*, const char*, const uint_fast64_t);
ERROR_CODE herder_extractShowInfo(Property*, Property*, EpisodeInfo*);
ERROR_CODE herder_addEpisode(Property*, Property*, Property*, EpisodeInfo*);
ERROR_CODE herder_pullShowInfo(Property*, Property*, Show*);
ERROR_CODE herder_add(Property*, Property*, Property*, EpisodeInfo*);
ERROR_CODE herder_renameEpisode(Property*, Property*, Property*, EpisodeInfo*, const char*, const uint_fast64_t);
ERROR_CODE herder_convertToMP3(Property*, Property*, Property*, const char*, const uint_fast64_t);
#endif
|
Ex05/herder
|
src/pls.h
|
#ifndef PLS_H
#define PLS_H
#include "util.h"
#include "propertyFile.h"
#include "mediaLibrary.h"
ERROR_CODE pls_savePlayList(Property*, const char*, Show*);
#endif
/*
[playlist]
File1=http://relay5.181.fm:8068
Length1=-1
File2=example2.mp3
Title2=Just some local audio that is 2mins long
Length2=120
File3=F:\Music\whatever.m4a
Title3=absolute path on Windows
File4=%UserProfile%\Music\short.ogg
Title4=example for an Environment variable
Length4=5
NumberOfEntries=4
Version=2
*/
|
Ex05/herder
|
src/propertyFile.h
|
<reponame>Ex05/herder
#ifndef PROPERTY_FILE_H
#define PROPERTY_FILE_H
#include "util.h"
#include "linkedList.h"
#define PROPERTY_IS_NOT_SET(property) (property == NULL)
#define PROPERTY_IS_SET(property) (property != NULL)
typedef struct{
uint_fast8_t release;
uint_fast8_t update;
uint_fast8_t hotfix;
}Version;
typedef struct{
FILE* file;
Version version;
uint_fast8_t maxPageEntries;
LinkedList pages;
}PropertyFile;
typedef struct{
uint_fast64_t nameOffset;
uint_fast64_t nameLength;
uint_fast64_t entryOffset;
uint_fast64_t dataOffset;
uint_fast64_t length;
char* name;
}PropertyFileEntry;
typedef struct{
PropertyFileEntry** entries;
uint_fast64_t offset;
}PropertyPage;
typedef struct{
PropertyFileEntry* entry;
PropertyFile* callBack;
int_fast8_t* buffer;
}Property;
ERROR_CODE propertyFile_init(PropertyFile*, const char*);
ERROR_CODE propertyFile_create(const char*, const uint_fast8_t);
ERROR_CODE propertyFile_getProperty(PropertyFile*, Property**, const char*);
void propertyFile_free(PropertyFile*);
void propertyFile_freeProperty(Property*);
ERROR_CODE propertyFile_addProperty(PropertyFile*, Property**, const char*, const uint_fast64_t);
ERROR_CODE propertyFile_setBuffer(Property*, int_fast8_t*);
ERROR_CODE propertyFile_removeProperty(Property*);
bool propertyFile_contains(PropertyFile*, const char*);
ERROR_CODE propertyFile_propertySet(Property*, const char*);
ERROR_CODE propertyFile_createAndSetDirectoryProperty(PropertyFile*, Property**, const char*, const char*, const uint_fast64_t);
ERROR_CODE propertyFile_createAndSetStringProperty(PropertyFile*, Property**, const char*, const char*, const uint_fast64_t);
ERROR_CODE propertyFile_createAndSetUINT16Property(PropertyFile*, Property**, const char*, const uint16_t);
ERROR_CODE propertyFile_createProperty(PropertyFile*, Property**, const char*, const uint_fast64_t);
#endif
/*
Version: 3 bytes
Max_Page_Entries: 1 byte
########################
# Page_0: #
# #
# Entry_0:{ #
# Name_Size: 8 bytes #
# Name_Offset: 8 bytes #
# Data_Size: 8 bytes #
# Data_Offset: 8 bytes #
# } #
# Next_Page: 8 bytes #
########################
Show_Name,
Episode_Name,
Path,
Season,
Episode,
*/
|
Ex05/herder
|
src/http.c
|
<filename>src/http.c
#ifndef HTTP_C
#define HTTP_C
#include "http.h"
#include "linkedList.c"
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <strings.h>
inline ERROR_CODE http_initRequest(HTTP_Request* request, const char* url, const uint_fast64_t urlLength, void* buffer, const uint_fast64_t bufferSize, const char version[] , const HTTP_RequestType requestType){
ERROR_CODE error;
if((error = http_initRequest_(request, buffer, bufferSize, requestType)) != ERROR_NO_ERROR){
return ERROR(error);
}
http_setHTTP_Version((HTTP_Response*)(request), version);
request->urlLength = urlLength;
request->requestURL = malloc(sizeof(request->requestURL) * (urlLength + 1));
if(request->requestURL == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(request->requestURL, url, urlLength);
request->requestURL[urlLength] = '\0';
return ERROR(error);
}
inline ERROR_CODE http_initRequest_(HTTP_Request* request, void* buffer, const uint_fast64_t bufferSize, const HTTP_RequestType requestType){
memset(request, 0, sizeof(*request));
request->data = buffer;
request->bufferSize = bufferSize;
ERROR_CODE error;
error = linkedList_init(&request->headerFields);
request->type = requestType;
return ERROR(error);
}
inline ERROR_CODE http_initResponse(HTTP_Response* response, void* buffer, const uint_fast64_t bufferSize){
memset(response, 0, sizeof(*response));
response->data = buffer;
response->bufferSize = bufferSize;
ERROR_CODE error;
error = linkedList_init(&response->headerFields);
response->statusCode = -1;
return ERROR(error);
}
inline ERROR_CODE http_initheaderField(HTTP_HeaderField* headerField, char* name, const uint_fast64_t nameLength, char* value, const uint_fast64_t valueLength){
headerField->name = name;
headerField->nameLength = nameLength;
headerField->value = value;
headerField->valueLength = valueLength;
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE http_addHeaderField(HTTP_Request* request, char* name, const uint_fast64_t nameLength, char* value, const uint_fast64_t valueLength){
#define HTTP_MAX_HEADER_FIELDS 32
if(request->headerFields.length == HTTP_MAX_HEADER_FIELDS){
return ERROR(ERROR_MAX_HEADER_FIELDS_REACHED);
}
HTTP_HeaderField* headerField = malloc(sizeof(*headerField));
if(headerField == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
http_initheaderField(headerField, name, nameLength, value, valueLength);
linkedList_add(&request->headerFields, headerField);
#undef HTTP_MAX_HEADER_FIELDS
return ERROR(ERROR_NO_ERROR);
}
inline HTTP_HeaderField* http_getHeaderField(HTTP_Request* request, char* name){
HTTP_HeaderField* ret = NULL;
LinkedListIterator it;
linkedList_initIterator(&it, &request->headerFields);
const uint_fast64_t nameLength = strlen(name);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
if(strncasecmp(name, headerField->name, nameLength) == 0){
ret = headerField;
break;
}
}
return ret;
}
inline ERROR_CODE http_closeConnection(int_fast32_t sockFD){
if(close(sockFD) != 0){
return ERROR(ERROR_FAILED_TO_CLOSE_SOCKET);
}
return ERROR(ERROR_NO_ERROR);
}
// TODO:(jan) Clean up error handling/clarify error console output.
ERROR_CODE http_openConnection(int_fast32_t* sockFD, const char* url, const uint_fast16_t port){
struct addrinfo addressHints = {0};
// AF_INET6 == force IPv6.
// Aparently the linux subsystem for Windoof does not like AF_UNSPEC & returns '0.0.0.0' for every getaddrinfo call if we do not force IPv4 via 'AF_INET'.
addressHints.ai_family = AF_INET;
addressHints.ai_socktype = SOCK_STREAM;
// Convert port to service string.
char service[UTIL_FORMATTED_NUMBER_LENGTH];
// util_formatNumber(service, UTIL_FORMATTED_NUMBER_LENGTH, port);
snprintf(service, UTIL_FORMATTED_NUMBER_LENGTH, "%" PRIdFAST16 "", port);
struct addrinfo* serverInfo;
int error;
if((error = getaddrinfo(url, service, &addressHints, &serverInfo)) != 0){
UTIL_LOG_ERROR_("GetaddrInfo:'%s'.", gai_strerror(error));
freeaddrinfo(serverInfo);
return ERROR(ERROR_FAILED_TO_RETRIEVE_ADDRESS_INFORMATION);
}
struct addrinfo* sockInfo;
// Loop through all returned internet addresses.
for(sockInfo = serverInfo; sockInfo != NULL; sockInfo = sockInfo->ai_next){
// Create communication endpoint with internet address.
if((*sockFD = socket(sockInfo->ai_family, sockInfo->ai_socktype, sockInfo->ai_protocol)) == -1){
continue;
}
// Connect file discriptor with internet address.
if(connect(*sockFD, sockInfo->ai_addr, sockInfo->ai_addrlen) == -1) {
UTIL_LOG_ERROR_("Connect:'%s'.", strerror(errno));
close(*sockFD);
*sockFD = -1;
continue;
}
break;
}
if(sockInfo == NULL){
UTIL_LOG_ERROR_("Failed to connect to '%s:%s'.", url, service);
freeaddrinfo(serverInfo);
return ERROR(ERROR_FAILED_TO_CONNECT);
}
freeaddrinfo(serverInfo);
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE http_sendRequest(HTTP_Request* request, HTTP_Response* response, const int_fast32_t connection){
int_fast64_t bufferSize = request->bufferSize - request->dataLength;
char* buffer = (char*) (request->data + request->dataLength);
// Request line.
uint_fast64_t writeOffset = snprintf(buffer, request->bufferSize, "%s %s %s\r\n",
http_getRequestType(request->type),
request->requestURL,
request->httpVersion
);
// Content-Length.
char* contentLength = malloc(sizeof(*contentLength) * UTIL_FORMATTED_NUMBER_LENGTH);
if(contentLength == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
const uint_fast64_t contentLengthLength = snprintf(contentLength, UTIL_FORMATTED_NUMBER_LENGTH, "%" PRIdFAST64 "", request->dataLength);
char* _contentLength = malloc(sizeof(*_contentLength) * 16);
if(contentLength == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(_contentLength, "Content-Length", 16);
http_addHeaderField(request, _contentLength, 16, contentLength, contentLengthLength);
// HeaderFields.
LinkedListIterator it;
linkedList_initIterator(&it, &request->headerFields);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
writeOffset += snprintf(buffer + writeOffset, request->bufferSize - writeOffset, "%s: %s\r\n",
headerField->name,
headerField->value
);
bufferSize -= writeOffset;
}
writeOffset += snprintf(buffer + writeOffset, request->bufferSize - writeOffset, "\r\n");
buffer[writeOffset] = '\0';
bufferSize -= writeOffset + 1;
// Thats bad, we just have overwritten data in the request.
if(bufferSize < 0){
return ERROR(ERROR_HTTP_REQUEST_SIZE_EXCEEDED);
}
// Send request.
if(send(connection, buffer, writeOffset, MSG_NOSIGNAL) != (int_fast64_t) writeOffset){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
if(send(connection, request->data, request->dataLength, MSG_NOSIGNAL) != (int_fast64_t) request->dataLength){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
// Receive response.
ERROR_CODE error;
error = http_receiveResponse(response, connection);
if(error != ERROR_NO_ERROR){
return error;
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE http_sendResponse(HTTP_Response* response, const int_fast32_t connection){
int_fast64_t bufferSize = !response->staticContent ? (response->bufferSize - response->dataLength) : response->bufferSize;
char* buffer = (char*) (response->data + (response->staticContent ? 0 : response->dataLength));
const int_fast16_t statusCode = http_getStatusCode(response->statusCode);
// Response line.
uint_fast64_t writeOffset = snprintf(buffer, response->bufferSize, "%*.*s %" PRIdFAST16 " %s\r\n",
8, 8, response->httpVersion,
statusCode,
http_getStatusMsg(response->statusCode)
);
// TODO:(jan) Clean this up.
// Content-Type:.
const char tType[] = "Content-Type";
const uint_fast64_t tTypeLength = strlen(tType);
char* contentType = malloc(sizeof(*contentType) * (tTypeLength + 1));
if(contentType == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(contentType, tType, tTypeLength + 1);
uint_fast64_t contentTypeLength;
const char* contentTypeString = http_contentTypeToString(response->contentType, &contentTypeLength);
char* _contentTypeString = malloc(sizeof(_contentTypeString) * (contentTypeLength + 1));
if(_contentTypeString == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(_contentTypeString, contentTypeString, contentTypeLength);
_contentTypeString[contentTypeLength] = '\0';
http_addHeaderField((HTTP_Request*) response, contentType, strlen(contentType), _contentTypeString, contentTypeLength);
// Content-Length.
char* contentLength = malloc(sizeof(*contentLength) * UTIL_FORMATTED_NUMBER_LENGTH);
if(contentLength == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
const uint_fast64_t contentLengthLength = snprintf(contentLength, UTIL_FORMATTED_NUMBER_LENGTH, "%" PRIdFAST64 "", response->dataLength);
const char cType[] = "Content-Length";
const uint_fast64_t _contentLengthLength = strlen(cType);
char* _contentLength = malloc(sizeof(*_contentLength) * (_contentLengthLength + 1));
if(_contentLength == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(_contentLength, cType, _contentLengthLength + 1);
http_addHeaderField((HTTP_Request*) response, _contentLength, strlen(_contentLength), contentLength, contentLengthLength);
const char* const serverMessage = "Herder Web-Server";
HTTP_ADD_HEADER_FIELD((*response), Server, serverMessage);
// HeaderFields.
LinkedListIterator it;
linkedList_initIterator(&it, &response->headerFields);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
writeOffset += snprintf(buffer + writeOffset, response->bufferSize - writeOffset, "%s: %s\r\n",
headerField->name,
headerField->value
);
bufferSize -= writeOffset;
}
writeOffset += snprintf(buffer + writeOffset, response->bufferSize - writeOffset, "\r\n");
buffer[writeOffset] = '\0';
bufferSize -= writeOffset + 1;
// Thats bad, we just have overwritten data in the response.
if(bufferSize < 0){
return ERROR(ERROR_HTTP_RESPONSE_SIZE_EXCEEDED);
}
// Send response.
if(send(connection, buffer, writeOffset, MSG_NOSIGNAL) != (int_fast64_t) writeOffset){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
if(!response->staticContent){
if(send(connection, response->data, response->dataLength, MSG_NOSIGNAL) != (int_fast64_t) response->dataLength){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
}else{
if(send(connection, response->cacheObject->data, response->dataLength, MSG_NOSIGNAL) != (int_fast64_t) response->dataLength){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write to socket. '%s'.", strerror(errno));
}
}
return ERROR(ERROR_NO_ERROR);
}
HTTP_StatusCode http_translateStatusCode(const int_fast16_t statusCode){
switch(statusCode){
case 100:{
return _100_CONTINUE;
}
case 101:{
return _101_SWITCHING_PROTOCOLS;
}
case 102:{
return _102_PROCESSING;
}
case 200:{
return _200_OK;
}
case 201:{
return _201_CREATED;
}
case 202:{
return _202_ACCEPTED;
}
case 203:{
return _203_NON_AUTHORATIVE_INFORMATION;
}
case 204:{
return _204_NO_CONTENT;
}
case 205:{
return _205_RESET_CONTROL;
}
case 206:{
return _206_PARTIAL_CONTENT;
}
case 207:{
return _207_MULTI_STATUS;
}
case 208:{
return _208_ALREADY_REPORTED;
}
case 226:{
return _226_IM_USED;
}
case 300:{
return _300_MULTIPLE_CHOICES;
}
case 301:{
return _301_MOVED_PERMANENTLY;
}
case 302:{
return _302_FOUND;
}
case 303:{
return _303_SEE_OTHER;
}
case 304:{
return _304_NOT_MODIFIED;
}
case 305:{
return _305_USE_PROXY;
}
case 307:{
return _307_TEMPORARY_REDIRECT;
}
case 308:{
return _308_PERMANENT_REDIRECT;
}
case 400:{
return _400_BAD_REQUEST;
}
case 401:{
return _401_UNAUTHORIZED;
}
case 402:{
return _402_PAYMENT_REQUIRED;
}
case 403:{
return _403_FORBIDDEN;
}
case 404:{
return _404_NOT_FOUND;
}
case 405:{
return _405_METHOD_NOT_ALLOWED;
}
case 406:{
return _406_NOT_ACCEPTABLE;
}
case 407:{
return _407_PROXY_AUTHENTICATION_REQUIRED;
}
case 408:{
return _408_REQUEST_TIMEOUT;
}
case 409:{
return _409_CONFLICT;
}
case 410:{
return _410_GONE;
}
case 411:{
return _411_LENGTH_REQUIRED;
}
case 412:{
return _412_PRECONDITION_FAILED;
}
case 413:{
return _413_PAYLOAD_TOO_LARGE;
}
case 414:{
return _414_REQUEST_URI_TOO_LARGE;
}
case 415:{
return _415_UNSUPPORTED_MEDIA_TYPE;
}
case 416:{
return _416_REQUEST_RANGE_NOT_SATISFIABLE;
}
case 417:{
return _417_EXPECTATION_FAILED;
}
case 418:{
return _418_IM_A_TEAPOT;
}
case 421:{
return _421_MISDIRECTED_REQUEST;
}
case 422:{
return _422_UNPROCESSABLE_ENTITY;
}
case 423:{
return _423_LOCKED;
}
case 424:{
return _424_FAILED_DEPENDENCY;
}
case 426:{
return _426_UPGRADE_REQUIRED;
}
case 428:{
return _428_PRECONDITION_REQUIRED;
}
case 429:{
return _429_TOO_MANY_REQUESTS;
}
case 431:{
return _431_REQUEST_HEADER_FIELD_TOO_LARGE;
}
case 444:{
return _444_CONNECTION_CLOSED_WITHOUT_RESPONSE;
}
case 451:{
return _451_UNAVAILABLE_FOR_LEAGAL_REASON;
}
case 499:{
return _499_CLIENT_CLOSED_REQUEST;
}
case 500:{
return _500_INTERNAL_SERVER_ERROR;
}
case 501:{
return _501_NOT_IMPLEMENTED;
}
case 502:{
return _502_BAD_GATEWAY;
}
case 503:{
return _503_SERVICE_UYNAVAILABLE;
}
case 504:{
return _504_GATEWAY_TIMEOUT;
}
case 505:{
return _505_HTTP_VERSION_NOT_SUPPORTED;
}
case 506:{
return _506_VARIANT_ALSO_NEGOTIATES;
}
case 507:{
return _507_INSUFFIECENT_STORAGE;
}
case 508:{
return _508_LOOP_DETECTED;
}
case 510:{
return _510_NOT_EXTENDED;
}
case 511:{
return _511_NETWORK_AUTHENTICATION_REQUIRED;
}
case 599:{
return _599_NETWORK_CONNECTION_TIMEOUT_ERROR;
}
default:{
UTIL_LOG_CRITICAL_("[%" PRIdFAST16"] Unsupported HTTP status code.", statusCode);
return _500_INTERNAL_SERVER_ERROR;
}
}
}
ERROR_CODE http_receiveResponse(HTTP_Response* response, const int_fast32_t connection){
char* buffer = (char*) response->data;
int_fast64_t bytesRead;
if((bytesRead = read(connection, buffer, response->bufferSize)) == -1){
return ERROR(ERROR_READ_ERROR);
}
if(bytesRead == 0){
return ERROR(ERROR_EMPTY_RESPONSE);
}else if(bytesRead ==(int_fast64_t) response->bufferSize){
return ERROR(ERROR_MAX_MESSAGE_SIZE_EXCEEDED);
}else if(bytesRead < 3/*RequestType*/ + 3/*Spaces*/ + 2/*Line delimiter*/ + 1/*RequestURL*/ + 8/*Version*/){
return ERROR(ERROR_INSUFICIENT_MESSAGE_LENGTH);
}
// RequestLine.
int_fast64_t i;
for(i = 1; i < bytesRead; i++){
if(buffer[i] == '\n' && buffer[i - 1] == '\r'){
int_fast64_t posSplitBegin = 0;
int_fast64_t posSplitEnd;
// Version.
posSplitEnd = util_findFirst(buffer, bytesRead, ' ');
const char* const version = buffer;
const uint_fast64_t versionLength = posSplitEnd;
if(strncmp(version, HTTP_VERSION_1_1, versionLength) != 0){
return ERROR(ERROR_VERSION_MISSMATCH);
}
posSplitBegin = posSplitEnd + 1;
// StatusCode.
posSplitEnd = util_findFirst(buffer + posSplitBegin, bytesRead, ' ');
const char* const statusCode = buffer + posSplitBegin;
errno = 0;
char* endPtr;
response->statusCode = strtol(statusCode, &endPtr, 10/*Decimal*/);
if((response->statusCode == 0 && endPtr == statusCode) || (errno == ERANGE && (response->statusCode == LONG_MIN || response->statusCode == LONG_MAX))){
return ERROR(ERROR_INVALID_STATUS_CODE);
}
response->statusCode = http_translateStatusCode(response->statusCode);
posSplitBegin = posSplitEnd + 1;
// StatusMessage.
posSplitEnd = util_findFirst(buffer + posSplitBegin, bytesRead, ' ');
response->statusMsg = buffer + posSplitBegin;
response->statusMsgLength = posSplitEnd - posSplitBegin;
break;
}
}
i++;
// HeaderFields.
int_fast64_t posSplitBegin = i;
int_fast64_t posSplitEnd;
for(;i < bytesRead; i++){
if(buffer[i] == '\n' && buffer[i - 1] == '\r'){
// No need to check for index underflow, because we need atleast two "\r\n" in the buffer to even get here.
if(buffer[i - 2] == '\n' && buffer[i - 3] == '\r'){
break;
}
posSplitEnd = i - 1;
char* line = buffer + posSplitBegin;
uint_fast64_t lineLength = posSplitEnd - posSplitBegin;
const int_fast64_t lineSplit = util_findFirst(line, lineLength, ':');
if(lineSplit == -1){
// Copy current line onto stack to add limiting '\0' for printing.
char* _line = alloca(lineLength + 1);
memcpy(_line, line, lineLength);
_line[lineLength] = '\0';
UTIL_LOG_ERROR_("Failed to parse '%s'.", _line);
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
uint_fast64_t nameLength = lineSplit;
char* name = malloc(sizeof(*name) * (nameLength + 1));
if(name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(name, line, nameLength);
name[nameLength] = '\0';
uint64_t valueLength = lineLength - (lineSplit + 1);
char* value = malloc(sizeof(*value) * (valueLength + 1));
if(value == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(value, line + lineSplit + 1, valueLength);
value[valueLength] = '\0';
util_trim(value, valueLength);
posSplitBegin = i + 1;
if(strncmp(name, "Content-Length:", nameLength) == 0){
char* endPtr;
int_fast64_t contentLength;
contentLength = strtol(value, &endPtr, 10/*Decimal*/);
errno = 0;
if((contentLength == 0 && endPtr == value) || (errno == ERANGE && (contentLength == LONG_MIN || contentLength == LONG_MAX))){
return ERROR(ERROR_INVALID_CONTENT_LENGTH);
}
response->dataLength = contentLength;
}
// TODO: (jan) Use a chunk of the processing buffer to store headerField structs.
// Because the headerFields are at the beginning of both structs, we should be fine casting between the types.
http_addHeaderField((HTTP_Request*) response, name, nameLength, value, valueLength);
}
}
uint_fast64_t bufferSize = bytesRead;
if(i + response->dataLength > (uint_fast64_t) bytesRead){
bytesRead += read(connection, buffer + bytesRead, HTTP_PROCESSING_BUFFER_SIZE - bytesRead);
bufferSize = bytesRead - bufferSize;
if(bytesRead == -1){
return ERROR(ERROR_READ_ERROR);
}else{
if(bytesRead >= HTTP_PROCESSING_BUFFER_SIZE){
return ERROR(ERROR_MAX_MESSAGE_SIZE_EXCEEDED);
}
}
}
// Data.
response->data = (int_fast8_t*) (buffer + i + 1);
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE http_receiveRequest(HTTP_Request* request, const int_fast32_t connection){
char* buffer = (char*) request->data;
int_fast64_t bytesRead = read(connection, buffer, HTTP_PROCESSING_BUFFER_SIZE);
if(bytesRead == -1){
return ERROR(ERROR_READ_ERROR);
}else if(bytesRead >= HTTP_PROCESSING_BUFFER_SIZE){
return ERROR(ERROR_MAX_MESSAGE_SIZE_EXCEEDED);
}else if(bytesRead < 3/*RequestType*/ + 3/*Spaces*/ + 2/*Line delimiter*/ + 1/*RequestURL*/ + 8/*Version*/){
return ERROR(ERROR_INSUFICIENT_MESSAGE_LENGTH);
}
// RequestLine.
int_fast64_t i;
for(i = 1; i < bytesRead; i++){
if(buffer[i - 1] == '\n' && buffer[i - 2] == '\r'){
int_fast64_t posSplitBegin = 0;
int_fast64_t posSplitEnd;
// RequestType.
posSplitEnd = util_findFirst(buffer, bytesRead, ' ');
if(posSplitEnd == -1){
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
const char* const requestType = buffer;
const uint_fast64_t requestTypeLength = posSplitEnd;
request->type = http_parseRequestType(requestType, requestTypeLength);
posSplitBegin = posSplitEnd + 1;
// RequestURL.
posSplitEnd = util_findFirst(buffer + posSplitBegin, bytesRead, ' ');
if(posSplitEnd == -1){
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
request->urlLength = posSplitEnd;
if(request->urlLength == 0){
return ERROR_(ERROR_INVALID_REQUEST_URL, "URL length can't be '%" PRIuFAST16 "'.", request->urlLength);
}
request->requestURL = malloc(sizeof(*request->requestURL) * request->urlLength + 1);
if(request->requestURL == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(request->requestURL, buffer + posSplitBegin, request->urlLength);
request->requestURL[request->urlLength] = '\0';
posSplitBegin += posSplitEnd + 1;
const int_fast64_t getParameterOffset = util_findFirst(request->requestURL, request->urlLength, '?');
if(getParameterOffset != -1){
request->requestURL[getParameterOffset] = '\0';
request->getParameterLength = request->urlLength - getParameterOffset;
request->urlLength = getParameterOffset;
request->getParameter = request->requestURL + (getParameterOffset + 1);
}
// Version.
posSplitEnd = util_findFirst(buffer, bytesRead, ' ');
const char* const version = buffer + posSplitBegin;
const uint_fast64_t versionLength = posSplitEnd;
if(strncmp(version, HTTP_VERSION_1_1, versionLength) != 0){
return ERROR(ERROR_VERSION_MISSMATCH);
}
break;
}
}
// HeaderFields.
uint_fast64_t posLineBegin = i;
for(;i < bytesRead; i++){
if(buffer[i] == '\n' && buffer[i - 1] == '\r'){
if(buffer[i - 2] == '\n' && buffer[i - 3] == '\r'){
// Skip trailing '\n'.
i++;
break;
}
char* line = buffer + posLineBegin;
uint_fast64_t lineLength = i - posLineBegin;
const int_fast64_t nameLength = util_findFirst(line, lineLength,':');
if(nameLength == -1){
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
char* name = malloc(sizeof(*name) * nameLength);
if(name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(name, line, nameLength);
// Move line beginning after ':'
line += nameLength + 1;
lineLength -= nameLength + 1;
// Skip trailing whitespace
if(isspace(*line) != 0){
line++;
lineLength--;
}
const int_fast64_t valueLength = lineLength;
if(valueLength == -1){
return ERROR(ERROR_INVALID_HEADER_FIELD);
}
char* value = malloc(sizeof(*value) * valueLength);
if(value == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(value, line, valueLength);
if(strncmp(name, "Content-Length:", nameLength) == 0){
errno = 0;
char* endPtr;
int_fast64_t contentLength;
contentLength = strtol(value, &endPtr, 10/*Decimal*/);
if((contentLength == 0 && endPtr == value) || (errno == ERANGE && (contentLength == LONG_MIN || contentLength == LONG_MAX))){
return ERROR(ERROR_INVALID_CONTENT_LENGTH);
}
request->dataLength = contentLength;
}
http_addHeaderField(request, name, nameLength, value, valueLength);
posLineBegin = i + 1;
}
}
// We have not read the whole request, because of the way we handle/send request header and data in 'http_sendRequest'.
uint_fast64_t bufferSize = bytesRead;
if(i + request->dataLength > (uint_fast64_t) bytesRead){
bytesRead += read(connection, buffer + bytesRead, HTTP_PROCESSING_BUFFER_SIZE - bytesRead);
bufferSize = bytesRead - bufferSize;
if(bytesRead == -1){
return ERROR(ERROR_READ_ERROR);
}else{
if(bytesRead >= HTTP_PROCESSING_BUFFER_SIZE){
return ERROR(ERROR_MAX_MESSAGE_SIZE_EXCEEDED);
}
}
}
// Data.
request->data = (int_fast8_t*) (buffer + i);
return ERROR(ERROR_NO_ERROR);
}
void http_freeHTTP_Request(HTTP_Request* request){
LinkedListIterator it;
linkedList_initIterator(&it, &request->headerFields);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
free(headerField->name);
free(headerField->value);
free(headerField);
}
free(request->requestURL);
linkedList_free(&request->headerFields);
}
void http_freeHTTP_Response(HTTP_Response* response){
LinkedListIterator it;
linkedList_initIterator(&it, &response->headerFields);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
HTTP_HeaderField* headerField = LINKED_LIST_ITERATOR_NEXT(&it);
free(headerField->name);
free(headerField->value);
free(headerField);
}
linkedList_free(&response->headerFields);
}
/*
printf("#define HASH_GET %d\n", util_hashString("GET"));
printf("#define HASH_HEAD %d\n", util_hashString("HEAD"));
printf("#define HASH_POST %d\n", util_hashString("POST"));
printf("#define HASH_PUT %d\n", util_hashString("PUT"));
printf("#define HASH_DELETE %d\n", util_hashString("DELETE"));
printf("#define HASH_TRACE %d\n", util_hashString("TRACE"));
printf("#define HASH_OPTIONS %d\n", util_hashString("OPTIONS"));
printf("#define HASH_CONNECT %d\n", util_hashString("CONNECT"));
printf("#define HASH_PATCH %d\n", util_hashString("PATCH"));
*/
HTTP_RequestType http_parseRequestType(const char* const type, const uint_fast64_t length){
#define HASH_GET 591093270
#define HASH_HEAD 942011328
#define HASH_POST -1319429824
#define HASH_PUT 666496399
#define HASH_DELETE 617851755
#define HASH_TRACE 1359153669
#define HASH_OPTIONS -1168929634
#define HASH_CONNECT -431736502
#define HASH_PATCH 867751912
HTTP_RequestType ret = REQUEST_TYPE_UNKNOWN;
switch(util_hashString(type, length)){
case HASH_GET:{
ret = REQUEST_TYPE_GET;
break;
}
case HASH_POST:{
ret = REQUEST_TYPE_POST;
break;
}
case HASH_HEAD:{
ret = REQUEST_TYPE_HEAD;
break;
}
case HASH_PUT:{
ret = REQUEST_TYPE_PUT;
break;
}
case HASH_DELETE:{
ret = REQUEST_TYPE_DELETE;
break;
}
case HASH_TRACE:{
ret = REQUEST_TYPE_TRACE;
break;
}
case HASH_OPTIONS:{
ret =REQUEST_TYPE_OPTIONS;
break;
}
case HASH_CONNECT:{
ret = REQUEST_TYPE_CONNECT;
break;
}
case HASH_PATCH:{
ret = REQUEST_TYPE_PATCH;
break;
}
default:{
UTIL_LOG_ERROR_("Unknown request type:'%s'.", type);
break;
}
}
#undef HASH_GET
#undef HASH_HEAD
#undef HASH_POST
#undef HASH_PUT
#undef HASH_DELETE
#undef HASH_TRACE
#undef HASH_OPTIONS
#undef HASH_CONNECT
#undef HASH_PATCH
return ret;
}
local const char* const HTTP_STATUS_MESSAGE_MAPPING_ARRAY[] = {
"Continue",
"Switching Protocols",
"Processing",
"OK",
"Created",
"Accepted",
"Non-authoritative Information",
"No Content",
"Reset Content",
"Partial Content",
"Multi-Status",
"Already Reported",
"IM Used",
"Multiple Choices",
"Moved Permanently",
"Found",
"See Other",
"Not Modified",
"Use Proxy",
"Temporary Redirect",
"Permanent Redirect",
"Bad Request",
"Unauthorized",
"Payment Required",
"Forbidden",
"Not Found",
"Method Not Allowed",
"Not Acceptable",
"Proxy Authentication Required",
"Request Timeout",
"Conflict",
"Gone",
"Length Required",
"Precondition Failed",
"Payload Too Large",
"Request-URI Too Long",
"Unsupported Media Type",
"Requested Range Not Satisfiable",
"Expectation Failed",
"I'm a teapot",
"Misdirected Request",
"Unprocessable Entity",
"Locked",
"Failed Dependency",
"Upgrade Required",
"Precondition Required",
"Too Many Requests",
"Request Header Fields Too Large",
"Connection Closed Without Response",
"Unavailable For Legal Reasons",
"Client Closed Request",
"Internal Server Error",
"Not Implemented",
"Bad Gateway",
"Service Unavailable",
"Gateway Timeout",
"HTTP Version Not Supported",
"Variant Also Negotiates",
"Insufficient Storage",
"Loop Detected",
"Not Extended",
"Network Authentication Required",
"Network Connect Timeout Error"
};
inline const char* http_getStatusMsg(HTTP_StatusCode statusCode){
return HTTP_STATUS_MESSAGE_MAPPING_ARRAY[statusCode];
}
local const char* HTTP_REQUEST_TYPE_MAPPING_ARRAY[] = {
"UNKNOWN",
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"OPTIONS",
"CONNECT",
"PATCH"
};
inline const char* http_getRequestType(HTTP_RequestType requestType){
return HTTP_REQUEST_TYPE_MAPPING_ARRAY[requestType];
}
local const int_fast16_t HTTP_STATUS_CODE_MAPPING_ARRAY[] = {
100,
101,
102,
200,
201,
202,
203,
204,
205,
206,
207,
208,
226,
300,
301,
302,
303,
304,
305,
307,
308,
400,
401,
402,
403,
404,
405,
406,
407,
408,
409,
410,
411,
412,
413,
414,
415,
416,
417,
418,
421,
422,
423,
424,
426,
428,
429,
431,
444,
451,
499,
500,
501,
502,
503,
504,
505,
506,
507,
508,
510,
511,
599
};
inline int_fast16_t http_getStatusCode(HTTP_StatusCode statusCode){
return HTTP_STATUS_CODE_MAPPING_ARRAY[statusCode];
}
inline void http_setHTTP_Version(HTTP_Response* response, const char version[]){
memcpy(response->httpVersion, version, 9);
}
typedef struct{
const char* name;
const uint_fast64_t length;
}ContentType;
local const ContentType HTTP_CONTENT_TYPE_MAPPING_ARRAY[] = {
{"TEXT/HTML", 9},
{"text/css", 8},
{"application/javascript", 22},
{"application/json", 16},
{"application/zip", 15},
{"iamge/jpeg", 10},
{"image/png", 9},
{"image/svg+xml", 13},
{"image/x-icon", 12}
};
inline const char* http_contentTypeToString(const HTTP_ContentType contentType, uint_fast64_t* length){
const ContentType _contentType = HTTP_CONTENT_TYPE_MAPPING_ARRAY[contentType];
*length = _contentType.length;
return _contentType.name;
}
// printf("#define HASH_TXT %d\n", util_hashString("txt", 3));
// printf("#define HASH_HTML %d\n", util_hashString("html", 4));
// printf("#define HASH_CSS %d\n", util_hashString("css", 3));
// printf("#define HASH_JS %d\n", util_hashString("js", 2));
// printf("#define HASH_JPG %d\n", util_hashString("jpg", 3));
// printf("#define HASH_PNG %d\n", util_hashString("png", 3));
// printf("#define HASH_SVG %d\n", util_hashString("svg", 3));
// printf("#define HASH_ICO %d\n", util_hashString("ico", 3));
// printf("#define HASH_ZIP %d\n", util_hashString("zip", 3));
inline HTTP_ContentType http_getContentType(const char* fileExtension, const uint_fast64_t fileExtensionLength){
#define HASH_TXT 966206576
#define HASH_HTML 542175051
#define HASH_CSS 825432995
#define HASH_JS 6953609
#define HASH_JPG 883066721
#define HASH_PNG 932504553
#define HASH_SVG 957813860
#define HASH_ICO 873952437
#define HASH_ZIP 1014791617
switch(util_hashString(fileExtension, fileExtensionLength)){
case HASH_CSS :{
return HTTP_CONTENT_TYPE_TEXT_CSS;
break;
}
case HASH_JS :{
return HTTP_CONTENT_TYPE_APPLICATION_JAVASCRIPT;
break;
}
case HASH_PNG :{
return HTTP_CONTENT_TYPE_IMAGE_PNG;
break;
}
case HASH_JPG :{
return HTTP_CONTENT_TYPE_IMAGE_JPG;
break;
}
case HASH_SVG :{
return HTTP_CONTENT_TYPE_IMAGE_SVG;
break;
}
case HASH_ICO:{
return HTTP_CONTENT_TYPE_IMAGE_ICON;
break;
}
case HASH_HTML:
case HASH_TXT:
default:{
return HTTP_CONTENT_TYPE_TEXT_HTML;
break;
}
}
#undef HASH_TXT
#undef HASH_HTML
#undef HASH_CSS
#undef HASH_JS
#undef HASH_JPG
#undef HASH_PNG
#undef HASH_SVG
#undef HASH_ICO
#undef HASH_ZIP
}
#endif
|
Ex05/herder
|
src/cache.h
|
#ifndef CACHE_H
#define CACHE_H
#include "util.h"
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include "linkedList.h"
typedef struct{
LinkedList elements;
uint_fast64_t maxSize;
uint_fast64_t currentSize;
sem_t activeAcesses;
pthread_mutex_t lock;
uint_fast64_t threads;
}Cache;
typedef struct{
uint8_t* data;
uint_fast64_t size;
struct timespec timeCheckin;
struct timespec timeLastHit;
uint32_t totalHits;
uint_fast64_t fileLocationLength;
uint_fast64_t symbolicFileLocationLength;
uint_fast64_t fileExtensionOffset;
char* fileLocation;
char* symbolicFileLocation;
}CacheObject;
ERROR_CODE cache_init(Cache*, const uint_fast64_t, const uint_fast64_t);
void cache_free(Cache*);
ERROR_CODE cache_get(Cache*, CacheObject**, char*, const uint_fast64_t);
ERROR_CODE cache_load(Cache*, CacheObject**, char*, const uint_fast64_t, char*, const uint_fast64_t);
ERROR_CODE cache_remove(Cache*, CacheObject*);
#endif
|
Ex05/herder
|
src/pls.c
|
#ifndef PLS_C
#define PLS_C
#include "pls.h"
ERROR_CODE pls_savePlayList(Property* libraryDirectory, const char* fileName, Show* show){
ERROR_CODE error;
FILE* file = fopen(fileName, "w+");
if(file == NULL){
UTIL_LOG_ERROR_("Failed to create file: '%s' - '%s'.", fileName, strerror(errno));
return ERROR(ERROR_FAILED_TO_CREATE_FILE);
}
fprintf(file, "[playlist]\n\n");
Season** seasons = alloca(sizeof(*seasons) * show->seasons.length);
if((error = mediaLibrary_sortSeasons(&seasons, &show->seasons)) != ERROR_NO_ERROR){
goto label_close;
}
uint_fast64_t numEntries;
register uint_fast64_t i;
for(i = 0, numEntries = 1; i < show->seasons.length; i++){
Season* season = seasons[i];
Episode** episodes = alloca(sizeof(*episodes) * season->episodes.length);
if((error = mediaLibrary_sortEpisodes(&episodes, &season->episodes)) != ERROR_NO_ERROR){
goto label_close;
}
register uint_fast64_t j;
for(j = 0; j < season->episodes.length; j++, numEntries++){
Episode* episode = episodes[j];
EpisodeInfo episodeInfo;
mediaLibrary_fillEpisodeInfo(&episodeInfo, show, season, episode);
char* relativePath;
uint_fast64_t relativePathLength;
HERDER_CONSTRUCT_RELATIVE_FILE_PATH(&relativePath, &relativePathLength, &episodeInfo);
const uint_fast64_t absoluteFilePathLength = (libraryDirectory->entry->length - 1) + relativePathLength + 1;
char* absoluteFilePath = alloca(sizeof(*absoluteFilePath) * (absoluteFilePathLength + 1));
uint_fast64_t writeOffset = 0;
strncpy(absoluteFilePath + writeOffset, (char*) libraryDirectory->buffer, libraryDirectory->entry->length - 1);
writeOffset += libraryDirectory->entry->length - 1;
strncpy(absoluteFilePath + writeOffset, relativePath, relativePathLength);
writeOffset += relativePathLength;
absoluteFilePath[writeOffset] = '\0';
fprintf(file, "File%" PRIuFAST64 "=%s\n", numEntries, absoluteFilePath);
fprintf(file, "Title%" PRIuFAST64 "=%s s%02" PRIdFAST16 "e%02" PRIdFAST16 " %s.%s\n\n", numEntries,episodeInfo.showName, episodeInfo.season, episodeInfo.episode, episodeInfo.name, episodeInfo.fileExtension);
}
}
fprintf(file, "NumberOfEntries=%" PRIuFAST64 "\n", numEntries);
fprintf(file, "Version=2");
label_close:
if(fflush(file) != 0){
return ERROR(ERROR_DISK_ERROR);
}
fclose(file);
return ERROR(error);
}
#endif
|
Ex05/herder
|
src/util.c
|
<reponame>Ex05/herder<filename>src/util.c
#ifndef UTIL_C
#define UTIL_C
#include "util.h"
/**
* Converts a given number <b>value</b> into a easy readable formated number string.
*
* Numbers <= to 999 will be padded with 0.<br>
* And every 3 digits an underscore('_') will be inserted.
* @param s The buffer in which the formated number will be put.
* @param bufferSize The size of the buffer.
* @param value The value to be converted.
* @return Returns <b>ERROR_NO_ERROR</b> on success. And <b>ERROR_BUFFER_OVERFLOW</b> if the provided buffer was not large enough.
*/
inline ERROR_CODE util_formatNumber(char* s, uint_fast64_t* bufferSize, const int_fast64_t value){
int_fast64_t length = snprintf(s, *bufferSize, value > 999 ? "%" PRIdFAST64 : "%03" PRIdFAST64, value);
if(length >= (int_fast64_t) *bufferSize){
return ERROR_(ERROR_BUFFER_OVERFLOW, "%s", util_toErrorString(ERROR_BUFFER_OVERFLOW));
}
#define SKIP_VALUE 3
*bufferSize = length;
if(value < 1000){
return ERROR(ERROR_NO_ERROR);
}
uint_fast8_t skip = SKIP_VALUE;
int_fast64_t i;
for(i = length; i >= 0; i--){
if(--skip == 0 && i > 0){
int_fast64_t j;
for(j = length; j >= i - 1; j--){
s[j + 1] = s[j];
}
s[j + 1] = '_';
length++;
skip = SKIP_VALUE;
}
}
#undef SKIP_VALUE
return ERROR(ERROR_NO_ERROR);
}
local const char* UTIL_ERROR_CODE_MESSAGE_MAPPING_ARRAY[] = {
"ERROR_NO_ERROR",
"ERROR_ERROR",
"ERROR_OUT_OF_MEMORY",
"ERROR_BUFFER_OVERFLOW",
"ERROR_TO_MANY_ELEMENTS",
"ERROR_FAILED_TO_UNMAP_MEMORY",
"ERROR_INVALID_REQUEST_URL",
"ERROR_PTHREAD_THREAD_CREATION_FAILED",
"ERROR_PTHREAD_MUTEX_INITIALISATION_FAILED",
"ERROR_PTHREAD_SEMAPHOR_INITIALISATION_FAILED",
"ERROR_UNIX_DOMAIN_SOCKET_INITIALISATION_FAILED",
"ERROR_FAILED_TO_BIND_SERVER_SOCKET",
"ERROR_FAILED_TO_LISTEN_ON_SERVER_SOCKET",
"ERROR_FAILED_TO_FORK_PROCESS",
"ERROR_FAILED_TO_CREATE_NEW_SESSION",
"ERROR_FAILED_TO_CHANGE_PROCESS_WORKING_DIRECTORY",
"ERROR_FAILED_TO_LOCK_FILE",
"ERROR_FAILED_TO_RETRIEVE_ADDRESS_INFORMATION",
"ERROR_FAILED_TO_CONNECT",
"ERROR_WRITE_ERROR",
"ERROR_READ_ERROR",
"ERROR_EMPTY_RESPONSE",
"ERROR_INSUFICIENT_MESSAGE_LENGTH",
"ERROR_INVALID_STATUS_CODE",
"ERROR_VERSION_MISSMATCH",
"ERROR_INVALID_HEADER_FIELD",
"ERROR_MAX_HEADER_FIELDS_REACHED",
"ERROR_INVALID_CONTENT_LENGTH",
"ERROR_MAX_MESSAGE_SIZE_EXCEEDED",
"ERROR_FAILED_TO_CLOSE_SOCKET",
"ERROR_FAILED_TO_APPEMD_SIGNAL_HANDLER",
"ERROR_HTTP_RESPONSE_SIZE_EXCEEDED",
"ERROR_HTTP_REQUEST_SIZE_EXCEEDED",
"ERROR_INCOMPLETE",
"ERROR_FAILED_TO_CREATE_FILE",
"ERROR_DUPLICATE_ENTRY",
"ERROR_PROPERTY_NOT_SET",
"ERROR_SERVER_ERROR",
"ERROR_UNAVAILABLE",
"ERROR_FAILED_TO_RETRIEV_FILE_INFO",
"ERROR_FAILED_TO_LOAD_FILE",
"ERROR_FAILED_TO_CLOSE_FILE",
"ERROR_MISSING_DIRECTORY",
"ERROR_REMOTE_PORT_PROPERTY_NO_SET",
"ERROR_REMOTE_HOST_PROPERTY_NO_SET",
"ERROR_INVALID_RETURN_CODE",
"ERROR_DISK_ERROR",
"ERROR_ENTRY_NOT_FOUND",
"ERROR_LIBRARY_DIRECTORY_NOT_SET",
"ERROR_FAILED_TO_CREATE_DIRECTORY",
"ERROR_FAILED_TO_OPEN_FILE",
"ERROR_M_PROTECT",
"ERROR_MEMORY_ALLOCATION_ERROR",
"ERROR_UNKNOWN_SHOW",
"ERROR_ALREADY_EXIST",
"ERROR_FAILED_TO_COPY_FILE",
"ERROR_FAILED_TO_DELETEFILE",
"ERROR_CONVERSION_ERROR",
"ERROR_FAILED_TO_ADD_PROPERTY",
"ERROR_FAILED_TO_REMOVE_PROPERTY",
"ERROR_INVALID_COMMAND_USAGE",
"ERROR_FAILED_TO_UPDATE_PROPERTY",
"ERROR_INVALID_STRING",
"ERROR_INVALID_VALUE",
"ERROR_FUNCTION_NOT_IMPLEMENTED",
"ERROR_FAILED_TO_OPEN_DIRECTORY",
"ERROR_NAME_MISSMATCH",
"ERROR_END_OF_FILE",
"ERROR_FAILED_TO_DELETE_DIRECTORY",
"ERROR_FAILED_TO_REMOVE_NODE",
"ERROR_NO_VALID_ARGUMENT",
"ERROR_INVALID_FILE_EXTENSION",
"ERROR_FAILED_TO_RENAME_FILE",
};
inline const char* util_toErrorString(const ERROR_CODE errorCode){
return UTIL_ERROR_CODE_MESSAGE_MAPPING_ARRAY[errorCode];
}
inline int_fast32_t util_fileExists(const char *file){
struct stat st = {0};
return stat(file, &st) == 0;
}
inline int_fast32_t util_directoryExists(const char* dir){
struct stat st = {0};
return stat(dir, &st) == 0 && S_ISDIR(st.st_mode);
}
inline ERROR_CODE util_blockAlloc(void** buffer, const uint_fast64_t length){
*buffer = mmap(NULL, length, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if(*buffer == MAP_FAILED){
return ERROR_(ERROR_MEMORY_ALLOCATION_ERROR, "Failed to create memory page '%s'.", strerror(errno));
}
if(mprotect(*buffer, length, PROT_READ | PROT_WRITE) != 0){
return ERROR_(ERROR_M_PROTECT, "Failed to protect memory page '%s'.", strerror(errno));
}else{
return ERROR(ERROR_NO_ERROR);
}
}
inline ERROR_CODE util_unMap(void* buffer, const uint_fast64_t length){
if(munmap(buffer, length) == -1){
return ERROR_(ERROR_FAILED_TO_UNMAP_MEMORY, "'%s'.", strerror(errno));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE util_concatenate(char* dst, const char* a, const uint_fast64_t lengthA, const char* b, const uint_fast64_t lengthB) {
strncpy(dst, a, lengthA);
strncpy(dst + lengthA, b, lengthB);
return ERROR(ERROR_NO_ERROR);
}
inline uint_fast16_t util_byteArrayTo_uint16(const int8_t* buffer){
return (uint_fast16_t)(
((uint8_t) buffer[0]) << 8 |
(uint8_t) buffer[1]);
}
inline uint_fast32_t util_byteArrayTo_uint32(const int8_t* buffer){
return (uint_fast32_t)((uint8_t) buffer[0]) << 24 |
((uint8_t) buffer[1]) << 16 |
((uint8_t) buffer[2]) << 8 |
((uint8_t) buffer[3]);
}
inline uint_fast64_t util_byteArrayTo_uint64(const int8_t* buffer){
return (uint_fast64_t)(((uint64_t) ((uint8_t) buffer[0]) << 56) |
((uint64_t)((uint8_t) buffer[1]) << 48) |
((uint64_t)((uint8_t) buffer[2]) << 40) |
((uint64_t)((uint8_t) buffer[3]) << 32) |
((uint64_t)((uint8_t) buffer[4]) << 24) |
((uint64_t)((uint8_t) buffer[5]) << 16) |
((uint64_t)((uint8_t) buffer[6]) << 8) |
((uint8_t) buffer[7]));
}
inline int8_t* util_uint16ToByteArray(int8_t* buffer, const uint_fast16_t value){
buffer[0] = (value >> 8) & 0XFF;
buffer[1] = value & 0XFF;
return buffer;
}
inline int8_t* util_uint32ToByteArray(int8_t* buffer, const uint_fast32_t value){
buffer[0] = (value >> 24) & 0xFF;
buffer[1] = (value >> 16) & 0xFF;
buffer[2] = (value >> 8) & 0XFF;
buffer[3] = value & 0XFF;
return buffer;
}
inline int8_t* util_uint64ToByteArray(int8_t* buffer, const uint_fast64_t value){
buffer[0] = (value >> 56) & 0xFF;
buffer[1] = (value >> 48) & 0xFF;
buffer[2] = (value >> 40) & 0XFF;
buffer[3] = (value >> 32) & 0XFF;
buffer[4] = (value >> 24) & 0XFF;
buffer[5] = (value >> 16) & 0XFF;
buffer[6] = (value >> 8) & 0XFF;
buffer[7] = value & 0XFF;
return buffer;
}
inline void util_toLowerChase(char* s){
for ( ; *s; ++s) {
*s = tolower(*s);
}
}
inline void util_stringCopy(char* a, char* b, uint_fast64_t length){
memmove(a, b, length);
}
inline int_fast64_t util_findFirst(const char* s, const uint_fast64_t length, const char c) {
int_fast64_t i;
for (i = 0; i < (int_fast64_t) length; i++){
if(*(s + i) == c){
return i;
}
}
return -1;
}
inline int_fast64_t util_findFirst_s(const char* buffer, const uint_fast64_t bufferLength, const char* s, const uint_fast64_t stringLength) {
uint_fast64_t offset = 0;
int_fast64_t i;
for (i = 0; i < (int_fast64_t) bufferLength; i++){
if(buffer[i] == s[offset++]){
if(offset == stringLength){
return i - (stringLength - 1);
}
}else{
offset = 0;
}
}
return -1;
}
inline int_fast64_t util_findLast(const char* s, const uint_fast64_t length, const char c) {
int_fast64_t i;
for (i = length - 1; i >= 0; i--){
if(*(s + i) == c){
return i;
}
}
return -1;
}
// TODO: Do some testing, what is actually the fastest way to copy a file on each platform. See: https://stackoverflow.com/questions/10195343/copy-a-file-in-a-sane-safe-and-efficient-way for some example implementations. (jan - 2018.11.20)
inline ERROR_CODE util_fileCopy(const char* src, const char* dst){
ERROR_CODE error = ERROR_NO_ERROR;
FILE* srcFile = fopen(src, "r");
if(srcFile == NULL){
error = ERROR_FAILED_TO_OPEN_FILE;
UTIL_LOG_ERROR_("Failed to open source file: '%s'.", src);
goto label_return;
}
FILE* dstFile = fopen(dst, "w+");
if(dstFile == NULL){
error = ERROR_FAILED_TO_OPEN_FILE;
UTIL_LOG_ERROR_("Failed to open destination file: '%s'.", dst);
goto label_closeSrc;
}
const uint_fast32_t bufferSize = util_getFileSystemBlockSize(src);
// TODO: Decide if putting the buffer on the stack is a good idea. (jan - 2018.11.17)
int8_t* buffer = alloca(bufferSize);
uint_fast64_t numBytesToWrite;
for(;;){
numBytesToWrite = fread(buffer, sizeof(*buffer), bufferSize, srcFile);
if(ferror(srcFile) != 0){
error = ERROR_READ_ERROR;
UTIL_LOG_ERROR_("Failed to read file '%s'.", src);
break;
}
uint_fast64_t numBytesWritten = fwrite(buffer, sizeof(*buffer), numBytesToWrite, dstFile);
if(numBytesWritten != numBytesToWrite || ferror(dstFile) != 0){
error = ERROR_WRITE_ERROR;
UTIL_LOG_ERROR_("Failed to copy data from '%s' to '%s' %" PRIu64" out of %" PRIu64 "bytes written in current block.", src, dst, numBytesWritten, numBytesToWrite);
break;
}
if(feof(srcFile) != 0){
break;
}
}
fclose(dstFile);
label_closeSrc:
fclose(srcFile);
label_return:
return ERROR(error);
}
inline uint_fast32_t util_getFileSystemBlockSize(const char* path){
struct statvfs stat;
if(statvfs(path, &stat) == 0){
return stat.f_bsize;
}else{
return 8192;
}
}
inline ERROR_CODE util_deleteFile(const char* file){
if(unlink(file) != 0){
return ERROR_(ERROR_FAILED_TO_DELETEFILE, "'%s' %s", file, strerror(errno));
}
return ERROR(ERROR_NO_ERROR);
}
// Note: 'directory' has to be slash terminated. (jan - 2019.05.20)
ERROR_CODE util_deleteDirectory(const char* directory, const bool preserveRoot, const bool emptyDirectoriesOnly){
ERROR_CODE error = ERROR_NO_ERROR;
DIR* currentDirectory = opendir(directory);
if(currentDirectory == NULL){
error = ERROR_FAILED_TO_OPEN_DIRECTORY;
goto label_closeDir;
}
struct dirent* directoryEntry;
const uint_fast64_t directoryLength = strlen(directory);
int_fast8_t isDirectoryEmpty = 2;
while((directoryEntry = readdir(currentDirectory)) != NULL){
// Avoid reentering current and parent directory.
const uint_fast64_t currentEntryLength = strlen(directoryEntry->d_name);
if(strncmp(directoryEntry->d_name, ".", currentEntryLength) == 0 || strncmp(directoryEntry->d_name, "..", currentEntryLength) == 0){
isDirectoryEmpty -= 1;
continue;
}
if(directoryEntry->d_type == DT_DIR){
isDirectoryEmpty += 1;
const uint_fast64_t directoryPathLength = directoryLength + currentEntryLength + 1;
char* directoryPath;
directoryPath = alloca(sizeof(*directoryPath) * (directoryPathLength + 1));
strncpy(directoryPath, directory, directoryLength);
directoryPath[directoryLength] = '\0';
util_append(directoryPath + directoryLength, directoryPathLength - 1 - directoryLength, directoryEntry->d_name, currentEntryLength);
directoryPath[directoryPathLength - 1] = '/';
directoryPath[directoryPathLength] = '\0';
if((error = util_deleteDirectory(directoryPath, false, emptyDirectoriesOnly)) != ERROR_NO_ERROR){
goto label_closeDir;
}
}else{
const uint_fast64_t filePathLength = directoryLength + currentEntryLength;
char* filePath;
filePath = alloca(sizeof(*filePath) * (filePathLength + 1));
strncpy(filePath, directory, directoryLength);
filePath[directoryLength] = '\0';
util_append(filePath + directoryLength, filePathLength - directoryLength, directoryEntry->d_name, currentEntryLength);
filePath[filePathLength] = '\0';
if(emptyDirectoriesOnly && isDirectoryEmpty != 0){
if((error = util_deleteFile(filePath)) != ERROR_NO_ERROR){
goto label_closeDir;
}
}
}
}
if(!preserveRoot && !(emptyDirectoriesOnly && isDirectoryEmpty != 0)){
if(rmdir(directory) != 0){
return ERROR_(ERROR_FAILED_TO_DELETE_DIRECTORY, "Dir:'%s'. [%s]", directory, strerror(errno));
}
}
label_closeDir:
closedir(currentDirectory);
return ERROR(error);
}
// http://www.stroustrup.com/new_learning.pdf
ERROR_CODE util_readUserInput(char** s, int_fast64_t* charRead){
uint_fast16_t limit = 64;
*s = malloc(limit);
if(*s == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
// Skip leading whitespaces.
while (true) {
int_fast32_t c = fgetc(stdin);
if(c == EOF){
break;
}
if(!isspace(c) || c == '\n') {
ungetc(c, stdin);
break;
}
}
uint_fast64_t i = 0;
while (true) {
const int_fast32_t c = fgetc(stdin);
if(c == '\n' || c == '\0' || c == EOF){
(*s)[i] = '\0';
break;
}
(*s)[i] = c;
if(i == limit - 1) {
limit *= 2;
*s = realloc(*s, limit);
}
i++;
}
*charRead = i;
return ERROR(ERROR_NO_ERROR);
}
inline void util_replaceAllChars(char* s, const char a, const char b){
do{
if(*s == a)
*s = b;
}while(*s++);
}
// NOTE:(jan) If both strings are not '\0' terminated, strcat/strncat will jump/move based on unitialised values.
inline void util_append(char* a, const uint_fast64_t lengthA, char* b, const uint_fast64_t lengthB){
strncat(a, b, lengthB - (lengthA - lengthB));
}
inline int util_hash(uint8_t* s, uint_fast64_t length){
int hash = 0;
int c;
while (length-- != 0){
c = *s++;
hash = c + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
// sdbm - hash implementation. see(http://www.cse.yorku.ca/~oz/hash.html)
inline int util_hashString(const char* s, uint_fast64_t length){
return util_hash((uint8_t*) s, length);
}
inline ERROR_CODE util_createDirectory(const char* directory){
if(!util_fileExists(directory)){
if(mkdir(directory, 0700) == 0){
return ERROR(ERROR_NO_ERROR);
}else{
return ERROR_(ERROR_FAILED_TO_CREATE_DIRECTORY, "\"%s\" - %s", directory, strerror(errno));
}
}else{
return ERROR_(ERROR_ALREADY_EXIST, "\"%s\"", directory);
}
}
inline ERROR_CODE util_createAllDirectories(const char* path, const uint_fast64_t pathLength){
ERROR_CODE error = ERROR_NO_ERROR;
char* _path = alloca(sizeof(*_path) * (pathLength + 1));
strncpy(_path, path, pathLength);
_path[pathLength] = '\0';
uint_fast64_t searchOffset = 1;
for(;;){
const int_fast64_t offset = util_findFirst(_path + searchOffset, pathLength - searchOffset, '/');
if(offset == -1){
break;
}
const uint_fast64_t index = searchOffset + offset + 1;
const char tmp = _path[index];
_path[index] = '\0';
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ALREADY_EXIST);
if((error = util_createDirectory(_path)) != ERROR_NO_ERROR){
if(error != ERROR_ALREADY_EXIST){
break;
}else{
error = ERROR_NO_ERROR;
}
}
_path[index] = tmp;
searchOffset += offset + 1;
}
return ERROR(error);
}
inline bool util_isDirectory(const char* file_path){
struct stat fileInfo;
lstat(file_path, &fileInfo);
return S_ISDIR(fileInfo.st_mode);
}
inline bool util_startsWith(const char* s, const char c){
return s[0] == c;
}
inline int_fast32_t util_getNumAvailableProcessorCores(void){
return sysconf(_SC_NPROCESSORS_ONLN);
}
inline ERROR_CODE util_getBaseDirectory(char** baseDirectory, uint_fast64_t* baseDirectoryLength, char* url, uint_fast64_t urlLength){
const int_fast64_t firstSeperator = util_findFirst(url, urlLength, '/');
if(firstSeperator == -1){
return ERROR(ERROR_INVALID_REQUEST_URL);
}else{
// URL: /
const int_fast64_t secondSeperator = util_findFirst(url + firstSeperator + 1, urlLength - (firstSeperator + 1), '/');
if(secondSeperator == -1){
if(util_findLast(url + firstSeperator + 1, urlLength - (firstSeperator + 1) , '.') == -1){
// URL: /img
*baseDirectory = url + firstSeperator;
*baseDirectoryLength = urlLength - firstSeperator;
}else{
// URL: /img_001.png
*baseDirectory = url + firstSeperator;
*baseDirectoryLength = 1;
}
return ERROR(ERROR_NO_ERROR);
}else{
// URL: /img/img_001.png
*baseDirectory = url + firstSeperator;
*baseDirectoryLength = (secondSeperator - firstSeperator) + 1/*Include the second '/'*/;
return ERROR(ERROR_NO_ERROR);
}
}
}
inline ERROR_CODE util_replace(char* buffer, const uint_fast64_t bufferLength, uint_fast64_t* srcStringLength, const char* a, const uint_fast64_t stringLengthA, const char* b, const uint_fast64_t stringLengthB){
int_fast64_t searchOffset = 0;
int_fast64_t offset = 0;
while((offset = util_findFirst_s(buffer + searchOffset, *srcStringLength - offset, a, stringLengthA)) != -1){
searchOffset += offset;
// We can replace the string inplace.
if(stringLengthB == stringLengthA){
memcpy(buffer + searchOffset, b, stringLengthB);
}else{
if(stringLengthB < stringLengthA){
uint_fast64_t i;
for(i = searchOffset + stringLengthB; i < *srcStringLength + 1; i++){
buffer[i] = buffer[i + (stringLengthA - stringLengthB)];
}
memcpy(buffer + searchOffset, b, stringLengthB);
*srcStringLength -= stringLengthA - stringLengthB;
}else{
if(*srcStringLength + (stringLengthB - stringLengthA) > bufferLength){
return ERROR(ERROR_BUFFER_OVERFLOW);
}
uint_fast64_t i;
// searchOffset will always be >= 0, so we can safely cast to unsigned here.
for(i = 1 + *srcStringLength; i >= ((uint_fast64_t) searchOffset) + stringLengthA; i--){
buffer[i + (stringLengthB - stringLengthA)] = buffer[i];
}
memcpy(buffer + searchOffset, b, stringLengthB);
*srcStringLength += stringLengthB - stringLengthA;
}
}
searchOffset += stringLengthB;
}
return ERROR(ERROR_NO_ERROR);
}
inline char* util_trim(char* s, const uint_fast64_t length) {
char c;
uint_fast64_t i = -1;
do{
c = *(s + (length - ++i) - 1);
}while(isspace(c));
*(s + length - i) = '\0';
i = -1;
do{
c = *(s + ++i);
}while(isspace(c));
uint_fast64_t j;
for (j = 0; j < length; j++){
*(s + j) = *(s + j + i);
}
return s;
}
inline void util_printBuffer(void* buffer, uint_fast64_t length){
uint_fast64_t i;
for(i = 0; i < length; i++){
printf("%c", ((char*) buffer)[i]);
}
printf("\n");
}
inline char* util_getHomeDirectory(void){
#ifdef __linux__
char* homeDir = getenv("HOME");
if(homeDir != NULL){
return homeDir;
}else{
return getpwuid(getuid())->pw_dir;;
}
#elif _WIN32
ERROR: FUNCTION NOT IMPLEMENTED.
#else
ERROR: FUNCTION NOT IMPLEMENTED.
#endif
}
inline ERROR_CODE util_stringToInt(const char* s, int64_t* value){
char* endPtr;
*value = strtol(s, &endPtr, 10/*Decimal*/);
if((*value == 0 && endPtr == s) || *value == LONG_MIN || *value == LONG_MAX){
return ERROR_(ERROR_INVALID_STRING, "'%s' is not a valid number.", s);
}
return ERROR(ERROR_NO_ERROR);
}
// Note: Use PATH_MAX, for the size of 'dir'. (jan - 2019.01.23)
inline ERROR_CODE util_getCurrentWorkingDirectory(char* dir, const uint_fast64_t dirLength){
if(getcwd(dir, dirLength) == NULL){
return ERROR_(ERROR_ERROR, "%s", strerror(errno));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE util_getFileExtension(char** extension, uint_fast64_t* fileExtensionLength, char* fileName, const uint_fast64_t fileNameLength){
const int_fast64_t fileExtensionOffset = util_findLast(fileName, fileNameLength, '.');
if(fileExtensionOffset == -1){
return ERROR_(ERROR_INVALID_STRING, "%s does not contain the token '.'", fileName);
}
*fileExtensionLength = fileNameLength - (fileExtensionOffset + 1);
*extension = fileName + (fileExtensionOffset + 1);
return ERROR(ERROR_NO_ERROR);
}
inline char* util_getFileName(char* filePath, const uint_fast64_t filePathLength){
return filePath + (util_findLast(filePath, filePathLength, '/') + 1);
}
inline ERROR_CODE util_getFileDirectory(char* dir, char* filePath, const uint_fast64_t filePathLength){
const uint_fast64_t dirLength = util_findLast(filePath, filePathLength, '/');
if(dirLength <= 0){
return ERROR_(ERROR_INVALID_STRING, "The path '%s' does not contain a directory.", filePath);
}
strncpy(dir, filePath, dirLength);
dir[dirLength] = '\0';
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE util_renameFile(char* file, char* newName){
if(rename(file, newName) != 0){
return ERROR(ERROR_FAILED_TO_RENAME_FILE);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE util_renameFileRelative(char* dir, char* file, char* newName){
const int fileDescriptor = open(dir, O_RDONLY | O_DIRECTORY);
if(fileDescriptor == -1){
return ERROR_(ERROR_FAILED_TO_OPEN_DIRECTORY, "'%s'", strerror(errno));
}
if(renameat(fileDescriptor, file, fileDescriptor, newName) != 0){
return ERROR_(ERROR_FAILED_TO_RENAME_FILE, "'%s'", strerror(errno));
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE util_walkDirectory(LinkedList* list, const char* directory, bool listItemType){
ERROR_CODE error = ERROR_NO_ERROR;
DIR* currentDirectory = opendir(directory);
if(currentDirectory == NULL){
error = ERROR_FAILED_TO_OPEN_DIRECTORY;
goto label_closeDir;
}
const uint_fast64_t directoryLength = strlen(directory);
struct dirent* directoryEntry;
while((directoryEntry = readdir(currentDirectory)) != NULL){
// Avoid reentering current and parent directory.
const uint_fast64_t currentEntryLength = strlen(directoryEntry->d_name);
const bool selfOrParent = directoryEntry->d_name[0] == '.';
if(selfOrParent || (selfOrParent && directoryEntry->d_name[1] == '.')){
continue;
}
if(directoryEntry->d_type == DT_DIR){
const uint_fast64_t directoryPathLength = directoryLength + currentEntryLength + 1;
char* directoryPath;
directoryPath = (listItemType == UTIL_DIRECTORIES_ONLY) ? malloc(sizeof(*directoryPath) * (directoryPathLength + 1)) : alloca(sizeof(*directoryPath) * (directoryPathLength + 1));
strncpy(directoryPath, directory, directoryLength + 1);
util_append(directoryPath + directoryLength, directoryPathLength - 1 - directoryLength, directoryEntry->d_name, currentEntryLength);
directoryPath[directoryPathLength - 1] = '/';
directoryPath[directoryPathLength] = '\0';
if(listItemType == UTIL_DIRECTORIES_ONLY){
if((error = linkedList_add(list, directoryPath)) !=ERROR_NO_ERROR){
goto label_closeDir;
}
}
if((error = util_walkDirectory(list, directoryPath, listItemType)) != ERROR_NO_ERROR){
goto label_closeDir;
}
}else{
if(listItemType == UTIL_FILES_ONLY){
const uint_fast64_t pathLength = directoryLength + currentEntryLength;
char* path;
path = malloc(sizeof(*path) * (pathLength + 1));
strncpy(path, directory, directoryLength + 1);
util_append(path + directoryLength, pathLength - directoryLength, directoryEntry->d_name, currentEntryLength);
path[pathLength] = '\0';
if((error = linkedList_add(list, path)) !=ERROR_NO_ERROR){
goto label_closeDir;
}
}
}
}
label_closeDir:
closedir(currentDirectory);
return ERROR(error);
}
#endif
|
Ex05/herder
|
src/cache.c
|
#ifndef CACHE_C
#define CACHE_C
#include "cache.h"
local ERROR_CODE cache_initCacheObject(CacheObject*, uint8_t*, const uint_fast64_t, char*, const uint_fast64_t, char*, const uint_fast64_t);
local void cache_freeCacheObject(CacheObject*);
inline ERROR_CODE cache_init(Cache* cache, const uint_fast64_t numThreads, const uint_fast64_t size){
memset(cache, 0, sizeof(*cache));
if(sem_init(&cache->activeAcesses, 0, numThreads)){
return ERROR(ERROR_PTHREAD_SEMAPHOR_INITIALISATION_FAILED);
}
if(pthread_mutex_init(&cache->lock, NULL)){
return ERROR(ERROR_PTHREAD_MUTEX_INITIALISATION_FAILED);
}
cache->maxSize = size;
cache->threads = numThreads;
ERROR_CODE error;
if((error = linkedList_init(&cache->elements)) != ERROR_NO_ERROR){
goto label_return;
}
label_return:
return ERROR(error);
}
inline ERROR_CODE cache_initCacheObject(CacheObject* cacheObject, uint8_t* data, const uint_fast64_t size, char* fileLocation, const uint_fast64_t fileLocationLength, char* symbolicFileLocation, const uint_fast64_t symbolicFileLocationLength){
cacheObject->data = data;
cacheObject->size = size;
cacheObject->fileLocation = fileLocation;
cacheObject->fileLocationLength = fileLocationLength;
cacheObject->symbolicFileLocation = malloc(sizeof(*cacheObject->symbolicFileLocation) * (symbolicFileLocationLength + 1));
if(cacheObject->symbolicFileLocation == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(cacheObject->symbolicFileLocation, symbolicFileLocation, symbolicFileLocationLength);
cacheObject->symbolicFileLocation[symbolicFileLocationLength] = '\0';
cacheObject->symbolicFileLocationLength = symbolicFileLocationLength;
clock_gettime(CLOCK_MONOTONIC, &cacheObject->timeCheckin);
cacheObject->timeLastHit = cacheObject->timeCheckin;
cacheObject->totalHits = 1;
// Note:(jan) If there is no fileExtension, the offset will be 0, and the HTTP_ContentType hash will just be the entire file path.
cacheObject->fileExtensionOffset = util_findLast(fileLocation, fileLocationLength, '.') + 1;
return ERROR(ERROR_NO_ERROR);
}
inline void cache_free(Cache* cache){
LinkedListIterator it;
linkedList_initIterator(&it, &cache->elements);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
CacheObject* cacheObject = LINKED_LIST_ITERATOR_NEXT(&it);
free(cacheObject->data);
free(cacheObject->fileLocation);
free(cacheObject->symbolicFileLocation);
free(cacheObject);
}
linkedList_free(&cache->elements);
sem_destroy(&cache->activeAcesses);
pthread_mutex_destroy(&cache->lock);
}
inline ERROR_CODE cache_get(Cache* cache, CacheObject** cacheObject, char* symbolicFileLocation, const uint_fast64_t symbolicFileLocationLength){
ERROR_CODE error = ERROR_ENTRY_NOT_FOUND;
sem_wait(&cache->activeAcesses);
LinkedListIterator it;
linkedList_initIterator(&it, &cache->elements);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
CacheObject* o = LINKED_LIST_ITERATOR_NEXT(&it);
if(strncmp(symbolicFileLocation, o->symbolicFileLocation, symbolicFileLocationLength > o->symbolicFileLocationLength ? symbolicFileLocationLength : o->symbolicFileLocationLength) == 0){
*cacheObject = o;
clock_gettime(CLOCK_MONOTONIC, &o->timeLastHit);
o->totalHits++;
error = ERROR_NO_ERROR;
goto label_return;
}
}
label_return:
sem_post(&cache->activeAcesses);
return ERROR(error);
}
inline ERROR_CODE cache_load(Cache* cache, CacheObject** cacheObject, char* fileLocation, const uint_fast64_t fileLocationLength, char* symbolicFileLocation, const uint_fast64_t symbolicFileLocationLength){
struct stat fileInfo;
if(lstat(fileLocation, &fileInfo) == -1){
return ERROR_(ERROR_FAILED_TO_RETRIEV_FILE_INFO, "File:'%s'", fileLocation);
}
if(!S_ISREG(fileInfo.st_mode)){
return ERROR(ERROR_FAILED_TO_RETRIEV_FILE_INFO);
}
const uint_fast64_t fileSize = fileInfo.st_size;
FILE* file;
if((file = fopen(fileLocation, "r")) == NULL){
return ERROR(ERROR_FAILED_TO_LOAD_FILE);
}
uint8_t* data = malloc(sizeof(*data) * fileSize);
if(data == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
if(fread(data, sizeof(uint8_t), fileSize, file) != fileSize){
return ERROR(ERROR_FAILED_TO_LOAD_FILE);
}
*cacheObject = malloc(sizeof(**cacheObject));
if(*cacheObject == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
ERROR_CODE error;
if((error = cache_initCacheObject(*cacheObject, data, fileSize, fileLocation, fileLocationLength, symbolicFileLocation, symbolicFileLocationLength)) != ERROR_NO_ERROR){
return ERROR(error);
}
if(fclose(file) != 0){
return ERROR(ERROR_FAILED_TO_CLOSE_FILE);
}
// Lock cache.
pthread_mutex_lock(&cache->lock);
uint_fast64_t i;
for(i = 0; i < cache->threads; i++){
sem_wait(&cache->activeAcesses);
}
label_removeStaleCacheObjects:
if(cache->currentSize + (*cacheObject)->size > cache->maxSize){
// TODO: Implement better algorithem to delete old cacheObjects.
uint_fast64_t maxSize = 0;
CacheObject* staleObject = NULL;
LinkedListIterator it;
linkedList_initIterator(&it, &cache->elements);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
CacheObject* o = LINKED_LIST_ITERATOR_NEXT(&it);
if(o->size >= maxSize){
staleObject = o;
}
}
cache->currentSize -= staleObject->size;
if(cache->currentSize + (*cacheObject)->size > cache->maxSize){
goto label_removeStaleCacheObjects;
}
// Unlock cache to remove entry.
for(; i > 0; i--){
sem_post(&cache->activeAcesses);
}
pthread_mutex_unlock(&cache->lock);
ERROR_CODE error;
if((error = cache_remove(cache, staleObject)) != ERROR_NO_ERROR){
return ERROR(error);
}
// Relock cache.
pthread_mutex_lock(&cache->lock);
for(i = 0; i < cache->threads; i++){
sem_wait(&cache->activeAcesses);
}
}
linkedList_add(&cache->elements, *cacheObject);
cache->currentSize += (*cacheObject)->size;
// Unlock cache.
for(; i > 0; i--){
sem_post(&cache->activeAcesses);
}
pthread_mutex_unlock(&cache->lock);
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE cache_remove(Cache* cache, CacheObject* cacheObject){
ERROR_CODE error;
pthread_mutex_lock(&cache->lock);
uint_fast64_t i;
for(i = 0; i < cache->threads; i++){
sem_wait(&cache->activeAcesses);
}
if((error = linkedList_remove(&cache->elements, cacheObject)) != ERROR_NO_ERROR){
return ERROR_(error, "Failed to remove cacheobject '%s' from cache. [%s]", cacheObject->symbolicFileLocation, util_toErrorString(error));
}
cache->currentSize += cacheObject->size;
for(; i > 0; i--){
sem_post(&cache->activeAcesses);
}
pthread_mutex_unlock(&cache->lock);
cache_freeCacheObject(cacheObject);
free(cacheObject);
return ERROR(error);
}
void cache_freeCacheObject(CacheObject* cacheObject){
free(cacheObject->data);
free(cacheObject->fileLocation);
free(cacheObject->symbolicFileLocation);
}
#endif
|
Ex05/herder
|
src/linkedList.c
|
#ifndef LINKED_LIST_C
#define LINKED_LIST_C
#include "linkedList.h"
local Node* linkedList_initNode(void*);
inline ERROR_CODE linkedList_init(LinkedList* list) {
memset(list, 0, sizeof(*list));
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE linkedList_add(LinkedList* list, void* data) {
Node* node = linkedList_initNode(data);
if(LINKED_LIST_IS_EMPTY(list)) {
list->tail = node;
}else{
node->next = list->tail;
list->tail = node;
}
list->length++;
return ERROR(ERROR_NO_ERROR);
}
inline Node* linkedList_initNode(void* data){
Node* node = malloc(sizeof(*node));
if(node == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
}
node->data = data;
node->next = NULL;
return node;
}
inline void linkedList_initIterator(LinkedListIterator* it, LinkedList* list) {
it->node = list->tail;
}
inline Node* linkedList_iteratorNextNode(LinkedListIterator* it){
Node* node = it->node;
it->node = node->next;
return node;
}
inline void linkedList_free(LinkedList* list){
LinkedListIterator it;
linkedList_initIterator(&it, list);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
free(linkedList_iteratorNextNode(&it));
}
}
inline ERROR_CODE linkedList_remove(LinkedList* list, void* data){
/* This is Linus Torvalds double Pointer based approach to removing nodes in LinkedLists, which compared to
other approachs (like the one shown below) removes a branch from the code.
*/
Node** node;
for(node = &list->tail; *node;){
Node* current = *node;
if(current->data == data){
*node = current->next;
list->length--;
free(current);
return ERROR(ERROR_NO_ERROR);
}else{
node = ¤t->next;
}
}
return ERROR(ERROR_FAILED_TO_REMOVE_NODE);
/*
LinkedListIterator it;
linkedList_initIterator(&it, list);
Node* prev = NULL;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Node* current = linkedList_iteratorNextNode(&it);
if(current->data == data){
// If the searched element is the only one in the list.
if(prev == NULL){
free(list->tail);
list->length--;
list->tail = NULL;
}else{
prev->next = current->next;
list->length--;
free(current);
}
}
prev = current;
}
*/
}
#endif
|
Ex05/herder
|
src/http.h
|
<filename>src/http.h<gh_stars>0
#ifndef HTTP_H
#define HTTP_H
#include "util.h"
#include "linkedList.h"
#include "cache.h"
#define HTTP_VERSION_1_0 "HTTP/1.0"
#define HTTP_VERSION_1_1 "HTTP/1.1"
#define HTTP_VERSION_2_0 "HTTP/2.0"
#define HTTP_ADD_HEADER_FIELD(request, _name, _value) do{ \
HTTP_HeaderField* headerField ## _name = malloc(sizeof(*headerField ## _name)); \
memset(headerField ## _name, 0, sizeof(*headerField ## _name)); \
const uint_fast64_t headerFieldHostNameLength = strlen(# _name); \
headerField ## _name->name = malloc(sizeof(headerField ## _name->name) * (headerFieldHostNameLength + 1)); \
if(headerField ## _name->name == NULL){ \
UTIL_LOG_ERROR_("%s.", util_toErrorString(ERROR_OUT_OF_MEMORY)); \
} \
strncpy(headerField ## _name->name, # _name, headerFieldHostNameLength + 1); \
\
const uint_fast64_t headerField ## _nameValueLength = strlen(_value); \
headerField ## _name->value = malloc(sizeof(headerField ## _name->value) * (headerField ## _nameValueLength + 1)); \
strncpy(headerField ## _name->value, _value, headerField ## _nameValueLength + 1); \
\
linkedList_add(&request.headerFields, headerField ## _name);\
}while(0)
#define HTTP_PROCESSING_BUFFER_SIZE 8192 //16384
#define http_parseRsponseType http_parseRequestType
typedef enum{
REQUEST_TYPE_UNKNOWN = 0,
REQUEST_TYPE_GET = 1,
REQUEST_TYPE_HEAD,
REQUEST_TYPE_POST,
REQUEST_TYPE_PUT,
REQUEST_TYPE_DELETE,
REQUEST_TYPE_TRACE,
REQUEST_TYPE_OPTIONS,
REQUEST_TYPE_CONNECT,
REQUEST_TYPE_PATCH
}HTTP_RequestType;
typedef HTTP_RequestType HTTP_ResponseType;
typedef enum{
// NOTE: Update HTTP_STATUSCODE_MAPPING_ARRAY & HTTP_STATUS_MESSAGE_MAPPING_ARRAY in 'http.c' if you change values in here.
_100_CONTINUE = 0,
_101_SWITCHING_PROTOCOLS,
_102_PROCESSING,
_200_OK,
_201_CREATED,
_202_ACCEPTED,
_203_NON_AUTHORATIVE_INFORMATION,
_204_NO_CONTENT,
_205_RESET_CONTROL,
_206_PARTIAL_CONTENT,
_207_MULTI_STATUS,
_208_ALREADY_REPORTED,
_226_IM_USED,
_300_MULTIPLE_CHOICES,
_301_MOVED_PERMANENTLY,
_302_FOUND,
_303_SEE_OTHER,
_304_NOT_MODIFIED,
_305_USE_PROXY,
_307_TEMPORARY_REDIRECT,
_308_PERMANENT_REDIRECT,
_400_BAD_REQUEST,
_401_UNAUTHORIZED,
_402_PAYMENT_REQUIRED,
_403_FORBIDDEN,
_404_NOT_FOUND,
_405_METHOD_NOT_ALLOWED,
_406_NOT_ACCEPTABLE,
_407_PROXY_AUTHENTICATION_REQUIRED,
_408_REQUEST_TIMEOUT,
_409_CONFLICT,
_410_GONE,
_411_LENGTH_REQUIRED,
_412_PRECONDITION_FAILED,
_413_PAYLOAD_TOO_LARGE,
_414_REQUEST_URI_TOO_LARGE,
_415_UNSUPPORTED_MEDIA_TYPE,
_416_REQUEST_RANGE_NOT_SATISFIABLE,
_417_EXPECTATION_FAILED,
_418_IM_A_TEAPOT,
_421_MISDIRECTED_REQUEST,
_422_UNPROCESSABLE_ENTITY,
_423_LOCKED,
_424_FAILED_DEPENDENCY,
_426_UPGRADE_REQUIRED,
_428_PRECONDITION_REQUIRED,
_429_TOO_MANY_REQUESTS,
_431_REQUEST_HEADER_FIELD_TOO_LARGE,
_444_CONNECTION_CLOSED_WITHOUT_RESPONSE,
_451_UNAVAILABLE_FOR_LEAGAL_REASON,
_499_CLIENT_CLOSED_REQUEST,
_500_INTERNAL_SERVER_ERROR,
_501_NOT_IMPLEMENTED,
_502_BAD_GATEWAY,
_503_SERVICE_UYNAVAILABLE,
_504_GATEWAY_TIMEOUT,
_505_HTTP_VERSION_NOT_SUPPORTED,
_506_VARIANT_ALSO_NEGOTIATES,
_507_INSUFFIECENT_STORAGE,
_508_LOOP_DETECTED,
_510_NOT_EXTENDED,
_511_NETWORK_AUTHENTICATION_REQUIRED,
_599_NETWORK_CONNECTION_TIMEOUT_ERROR
}HTTP_StatusCode;
typedef enum{
HTTP_CONTENT_TYPE_TEXT_HTML = 0,
HTTP_CONTENT_TYPE_TEXT_CSS,
HTTP_CONTENT_TYPE_APPLICATION_JAVASCRIPT,
HTTP_CONTENT_TYPE_APPLICATION_JSON,
HTTP_CONTENT_TYPE_APPLICATION_ZIP,
HTTP_CONTENT_TYPE_IMAGE_JPG,
HTTP_CONTENT_TYPE_IMAGE_PNG,
HTTP_CONTENT_TYPE_IMAGE_SVG,
HTTP_CONTENT_TYPE_IMAGE_ICON
}HTTP_ContentType;
typedef struct{
LinkedList headerFields;
char httpVersion[9];
HTTP_RequestType type;
char* requestURL;
uint_fast16_t urlLength;
int8_t* data;
uint_fast64_t bufferSize;
uint_fast64_t dataLength;
uint_fast64_t getParameterLength;
char* getParameter;
}HTTP_Request;
typedef struct{
LinkedList headerFields;
char httpVersion[9];
HTTP_ContentType contentType;
char* statusMsg;
int_fast16_t statusCode;
uint_fast64_t statusMsgLength;
int8_t* data;
uint_fast64_t bufferSize;
uint_fast64_t dataLength;
bool staticContent;
CacheObject* cacheObject;
}HTTP_Response;
typedef struct{
char* name;
uint_fast64_t nameLength;
char* value;
uint_fast64_t valueLength;
}HTTP_HeaderField;
ERROR_CODE http_initRequest(HTTP_Request*, const char*, const uint_fast64_t, void*, uint_fast64_t, const char[], const HTTP_RequestType);
ERROR_CODE http_initRequest_(HTTP_Request*, void*, uint_fast64_t, const HTTP_RequestType);
ERROR_CODE http_initResponse(HTTP_Response*, void*, uint_fast64_t);
ERROR_CODE http_initheaderField(HTTP_HeaderField*, char*, const uint_fast64_t, char*, const uint_fast64_t);
ERROR_CODE http_addHeaderField(HTTP_Request*, char*, const uint_fast64_t, char*, const uint_fast64_t);
HTTP_HeaderField* http_getHeaderField(HTTP_Request*, char*);
void http_freeHTTP_Request(HTTP_Request*);
void http_freeHTTP_Response(HTTP_Response*);
HTTP_RequestType http_parseRequestType(const char* const, const uint_fast64_t);
HTTP_ContentType http_getContentType(const char*, const uint64_t);
const char* http_getStatusMsg(HTTP_StatusCode);
const char* http_getRequestType(HTTP_RequestType);
int_fast16_t http_getStatusCode(HTTP_StatusCode);
ERROR_CODE http_sendRequest(HTTP_Request*, HTTP_Response*, const int_fast32_t);
ERROR_CODE http_sendResponse(HTTP_Response*, const int_fast32_t);
ERROR_CODE http_receiveResponse(HTTP_Response*, const int_fast32_t);
ERROR_CODE http_receiveRequest(HTTP_Request*, const int_fast32_t);
HTTP_StatusCode http_translateStatusCode(const int_fast16_t);
ERROR_CODE http_openConnection(int_fast32_t*, const char*, const uint_fast16_t);
ERROR_CODE http_closeConnection(int_fast32_t);
void http_setHTTP_Version(HTTP_Response*, const char[__require 8]);
const char* http_contentTypeToString(const HTTP_ContentType, uint_fast64_t*);
#endif
|
Ex05/herder
|
src/mediaLibrary.h
|
#ifndef MEDIA_LIBRARY_H
#define MEDIA_LIBRARY_H
#include "util.h"
#include <dirent.h>
#include "linkedList.h"
#include "propertyFile.h"
typedef struct{
FILE* libraryFile;
char* libraryFileLocation;
uint_fast64_t libraryFileLocationLength;
LinkedList shows;
Version version;
volatile bool initialised;
}MediaLibrary;
typedef struct{
char* name;
uint_fast64_t nameLength;
LinkedList seasons;
}Show;
typedef struct{
uint_fast16_t number;
LinkedList episodes;
}Season;
typedef struct{
uint_fast64_t nameLength;
uint_fast16_t number;
uint_fast16_t fileExtensionLength;
char* fileExtension;
char* name;
}Episode;
typedef struct{
char* showName;
char* name;
char* fileExtension;
char* path;
char* fileName;
uint_fast64_t pathLength;
uint_fast64_t showNameLength;
uint_fast64_t nameLength;
uint_fast64_t fileNameLength;
uint_fast16_t fileExtensionLength;
int_fast16_t season;
int_fast16_t episode;
}EpisodeInfo;
ERROR_CODE mediaLibrary_init(MediaLibrary*, const char*, const uint_fast64_t);
void mediaLibrary_free(MediaLibrary*);
ERROR_CODE mediaLibrary_addShow(MediaLibrary*, Show**, const char*, const uint_fast64_t);
ERROR_CODE mediaLibrary_removeShow(MediaLibrary*, const char*, const uint_fast64_t);
ERROR_CODE medialibrary_removeEpisode(MediaLibrary*, Show* show, Season*, Episode*, const bool);
ERROR_CODE medialibrary_getShow(MediaLibrary*, Show**, const char*, const uint_fast64_t);
ERROR_CODE mediaLibrary_addSeason(MediaLibrary*, Season**, Show*, const uint_fast16_t);
ERROR_CODE medialibrary_getSeason(Show*, Season**, const uint_fast16_t);
ERROR_CODE mediaLibrary_addEpisode(MediaLibrary*, Episode**, Show*, Season*, const uint_fast16_t, const char*, const uint_fast64_t, const char*, const uint_fast16_t, const bool);
ERROR_CODE mediaLibrary_getEpisode(Season*, Episode**, const uint_fast16_t);
ERROR_CODE mediaLibrary_extractEpisodeInfo(EpisodeInfo*, LinkedList*, char*, const uint_fast64_t);
ERROR_CODE mediaLibrary_initEpisodeInfo(EpisodeInfo*);
ERROR_CODE mediaLibrary_initEpisodeInfo_(EpisodeInfo*, char*, const uint_fast64_t);
ERROR_CODE mediaLibrary_extractPrefixedNumber(char*, uint_fast64_t, int_fast16_t*, const char);
void mediaLibrary_freeEpisodeInfo(EpisodeInfo*);
ERROR_CODE mediaLibrary_sortSeasons(Season***, LinkedList*);
ERROR_CODE mediaLibrary_sortEpisodes(Episode***, LinkedList*);
void mediaLibrary_fillEpisodeInfo(EpisodeInfo*, Show*, Season*, Episode*);
ERROR_CODE mediaLibrary_renameEpisode(MediaLibrary*, Show*, Season*, Episode*, char*, const uint_fast64_t);
ERROR_CODE mediaLibrary_saveEpisodeToDisk(MediaLibrary*, Show*, Season*, Episode*);
#endif
/*
Show_Name [uint64_t + ~ ],
Season_Number [uint16_t],
Episode_Number [uint16_t],
Episode_Name [uint64_t + ~ ],
File_Extension [uint16_t + ~ ]
*/
/*
URL: '/showInfo'
Num_Seasons,
{
Number,
Num_Episodes,
{
Number,
NameLength,
Name,
FileExtensionLength,
FileExtension
}
}
*/
|
Ex05/herder
|
src/herder.c
|
<filename>src/herder.c
#include "herder.h"
#include "util.c"
#include "linkedList.c"
#include "http.c"
#include "argumentParser.c"
#include "propertyFile.c"
#include "mediaLibrary.c"
#define HTTP_PROCESSING_BUFFER_SIZE 8192 //16384
ERROR_CODE herder_pullShowList(LinkedList* shows, Property* remoteHost, Property* remotePort){
ERROR_CODE error = ERROR_NO_ERROR;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const char url[] = "/shows";
const uint_fast64_t urlLength = strlen(url);
HTTP_Request request;
if((error = http_initRequest(&request, url, urlLength, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_GET)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_Response response;
if((error = http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
if((error = http_closeConnection(socketFD)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
if(response.statusCode != _200_OK){
error = ERROR_SERVER_ERROR;
goto label_freeRequest;
}
uint_fast64_t readOffset = 0;
const uint_fast64_t numShows = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
if((error = linkedList_init(shows)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
uint_fast64_t i;
for(i = 0; i < numShows; i++){
const uint_fast64_t nameLength = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
Show* show = malloc(sizeof(*show));
medialibrary_initShow(show, (char*) response.data + readOffset, nameLength);
readOffset += nameLength;
linkedList_add(shows, show);
}
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
return ERROR(error);
}
ERROR_CODE herder_addShow(Property* remoteHost, Property* remotePort, const char* showName, const uint_fast64_t showNameLength){
ERROR_CODE error = ERROR_NO_ERROR;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const char url[] = "/addShow";
HTTP_Request request;
if((error = http_initRequest(&request, url, strlen(url), httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_POST)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_ADD_HEADER_FIELD(request, Host, host);
util_uint64ToByteArray(request.data + request.dataLength, showNameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, showName, showNameLength);
request.dataLength += showNameLength;
HTTP_Response response;
http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
http_closeConnection(socketFD);
const uint_fast64_t returnCode = util_byteArrayTo_uint64(response.data);
if(response.statusCode != _200_OK){
error = ERROR_INVALID_STATUS_CODE;
UTIL_LOG_CONSOLE_(LOG_ERR, "Server_status:'%s'.", http_getStatusMsg(response.statusCode));
}else{
if(response.dataLength != sizeof(uint64_t)){
error = ERROR_INVALID_CONTENT_LENGTH;
}else{
if(returnCode != ERROR_NO_ERROR){
if(returnCode == ERROR_DUPLICATE_ENTRY){
error = ERROR_DUPLICATE_ENTRY;
}else{
error = ERROR_INVALID_RETURN_CODE;
}
}
}
}
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
return ERROR(error);
}
ERROR_CODE herder_removeShow(Property* remoteHost, Property* remotePort, const char* showName, const uint_fast64_t showNameLength){
ERROR_CODE error = ERROR_NO_ERROR;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const char url[] = "/removeShow";
HTTP_Request request;
if((error = http_initRequest(&request, url, strlen(url), httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_POST)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_ADD_HEADER_FIELD(request, Host, host);
util_uint64ToByteArray(request.data + request.dataLength, showNameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, showName, showNameLength);
request.dataLength += showNameLength;
HTTP_Response response;
http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
http_closeConnection(socketFD);
const ERROR_CODE returnCode = util_byteArrayTo_uint64(response.data);
if(response.statusCode != _200_OK){
error = ERROR_INVALID_STATUS_CODE;
UTIL_LOG_CONSOLE_(LOG_ERR, "Server_status:'%s'.", http_getStatusMsg(response.statusCode));
}else{
if(response.dataLength != sizeof(uint64_t)){
error = ERROR_INVALID_CONTENT_LENGTH;
}else{
error = returnCode;
}
}
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
return ERROR(error);
}
ERROR_CODE herder_addEpisode(Property* remoteHost, Property* remotePort, Property* libraryDirectory, EpisodeInfo* episodeInfo){
ERROR_CODE error = ERROR_NO_ERROR;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const char url[] = "/add";
HTTP_Request request;
if((error = http_initRequest(&request, url, strlen(url), httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_POST)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_ADD_HEADER_FIELD(request, Host, host);
// ShowName.
util_uint64ToByteArray(request.data + request.dataLength, episodeInfo->showNameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, episodeInfo->showName, episodeInfo->showNameLength);
request.dataLength += episodeInfo->showNameLength;
// EpisodeName.
util_uint64ToByteArray(request.data + request.dataLength, episodeInfo->nameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, episodeInfo->name, episodeInfo->nameLength);
request.dataLength += episodeInfo->nameLength;
// Season.
util_uint16ToByteArray(request.data + request.dataLength, episodeInfo->season);
request.dataLength += sizeof(uint16_t);
// Episode.
util_uint16ToByteArray(request.data + request.dataLength, episodeInfo->episode);
request.dataLength += sizeof(uint16_t);
// FileExtension.
util_uint16ToByteArray(request.data + request.dataLength, episodeInfo->fileExtensionLength);
request.dataLength += sizeof(uint16_t);
memcpy(request.data + request.dataLength, episodeInfo->fileExtension, episodeInfo->fileExtensionLength);
request.dataLength += episodeInfo->showNameLength;
HTTP_Response response;
http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
http_closeConnection(socketFD);
uint_fast64_t readOffset = 0;
error = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
if(error != ERROR_NO_ERROR){
if(error == ERROR_NAME_MISSMATCH || ERROR_DUPLICATE_ENTRY){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to add Season:%02" PRIdFAST16 " Episode:%02" PRIdFAST16 " of '%s' to the library, an entry for this episode %s. [%s]", episodeInfo->season, episodeInfo->episode, episodeInfo->showName, error == ERROR_NAME_MISSMATCH ? "with a different name is already present" : "is already present.", util_toErrorString(error));
}
goto label_freeRequest;
}
char* path;
uint_fast64_t pathLength;
HERDER_CONSTRUCT_RELATIVE_FILE_PATH(&path, &pathLength, episodeInfo);
const uint_fast64_t fileDstLength = (libraryDirectory->entry->length - 1) + pathLength + episodeInfo->fileExtensionLength + 1;
char* fileDst = alloca(sizeof(*fileDst) * (fileDstLength + 1));
uint_fast64_t writeOffset = 0;
strncpy(fileDst + writeOffset, (char*) libraryDirectory->buffer, libraryDirectory->entry->length - 1);
writeOffset += libraryDirectory->entry->length - 1;
strncpy(fileDst + writeOffset, path, pathLength);
writeOffset += pathLength;
fileDst[writeOffset] = '\0';
if((error = util_createAllDirectories(fileDst, fileDstLength)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
if((error = util_fileCopy(episodeInfo->path, fileDst)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
if(util_deleteFile(episodeInfo->path) != ERROR_NO_ERROR){
goto label_freeRequest;
}
// TODO: Inform server that something went wrong and stuff should be removed from the library in case of failed file copy. (jan - 2018.11.28)
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
return ERROR(error);
}
ERROR_CODE herder_removeEpisode(Property* remoteHost, Property* remotePort, Property* libraryDirectory, EpisodeInfo* episodeInfo){
ERROR_CODE error = ERROR_NO_ERROR;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const char url[] = "/removeEpisode";
HTTP_Request request;
if((error = http_initRequest(&request, url, strlen(url), httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_POST)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_ADD_HEADER_FIELD(request, Host, host);
// ShowName.
util_uint64ToByteArray(request.data + request.dataLength, episodeInfo->showNameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, episodeInfo->showName, episodeInfo->showNameLength);
request.dataLength += episodeInfo->showNameLength;
// Season.
util_uint16ToByteArray(request.data + request.dataLength, episodeInfo->season);
request.dataLength += sizeof(uint16_t);
// Episode.
util_uint16ToByteArray(request.data + request.dataLength, episodeInfo->episode);
request.dataLength += sizeof(uint16_t);
HTTP_Response response;
http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
http_closeConnection(socketFD);
uint_fast64_t readOffset = 0;
error = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
if(error != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to remove Season:%02" PRIdFAST16 " Episode:%02" PRIdFAST16 " of '%s' from the library. [%s]", episodeInfo->season, episodeInfo->episode, episodeInfo->showName, util_toErrorString(error));
goto label_freeRequest;
}
char* relativePath;
uint_fast64_t relativePathLength;
HERDER_CONSTRUCT_RELATIVE_FILE_PATH(&relativePath, &relativePathLength, episodeInfo);
const uint_fast64_t absoluteFilePathLength = (libraryDirectory->entry->length - 1) + relativePathLength + 1;
char* absoluteFilePath = alloca(sizeof(*absoluteFilePath) * (absoluteFilePathLength + 1));
uint_fast64_t writeOffset = 0;
strncpy(absoluteFilePath + writeOffset, (char*) libraryDirectory->buffer, libraryDirectory->entry->length - 1);
writeOffset += libraryDirectory->entry->length - 1;
strncpy(absoluteFilePath + writeOffset, relativePath, relativePathLength);
writeOffset += relativePathLength;
absoluteFilePath[writeOffset] = '\0';
// Remove file/episode from disk.
if((error = util_deleteFile(absoluteFilePath)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to remove Season:%02" PRIdFAST16 " Episode:%02" PRIdFAST16 " of '%s' from the library. [%s]", episodeInfo->season, episodeInfo->episode, episodeInfo->showName, util_toErrorString(error));
goto label_freeRequest;
}
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
return ERROR(error);
}
ERROR_CODE herder_extractShowInfo(Property* remoteHost, Property* remotePort, EpisodeInfo* episodeInfo){
ERROR_CODE error;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const uint_fast64_t fileNameOffset = util_findLast(episodeInfo->path, episodeInfo->pathLength, '/') + 1;
const char* fileName = episodeInfo->path + fileNameOffset;
const uint_fast64_t fileNameLength = episodeInfo->pathLength - fileNameOffset;
const char url[] = "/extractShowInfo";
if((error = util_getFileExtension(&episodeInfo->fileExtension,(uint_fast64_t*) &episodeInfo->fileExtensionLength, episodeInfo->path, episodeInfo->pathLength)) != ERROR_NO_ERROR){
if(error == ERROR_INVALID_STRING){
error = ERROR_INVALID_FILE_EXTENSION;
}
goto label_unMap;
}
episodeInfo->fileExtensionLength = strlen(episodeInfo->fileExtension);
HTTP_Request request;
if((error = http_initRequest(&request, url, strlen(url), httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_POST)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_ADD_HEADER_FIELD(request, Host, host);
util_uint64ToByteArray(request.data + request.dataLength, fileNameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, fileName, fileNameLength);
request.dataLength += fileNameLength;
HTTP_Response response;
http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
http_closeConnection(socketFD);
if(response.statusCode == _200_OK){
uint_fast64_t readOffset = 0;
uint_fast64_t returnCode = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
if(returnCode != ERROR_NO_ERROR && returnCode != ERROR_INCOMPLETE){
error = returnCode;
}else{
episodeInfo->showNameLength = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
if(episodeInfo->showNameLength != 0){
episodeInfo->showName = malloc(sizeof(*episodeInfo->showName) * (episodeInfo->showNameLength) + 1);
if(episodeInfo->showName == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(episodeInfo->showName, (char*) (response.data + readOffset), episodeInfo->showNameLength);
episodeInfo->showName[episodeInfo->showNameLength] = '\0';
readOffset += episodeInfo->showNameLength;
}else{
episodeInfo->showName = NULL;
}
episodeInfo->nameLength = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
if(episodeInfo->nameLength != 0){
episodeInfo->name = malloc(sizeof(*episodeInfo->name) * (episodeInfo->nameLength + 1));
if(episodeInfo->name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(episodeInfo->name, (char*) (response.data + readOffset), episodeInfo->nameLength);
readOffset += episodeInfo->nameLength;
}else{
episodeInfo->name = NULL;
}
episodeInfo->season = util_byteArrayTo_uint16(response.data + readOffset);
readOffset += sizeof(uint16_t);
episodeInfo->episode = util_byteArrayTo_uint16(response.data + readOffset);
readOffset += sizeof(uint16_t);
}
}else{
error = ERROR_INVALID_STATUS_CODE;
UTIL_LOG_CONSOLE_(LOG_ERR, "Server_status:'%s'.", http_getStatusMsg(response.statusCode));
}
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
return ERROR(error);
}
ERROR_CODE herder_add(Property* remoteHost, Property* remotePort, Property* libraryDirectory, EpisodeInfo* episodeInfo){
ERROR_CODE error;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const char url[] = "/add";
HTTP_Request request;
if((error = http_initRequest(&request, url, strlen(url), httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_POST)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_ADD_HEADER_FIELD(request, Host, host);
// ShowName.
util_uint64ToByteArray(request.data + request.dataLength, episodeInfo->showNameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, episodeInfo->showName, episodeInfo->showNameLength);
request.dataLength += episodeInfo->showNameLength;
// EpisodeName.
util_uint64ToByteArray(request.data + request.dataLength, episodeInfo->nameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, episodeInfo->name, episodeInfo->nameLength);
request.dataLength += episodeInfo->nameLength;
// Season.
util_uint16ToByteArray(request.data + request.dataLength, episodeInfo->season);
request.dataLength += sizeof(uint16_t);
// Episode.
util_uint16ToByteArray(request.data + request.dataLength, episodeInfo->episode);
request.dataLength += sizeof(uint16_t);
// FileExtension.
util_uint16ToByteArray(request.data + request.dataLength, episodeInfo->fileExtensionLength);
request.dataLength += sizeof(uint16_t);
memcpy(request.data + request.dataLength, episodeInfo->fileExtension, episodeInfo->fileExtensionLength);
request.dataLength += episodeInfo->showNameLength;
HTTP_Response response;
http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
http_closeConnection(socketFD);
uint_fast64_t readOffset = 0;
error = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
if(error != ERROR_NO_ERROR){
if(error == ERROR_NAME_MISSMATCH || ERROR_DUPLICATE_ENTRY){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to add Season:%02" PRIdFAST16 " Episode:%02" PRIdFAST16 " of '%s' to the library, an entry for this episode %s. [%s]", episodeInfo->season, episodeInfo->episode, episodeInfo->showName, error == ERROR_NAME_MISSMATCH ? "with a different name is already present" : "is already present.", util_toErrorString(error));
}
goto label_freeRequest;
}
char* path;
uint_fast64_t pathLength;
HERDER_CONSTRUCT_RELATIVE_FILE_PATH(&path, &pathLength, episodeInfo);
const uint_fast64_t fileDstLength = (libraryDirectory->entry->length - 1) + pathLength;
char* fileDst = alloca(sizeof(*fileDst) * (fileDstLength + 1));
uint_fast64_t writeOffset = 0;
strncpy(fileDst + writeOffset, (char*) libraryDirectory->buffer, libraryDirectory->entry->length - 1);
writeOffset += libraryDirectory->entry->length - 1;
strncpy(fileDst + writeOffset, path, pathLength);
writeOffset += pathLength;
fileDst[writeOffset] = '\0';
if((error = util_createAllDirectories(fileDst, fileDstLength)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
if((error = util_fileCopy(episodeInfo->path, fileDst)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
if(util_deleteFile(episodeInfo->path) != ERROR_NO_ERROR){
goto label_freeRequest;
}
// TODO: Inform server that something went wrong and stuff should be removed from the library in case of failed file copy. (jan - 2018.11.28)
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
return ERROR(error);
}
/* printf("#define HASH_MP4 %d\n", util_hashString(".mp4"));
printf("#define HASH_MKV %d\n", util_hashString(".mkv"));
printf("#define HASH_AVI %d\n", util_hashString(".avi")); */
local inline bool herder_walkDirectoryAcceptFunction(const char* s, const uint_fast64_t length){
#define HASH_MP4 -1839843325
#define HASH_MKV -1840171254
#define HASH_AVI -1938587738
switch(util_hashString(s, length)){
case HASH_MP4:
case HASH_MKV:
case HASH_AVI:{
return true;
}
default:
return false;
}
#undef HASH_MP4
#undef HASH_MKV
#undef HASH_AVI
}
ERROR_CODE herder_pullShowInfo(Property* remoteHost, Property* remotePort, Show* show){
ERROR_CODE error;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const char url[] = "/showInfo";
HTTP_Request request;
if((error = http_initRequest(&request, url, strlen(url), httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_POST)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_ADD_HEADER_FIELD(request, Host, host);
util_uint64ToByteArray(request.data + request.dataLength, show->nameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, show->name, show->nameLength + 1);
request.dataLength += show->nameLength + 1;
HTTP_Response response;
http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
http_closeConnection(socketFD);
if(response.statusCode == _200_OK){
uint_fast64_t readOffset = 0;
error = util_byteArrayTo_uint64(response.data);
readOffset += sizeof(uint64_t);
if(error != ERROR_NO_ERROR){
goto label_freeRequest;
}
// Num_Seasons.
uint_fast64_t numSeasons = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
if(numSeasons != 0){
for( ; numSeasons > 0; numSeasons--){
// Season_Number.
const uint_fast16_t seasonNumber = util_byteArrayTo_uint16(response.data + readOffset);
readOffset += sizeof(uint16_t);
Season* season;
season = malloc(sizeof(*season));
if((error = medialibrary_initSeason(season, seasonNumber)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
if((error = linkedList_add(&show->seasons, season)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
// Num_Episodes.
uint_fast64_t numEpisodes = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
for( ; numEpisodes > 0; numEpisodes--){
// Episode_Number.
const uint_fast16_t episodeNumber = util_byteArrayTo_uint16(response.data + readOffset);
readOffset += sizeof(uint16_t);
// Episode_NameLength.
uint_fast64_t nameLength = util_byteArrayTo_uint64(response.data + readOffset);
readOffset += sizeof(uint64_t);
// TODO: Remove memcpy into the stack. We can just point into the HTTP_PROCESSING_BUFFER since we malloc and memcpy in 'mediaLibrary_initEpisode' anyways. (jan - 2020.02.10)
// Episode_Name.
char* name = alloca(sizeof(*name) * (nameLength + 1));
memcpy(name, response.data + readOffset, nameLength + 1);
readOffset += nameLength + 1;
// File_ExtensionLength.
uint_fast16_t fileExtensionLength = util_byteArrayTo_uint16(response.data + readOffset);
readOffset += sizeof(uint16_t);
// File_Extension.
char* fileExtension = alloca(sizeof(*fileExtension) * (fileExtensionLength + 1));
memcpy(fileExtension, response.data + readOffset, fileExtensionLength + 1);
readOffset += fileExtensionLength + 1;
Episode* episode;
if((episode = malloc(sizeof(*episode))) == NULL){
error = ERROR_OUT_OF_MEMORY;
goto label_freeRequest;
}
if((medialibrary_initEpisode(episode, episodeNumber, name, nameLength, fileExtension, fileExtensionLength)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
if((error = linkedList_add(&season->episodes, episode)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
}
}
}
}else{
error = ERROR_INVALID_STATUS_CODE;
UTIL_LOG_CONSOLE_(LOG_ERR, "Server_status:'%s'.", http_getStatusMsg(response.statusCode));
}
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
return ERROR(error);
}
ERROR_CODE herder_renameEpisode(Property* remoteHost, Property* remotePort, Property* libraryDirectory, EpisodeInfo* info, const char* newEpisodeName, const uint_fast64_t newEpisodeNameLength){
ERROR_CODE error;
char* host = (char*) remoteHost->buffer;
uint_fast16_t port = util_byteArrayTo_uint64(remotePort->buffer);
void* httpProcessingBuffer;
if((error = util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE)) != ERROR_NO_ERROR){
goto label_unMap;
}
int_fast32_t socketFD;
if((error = http_openConnection(&socketFD, host, port)) != ERROR_NO_ERROR){
goto label_unMap;
}
const char url[] = "/renameEpisode";
HTTP_Request request;
if((error = http_initRequest(&request, url, strlen(url), httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_POST)) != ERROR_NO_ERROR){
goto label_freeRequest;
}
HTTP_ADD_HEADER_FIELD(request, Host, host);
// Show_Name.
util_uint64ToByteArray(request.data + request.dataLength, info->nameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, info->showName, info->nameLength + 1);
request.dataLength += info->nameLength + 1;
// Season_Number.
util_uint16ToByteArray(request.data + request.dataLength, info->season);
request.dataLength += sizeof(uint16_t);
// Episode_Number.
util_uint16ToByteArray(request.data + request.dataLength, info->episode);
request.dataLength += sizeof(uint16_t);
// New Episode_Name.
util_uint64ToByteArray(request.data + request.dataLength, newEpisodeNameLength);
request.dataLength += sizeof(uint64_t);
memcpy(request.data + request.dataLength, newEpisodeName, newEpisodeNameLength + 1);
request.dataLength += newEpisodeNameLength + 1;
HTTP_Response response;
http_initResponse(&response, httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
if((error = http_sendRequest(&request, &response, socketFD)) != ERROR_NO_ERROR){
goto label_freeResponse;
}
http_closeConnection(socketFD);
if(response.statusCode != _200_OK){
error = ERROR_INVALID_STATUS_CODE;
UTIL_LOG_CONSOLE_(LOG_ERR, "Server_status:'%s'.", http_getStatusMsg(response.statusCode));
}else{
if(response.dataLength != sizeof(uint64_t)){
error = ERROR_INVALID_CONTENT_LENGTH;
}else{
const uint_fast64_t returnCode = util_byteArrayTo_uint64(response.data);
error = returnCode;
}
}
label_freeRequest:
http_freeHTTP_Request(&request);
label_freeResponse:
http_freeHTTP_Response(&response);
label_unMap:
if(util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(ERROR_FAILED_TO_UNMAP_MEMORY));
}
char* path;
uint_fast64_t pathLength;
HERDER_CONSTRUCT_RELATIVE_FILE_PATH(&path, &pathLength, info);
const uint_fast64_t fileDstLength = (libraryDirectory->entry->length - 1) + pathLength + 1;
char* filePath = alloca(sizeof(*filePath) * (fileDstLength + 1));
uint_fast64_t writeOffset = 0;
strncpy(filePath + writeOffset, (char*) libraryDirectory->buffer, libraryDirectory->entry->length - 1);
writeOffset += libraryDirectory->entry->length - 1;
strncpy(filePath + writeOffset, path, pathLength);
writeOffset += pathLength;
filePath[writeOffset] = '\0';
char* fileDirectory = alloca(sizeof(*fileDirectory) * fileDstLength + 1);
if((error = util_getFileDirectory(fileDirectory, filePath, fileDstLength)) != ERROR_NO_ERROR){
goto label_return;
}
char* oldFileName = util_getFileName(filePath, fileDstLength);
// Build new fileName.
const uint_fast64_t newFileNameLength = info->showNameLength + 2/*_*/ + (2 * UTIL_UINT16_STRING_LENGTH) + 3 /*'e'/'s'/'.'*/ + newEpisodeNameLength + info->fileExtensionLength;
char* newFileName = alloca(sizeof(*newFileName) * (newFileNameLength + 1));
snprintf(newFileName, newFileNameLength, "%s_s%02" PRIdFAST16 "e%02" PRIdFAST16 "_%s.%s", info->showName, info->season, info->episode, newEpisodeName, info->fileExtension);
util_replaceAllChars(newFileName, ' ', '_');
// Rename file on disk.
if((error = util_renameFileRelative(fileDirectory, oldFileName, newFileName)) != ERROR_NO_ERROR){
goto label_return;
}
label_return:
return ERROR(error);
}
ERROR_CODE herder_convertToMP3(Property* remoteHost, Property* remotePort, Property* libraryDirectory, const char* showName, const uint_fast64_t showNameLength){
ERROR_CODE error = ERROR_NO_ERROR;
#define HERDER_STRING_CONSTANT_AUDIO "audio/"
const uint_fast64_t audioStringLength = strlen(HERDER_STRING_CONSTANT_AUDIO);
const uint_fast64_t audioDirectoryLength = (libraryDirectory->entry->length - 1) + audioStringLength;
char* audioDirectory = alloca(sizeof(*audioDirectory) * (audioDirectoryLength + 1));
memcpy(audioDirectory, libraryDirectory->buffer, libraryDirectory->entry->length - 1);
strncpy(audioDirectory + libraryDirectory->entry->length - 1, HERDER_STRING_CONSTANT_AUDIO, audioStringLength + 1);
#undef HERDER_STRING_CONSTANT_AUDIO
if(!util_directoryExists(audioDirectory)){
if((error = util_createDirectory(audioDirectory)) != ERROR_NO_ERROR){
goto label_return;
}
UTIL_LOG_INFO_("Created directory:'%s'.", audioDirectory);
}
const uint_fast64_t showDirectoryLength = audioDirectoryLength + showNameLength + 1/*'/'*/;
char* _showName = alloca(sizeof(*_showName) * showNameLength + 1);
strncpy(_showName, showName, showNameLength + 1);
util_replaceAllChars(_showName, ' ', '_');
char* showDirectory = alloca(sizeof(*showDirectory) * (showDirectoryLength + 1));
strncpy(showDirectory, audioDirectory, audioDirectoryLength);
strncpy(showDirectory + audioDirectoryLength, _showName, showNameLength);
showDirectory[audioDirectoryLength + showNameLength] = '/';
showDirectory[audioDirectoryLength + showNameLength + 1] = '\0';
if(!util_directoryExists(showDirectory)){
if((error = util_createDirectory(showDirectory)) != ERROR_NO_ERROR){
goto label_return;
}
UTIL_LOG_INFO_("Created directory:'%s'.", showDirectory);
}
Show show;
if((error = medialibrary_initShow(&show, showName, showNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
if((error = herder_pullShowInfo(remoteHost, remotePort, &show)) != ERROR_NO_ERROR){
goto label_freeShow;
}
LinkedListIterator seasonIterator;
linkedList_initIterator(&seasonIterator, &show.seasons);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&seasonIterator)){
Season* season = LINKED_LIST_ITERATOR_NEXT(&seasonIterator);
uint_fast64_t seasonDirectoryLength = showDirectoryLength + (showNameLength + 3/*' - '*/ + 7/*'Season_'*/ + UTIL_UINT16_STRING_LENGTH + 1/*'/'*/);
char* seasonDirectory = alloca(sizeof(*seasonDirectory) * (seasonDirectoryLength + 1));
seasonDirectoryLength = snprintf(seasonDirectory, seasonDirectoryLength + 1, "%s%s - Season_%02" PRIdFAST16 "/", showDirectory, _showName, season->number);
if(!util_directoryExists(seasonDirectory)){
if((error = util_createDirectory(seasonDirectory)) != ERROR_NO_ERROR){
goto label_return;
}
UTIL_LOG_INFO_("Created directory:'%s'.", seasonDirectory);
}
LinkedListIterator episodeIterator;
linkedList_initIterator(&episodeIterator, &season->episodes);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&episodeIterator)){
Episode* episode = LINKED_LIST_ITERATOR_NEXT(&episodeIterator);
uint_fast64_t episodePathLength = seasonDirectoryLength + showNameLength + episode->nameLength + (2 * UTIL_UINT16_STRING_LENGTH + 2/*'_s'*/ + 1/*'e'*/ + 1/*"_"*/ + 4/*'.mp3'*/);
char* episodePath = alloca(sizeof(*episodePath) * (episodePathLength + 1));
util_replaceAllChars(episode->name, ' ', '_');
episodePathLength = snprintf(episodePath, episodePathLength + 1, "%s%s_s%02" PRIdFAST16 "e%02"
PRIdFAST16 "_%s%s", seasonDirectory, _showName, season->number, episode->number, episode->name, ".mp3");
if(!util_fileExists(episodePath)){
EpisodeInfo episodeInfo;
mediaLibrary_fillEpisodeInfo(&episodeInfo, &show, season, episode);
char* relativePath;
uint_fast64_t relativePathLength;
HERDER_CONSTRUCT_RELATIVE_FILE_PATH(&relativePath, &relativePathLength, &episodeInfo);
const uint_fast64_t absoluteFilePathLength = (libraryDirectory->entry->length - 1) + relativePathLength + 1;
char* absoluteFilePath = alloca(sizeof(*absoluteFilePath) * (absoluteFilePathLength + 1));
uint_fast64_t writeOffset = 0;
strncpy(absoluteFilePath + writeOffset, (char*) libraryDirectory->buffer, libraryDirectory->entry->length - 1);
writeOffset += libraryDirectory->entry->length - 1;
strncpy(absoluteFilePath + writeOffset, relativePath, relativePathLength);
writeOffset += relativePathLength;
absoluteFilePath[writeOffset] = '\0';
uint_fast64_t ffmpegCallStringLength = 10/*'ffmpeg -i '*/ + episodePathLength + 51/*'-q:a 2 -loglevel error -stats -af "volume=4dB" -vn '*/ + absoluteFilePathLength + 4/*'""'*/;
char* ffmpegCallString = alloca(sizeof(*ffmpegCallString) * (ffmpegCallStringLength + 1));
ffmpegCallStringLength = snprintf(ffmpegCallString, ffmpegCallStringLength + 1, "ffmpeg -i \"%s\" -q:a 2 -loglevel error -stats -af \"volume=4dB\" -vn \"%s\"", absoluteFilePath, episodePath);
const uint_fast64_t episodeOffset = util_findLast(relativePath, relativePathLength, '/');
UTIL_LOG_CONSOLE_(LOG_DEBUG, "%s", relativePath + episodeOffset + 1);
const int returnValue = system(ffmpegCallString);
if(returnValue == -1){
UTIL_LOG_ERROR(strerror(error));
}else{
if(returnValue != 0){
if(util_fileExists(episodePath)){
error = util_deleteFile(episodePath);
}
goto label_freeShow;
}
}
// https://trac.ffmpeg.org/wiki/Encode/MP3
// -i Input.
// -b:a 192k Desired bitrate. (Constant encoding)
// -q:a 2 ~190kbit/s. -q:a == -qscale:a.
// -af voulume=4dB Increase voulume.
// -vn No video output.
// -ar 44100 SamplingRate.
// -ac 2 Numnber of audio chanels.
// -loglevel error -stats
}
}
}
label_freeShow:
mediaLibrary_freeShow(&show);
label_return:
return ERROR(error);
}
|
Ex05/herder
|
src/que.h
|
#ifndef QUE_H
#define QUE_H
#include "util.h"
typedef struct queElement{
void* value;
struct queElement* next;
}QueElement;
typedef struct{
QueElement* head;
QueElement* tail;
uint_fast64_t len;
}Que;
ERROR_CODE que_init(Que*);
ERROR_CODE que_enque(Que*, void*);
void* que_deque(Que*);
void que_clear(Que*);
#endif
|
Ex05/herder
|
src/arrayList.c
|
#ifndef ARRAY_LIST_C
#define ARRAY_LIST_C
#include "util.h"
#include "arrayList.h"
ARRAY_LIST_EXPAND_FUNCTION(arrayList_defaultExpandFunction){
return previousSize + (previousSize >> 1);
}
uint_fast64_t arrayList_expand(const uint_fast16_t i);
local ERROR_CODE arrayList_expandList(ArrayList*);
local void arrayList_init_(ArrayList*, const uint_fast64_t, const uint_fast64_t, ArrayList_ExpandFunction);
inline void arrayList_init_(ArrayList* list, const uint_fast64_t initialSize, const uint_fast64_t stride, ArrayList_ExpandFunction expandFunction){
list->length = 0;
list->stride = stride;
list->expansions = 1;
list->expandFunction = expandFunction;
list->maxLength = initialSize;
}
inline ERROR_CODE arrayList_init(ArrayList* list, const uint_fast64_t initialSize, const uint_fast64_t stride, ArrayList_ExpandFunction expandFunction){
arrayList_init_(list, initialSize, stride, expandFunction);
list->elements = malloc(stride * list->maxLength);
if(list->elements == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE arrayList_initFixedSizeList(ArrayList* list, const uint_fast64_t size, const uint_fast64_t stride){
arrayList_init_(list, size, stride, NULL);
list->elements = malloc(stride * list->maxLength);
if(list->elements == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE arrayList_expandList(ArrayList* list){
list->maxLength = list->expandFunction(list->expansions++, list->maxLength);
void* elements = realloc(list->elements, list->stride * list->maxLength);
// TODO:(jan) Check for 'ENOMEM' to see if the realloc call failed.
if(elements == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}else{
list->elements = elements;
}
return ERROR(ERROR_NO_ERROR);
}
inline void arrayList_initIterator(ArrayListIterator* it, ArrayList* list){
it->list = list;
it->index = 0;
}
inline void arrayList_iteratorSetBeginIndex(ArrayListIterator* it, const uint_fast64_t index){
it->index = index;
}
inline int_fast32_t arrayList_iteratorHasNext(ArrayListIterator* it){
return it->index < it->list->length;
}
inline void arrayList_free(ArrayList* list){
free(list->elements);
}
#endif
|
Ex05/herder
|
src/test.c
|
// POSIX Version ¢2008 clock_gettime()
#define _XOPEN_SOURCE 700
// For mmap flags that are not in the POSIX-Standard.
#define _GNU_SOURCE
#include "util.c"
#include "mediaLibrary.c"
#include "arrayList.c"
#include "linkedList.c"
#include "argumentParser.c"
#include "http.c"
#include "que.c"
#include "threadPool.c"
#include "cache.c"
#include "propertyFile.c"
#include "server.c"
#include "herder.c"
#define TEST_NO_SETUP_FLAG 0x01
#define TEST_TEST_SUIT_CONSTRUCT_FUNCTION(functionName, varName) ERROR_CODE test_testSuitConstruct_##functionName(void** varName)
typedef ERROR_CODE test_TestSuitConstructFunction(void**);
#define TEST_TEST_SUIT_DESTRUCT_FUNCTION(functionName, varName) ERROR_CODE test_testSuitDestruct_##functionName (void* varName)
typedef ERROR_CODE test_TestSuitDestructFunction(void*);
#define TEST_TEST_FUNCTION(functionName) bool test_ ## functionName (void* data)
#define TEST_TEST_FUNCTION_(functionName, type, varName) bool test_ ## functionName (type* varName)
typedef TEST_TEST_FUNCTION(testFunction);
#define TEST_END() return test_testEnd()
#define TEST_BEGIN() test_testBegin()
#define TEST_SUIT_BEGIN_(name) test_testSuitBegin_(# name, test_testSuitConstruct_## name, test_testSuitDestruct_## name)
#define TEST_SUIT_BEGIN(name) test_testSuitBegin(name)
#define TEST_SUIT_END() test_testSuitEnd()
#define TEST(name) test_test((test_testFunction*)test_ ## name, #name)
#define __TEST_NO_SETUP__(void) do { \
TestSuit* testSuit = ARRAY_LIST_GET_PTR(&testSuits, ARRAY_LIST_LENGTH((&testSuits)) - 1, TestSuit); \
testSuit->noSetup = TEST_NO_SETUP_FLAG; \
}while(0)
#define TEST_NO_SETUP(name) __TEST_NO_SETUP__(); \
TEST(name)
#define TEST_SUCCESS true
#define TEST_FAILURE(format, ...) UTIL_LOG_ERROR_(format, __VA_ARGS__), false
static ArrayList testSuits;
typedef struct testSuit{
test_TestSuitConstructFunction* constructFunction;
test_TestSuitDestructFunction* destructFunction;
void* data;
char* name;
UTIL_FLAG(noSetup, 1);
ArrayList testedFunctions;
}TestSuit;
typedef struct{
char* name;
bool failed;
}Test;
void test_testBegin(void){
arrayList_init(&testSuits, 16, sizeof(TestSuit), arrayList_defaultExpandFunction);
}
TestSuit* test_testSuitBegin(const char*);
int32_t test_testEnd(void){
uint_fast64_t totalTests = 0;
uint_fast64_t failedTests = 0;
uint_fast64_t successfulTests = 0;
ArrayListIterator testSuitIterator;
arrayList_initIterator(&testSuitIterator, &testSuits);
while(ARRAY_LIST_ITERATOR_HAS_NEXT(&testSuitIterator)){
TestSuit testSuit = ARRAY_LIST_ITERATOR_NEXT(&testSuitIterator, TestSuit);
ArrayListIterator testIterator;
arrayList_initIterator(&testIterator, &testSuit.testedFunctions);
uint_fast64_t testSuitTests = testSuit.testedFunctions.length;
uint_fast64_t failedTestSuitTests = 0;
while(ARRAY_LIST_ITERATOR_HAS_NEXT(&testIterator)){
Test test = ARRAY_LIST_ITERATOR_NEXT(&testIterator, Test);
if(test.failed){
failedTestSuitTests++;
failedTests++;
}else{
successfulTests++;
}
totalTests++;
}
arrayList_initIterator(&testIterator, &testSuit.testedFunctions);
if(failedTestSuitTests != 0){
printf("\nTestSuit: %s", testSuit.name);
printf(" [%" PRIdFAST64 "/%" PRIdFAST64"]\n", testSuitTests - failedTestSuitTests, testSuitTests);
}
while(ARRAY_LIST_ITERATOR_HAS_NEXT(&testIterator)){
Test test = ARRAY_LIST_ITERATOR_NEXT(&testIterator, Test);
if(test.failed){
printf("\t %s: failed\n", test.name);
}
free(test.name);
}
arrayList_free(&testSuit.testedFunctions);
free(testSuit.name);
}
arrayList_free(&testSuits);
printf("\nTotal %" PRIuFAST64 "/%" PRIuFAST64 ".\n", successfulTests, totalTests);
return failedTests == 0 ? 0 : -1;
}
void test_testSuitBegin_(const char* name, test_TestSuitConstructFunction* constructFunction, test_TestSuitDestructFunction destructFunction){
TestSuit* testSuit = test_testSuitBegin(name);
testSuit->constructFunction = constructFunction;
testSuit->destructFunction = destructFunction;
}
TestSuit* test_testSuitBegin(const char* name){
TestSuit testSuit = {0};
testSuit.name = malloc(sizeof(char*) * (strlen(name) + 1));
if(testSuit.name == NULL){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_OUT_OF_MEMORY));
}
strcpy(testSuit.name, name);
arrayList_init(&testSuit.testedFunctions, 16, sizeof(Test), arrayList_defaultExpandFunction);
ARRAY_LIST_ADD(&testSuits, testSuit, TestSuit);
return ARRAY_LIST_GET_PTR(&testSuits, ARRAY_LIST_LENGTH(&testSuits) - 1, TestSuit);
}
// Note: Intentionally empty. (jan - 2019.03.01)
void test_testSuitEnd(void){
// Unused.
}
void test_test(test_testFunction func, const char* name){
TestSuit* testSuit = ARRAY_LIST_GET_PTR(&testSuits, testSuits.length - 1, TestSuit);
Test test = {0};
test.name = malloc(sizeof(*name) * (strlen(name) + 1));
if(test.name == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
}
strcpy(test.name, name);
ERROR_CODE error = ERROR_NO_ERROR;
if(testSuit->constructFunction != NULL && testSuit->noSetup != TEST_NO_SETUP_FLAG){
if((error = testSuit->constructFunction(&testSuit->data)) != ERROR_NO_ERROR){
test.failed = true;
}
}
if(error == ERROR_NO_ERROR){
test.failed = !func(testSuit->data);
}
if(testSuit->destructFunction != NULL && testSuit->noSetup != TEST_NO_SETUP_FLAG){
if(testSuit->destructFunction(testSuit->data) != ERROR_NO_ERROR){
test.failed = true;
}
}
ARRAY_LIST_ADD(&testSuit->testedFunctions, test, Test);
testSuit->noSetup = 0;
}
// arrayList.c
TEST_TEST_FUNCTION(arraylist_iteration){
ArrayList list;
arrayList_initFixedSizeList(&list, 12, sizeof(uint8_t));
ARRAY_LIST_ADD(&list, 0, uint8_t);
ARRAY_LIST_ADD(&list, 1, uint8_t);
ARRAY_LIST_ADD(&list, 2, uint8_t);
ARRAY_LIST_ADD(&list, 3, uint8_t);
uint8_t buf[4] = {0};
ArrayListIterator it;
arrayList_initIterator(&it, &list);
uint_fast64_t i = 0;
while(ARRAY_LIST_ITERATOR_HAS_NEXT(&it)){
buf[i++] = ARRAY_LIST_ITERATOR_NEXT(&it, uint8_t);
}
if(buf[0] != 0 || buf[1] != 1 || buf[2] != 2 || buf[3] != 3){
return TEST_FAILURE("%s", "Failed to iterate over array list.");
}
arrayList_free(&list);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(arraylist_fixedSizedStackList){
ArrayList list;
ARRAY_LIST_INIT_FIXED_SIZE_STACK_LIST((&list), 4, sizeof(uint8_t));
ARRAY_LIST_ADD(&list, 0, uint8_t);
ARRAY_LIST_ADD(&list, 1, uint8_t);
ARRAY_LIST_ADD(&list, 2, uint8_t);
ARRAY_LIST_ADD(&list, 3, uint8_t);
uint8_t buf[4] = {0};
ArrayListIterator it;
arrayList_initIterator(&it, &list);
uint_fast64_t i = 0;
while(ARRAY_LIST_ITERATOR_HAS_NEXT(&it)){
buf[i++] = ARRAY_LIST_ITERATOR_NEXT(&it, uint8_t);
}
if(buf[0] != 0 || buf[1] != 1 || buf[2] != 2 || buf[3] != 3){
return TEST_FAILURE("%s", "Failed to create fix sized stack list.");
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(arraylist_get){
// Test_0.
{
ArrayList list;
ARRAY_LIST_INIT_FIXED_SIZE_STACK_LIST((&list), 4, sizeof(uint8_t));
ARRAY_LIST_ADD(&list, 0, uint8_t);
ARRAY_LIST_ADD(&list, 1, uint8_t);
ARRAY_LIST_ADD(&list, 2, uint8_t);
ARRAY_LIST_ADD(&list, 3, uint8_t);
uint8_t ret;
if((ret = ARRAY_LIST_GET(&list, 1, uint8_t)) != 1){
return TEST_FAILURE("Return value '%" PRIu8 " != '%" PRIu8 "'.", ret, 1);
}
}
// Test_1.
{
struct testStruct{
uint8_t a;
char b;
};
ArrayList list;
ARRAY_LIST_INIT_FIXED_SIZE_STACK_LIST((&list), 4, sizeof(struct testStruct));
struct testStruct b2 = {1, 'c'};
struct testStruct b3 = {2, 'd'};
struct testStruct b4 = {3, 'g'};
ARRAY_LIST_ADD(&list, b2, struct testStruct);
ARRAY_LIST_ADD(&list, b3, struct testStruct);
ARRAY_LIST_ADD(&list, b4, struct testStruct);
struct testStruct* ret;
ret = ARRAY_LIST_GET_PTR(&list, 0, struct testStruct);
if(ret->a != 1 && ret->b != 'c'){
return TEST_FAILURE("%s", "Failed to get arrayList value.");
}
ret = ARRAY_LIST_GET_PTR(&list, 2, struct testStruct);
if(ret->a != 3 && ret->b != 'g'){
return TEST_FAILURE("%s", "Failed to get arrayList value.");
}
}
// Test_2.
{
struct testStruct{
uint8_t a;
char b;
};
ArrayList list;
ARRAY_LIST_INIT_FIXED_SIZE_STACK_LIST((&list), 4, sizeof(struct testStruct));
struct testStruct b2 = {1, 'c'};
struct testStruct* b3 = malloc(sizeof(struct testStruct));
b3->a = 7;
b3->b = 'h';
ARRAY_LIST_ADD(&list, b2, struct testStruct);
ARRAY_LIST_ADD_PTR(&list, b3, struct testStruct);
free(b3);
struct testStruct* ret;
ret = ARRAY_LIST_GET_PTR(&list, 0, struct testStruct);
if(ret->a != 1 && ret->b != 'c'){
return TEST_FAILURE("%s", "Failed to get arrayList value.");
}
ret = ARRAY_LIST_GET_PTR(&list, 1, struct testStruct);
if(ret->a != 7 && ret->b != 'h'){
return TEST_FAILURE("%s", "Failed to get arrayList value.");
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(arraylist_expand){
ArrayList list;
arrayList_init(&list, 1, sizeof(uint8_t), arrayList_defaultExpandFunction);
ARRAY_LIST_ADD(&list, 0, uint8_t);
ARRAY_LIST_ADD(&list, 1, uint8_t);
ARRAY_LIST_ADD(&list, 2, uint8_t);
ARRAY_LIST_ADD(&list, 3, uint8_t);
uint8_t buf[4] = {0};
ArrayListIterator it;
arrayList_initIterator(&it, &list);
uint_fast64_t i = 0;
while(ARRAY_LIST_ITERATOR_HAS_NEXT(&it)){
buf[i++] = ARRAY_LIST_ITERATOR_NEXT(&it, uint8_t);
}
if(buf[0] != 0 || buf[1] != 1 || buf[2] != 2 || buf[3] != 3){
return TEST_FAILURE("%s", "Failed to iterate over array list.");
}
arrayList_free(&list);
return TEST_SUCCESS;
}
// arguemntParser.c
TEST_TEST_FUNCTION(argumentParser_parse){
ERROR_CODE error;
ArgumentParser parser;
argumentParser_init(&parser);
#if !defined __GNUC__ && !defined __GNUG__
// TODO:(jan); Add preprocessor macros for other compiler.
#endif
ARGUMENT_PARSER_ADD_ARGUMENT(Test_0, 2, "-t", "--test");
ARGUMENT_PARSER_ADD_ARGUMENT(Import_0, 1, "-i");
ARGUMENT_PARSER_ADD_ARGUMENT(Rename_1, 1, "--rename");
const char* argc_0[] = {"./test", "--rename", "/home/ex05", "/home/29a", "-t", "-t", "-v", "--add", "American Dad"};
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_DUPLICATE_ENTRY);
if((error = argumentParser_parse(&parser, UTIL_ARRAY_LENGTH(argc_0), argc_0)) != ERROR_DUPLICATE_ENTRY){
return TEST_FAILURE("'arguemntParser_parse' did not fail with '%s'. '%s'.", "ERROR_DUPLICATE_ENTRY", util_toErrorString(error));
}
argumentParser_free(&parser);
argumentParser_init(&parser);
ARGUMENT_PARSER_ADD_ARGUMENT(Test_1, 2, "-t", "--test");
ARGUMENT_PARSER_ADD_ARGUMENT(Import_1, 1, "-i");
const char* argc_1[] = {"./test", "-i"};
if(argumentParser_parse(&parser, UTIL_ARRAY_LENGTH(argc_1), argc_1) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to parse arguments. '%s'.", util_toErrorString(error));
}
if(argumentImport_1.numValues != 0){
return TEST_FAILURE("Failed to parse argument: '%s' '%s'.", argumentImport_1.arguments[0], util_toErrorString(error));
}
argumentParser_free(&parser);
argumentParser_init(&parser);
ARGUMENT_PARSER_ADD_ARGUMENT(Test_2, 2, "-t", "--test");
ARGUMENT_PARSER_ADD_ARGUMENT(Import_2, 1, "-i");
ARGUMENT_PARSER_ADD_ARGUMENT(Rename_0, 1, "--rename");
const char* argc_2[] = {"./test", "-v", "-i", "test", "12", "--test", "abbab", "---Tester", "12", "--rename", "/home/123.mpv", "/home/456.lmpv"};
if(argumentParser_parse(&parser, UTIL_ARRAY_LENGTH(argc_2), argc_2) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to parse arguments. '%s'.", util_toErrorString(error));
}
if(!argumentParser_contains(&parser, &argumentTest_2)){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentTest_2.arguments[0]);
}else{
if(argumentTest_2.numValues != 1){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentTest_2.arguments[0]);
}
}
if(!argumentParser_contains(&parser, &argumentImport_2)){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentImport_2.arguments[0]);
}else{
if(argumentImport_2.numValues != 2){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentImport_2.arguments[0]);
}
}
if(!argumentParser_contains(&parser, &argumentRename_0)){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentRename_0.arguments[0]);
}else{
if(argumentRename_0.numValues != 2){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentRename_0.arguments[0]);
}else{
if(argumentRename_0.numValues != 2){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentRename_0.arguments[0]);
}
if(strncmp(argumentRename_0.values[0], "/home/123.mpv", strlen("/home/123.mpv") + 1) != 0){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentRename_0.arguments[0]);
}
if(strncmp(argumentRename_0.values[1], "/home/456.lmpv", strlen("/home/456.lmpv") + 1) != 0){
return TEST_FAILURE("Failed to parse argument: '%s'.", argumentRename_0.arguments[0]);
}
}
}
argumentParser_free(&parser);
return TEST_SUCCESS;
}
// linkedList.c
TEST_TEST_SUIT_CONSTRUCT_FUNCTION(linkedList, list){
*list = malloc(sizeof(LinkedList));
if(*list == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
return ERROR(linkedList_init(*list));
}
TEST_TEST_SUIT_DESTRUCT_FUNCTION(linkedList, list){
linkedList_free(list);
free(list);
return ERROR(ERROR_NO_ERROR);
}
TEST_TEST_FUNCTION_(linkedList_iteration, LinkedList, list){
uint8_t a = 0;
uint8_t b = 1;
uint8_t c = 2;
uint8_t d = 3;
linkedList_add(list, &a);
linkedList_add(list, &b);
linkedList_add(list, &c);
linkedList_add(list, &d);
uint8_t buf[4] = {0};
LinkedListIterator it;
// Test_0.
{
linkedList_initIterator(&it, list);
uint_fast64_t i = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
buf[i++] = *(uint8_t*) LINKED_LIST_ITERATOR_NEXT(&it);
}
if(buf[0] != 3 || buf[1] != 2 || buf[2] != 1 || buf[3] != 0){
return TEST_FAILURE("%s", "Failed to iterate over linked list.");
}
}
// Test_1.
{
linkedList_initIterator(&it, list);
uint_fast64_t i = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
buf[i++] = *(uint8_t*) LINKED_LIST_ITERATOR_NEXT(&it);
}
if(buf[0] != 3 || buf[1] != 2 || buf[2] != 1 || buf[3] != 0){
return TEST_FAILURE("%s", "Failed to iterate over linked list.");
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(linkedList_remove, LinkedList, list){
uint8_t a = 0;
uint8_t b = 1;
uint8_t c = 2;
uint8_t d = 3;
linkedList_add(list, &a);
linkedList_add(list, &b);
linkedList_add(list, &c);
linkedList_add(list, &d);
linkedList_remove(list, &a);
linkedList_remove(list, &b);
uint8_t buf[4] = {0};
LinkedListIterator it;
linkedList_initIterator(&it, list);
uint_fast64_t i = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
buf[i++] = *(uint8_t*) LINKED_LIST_ITERATOR_NEXT(&it);
}
if(buf[0] != 3 || buf[1] != 2){
return TEST_FAILURE("%s", "Failed to remove link from linked list.");
}
if(list->length != 2){
return TEST_FAILURE("linked list length '%" PRIuFAST64 "' != '%d'.", list->length, 2);
}
return TEST_SUCCESS;
}
// util.c
TEST_TEST_FUNCTION(util_byteArrayTo_uint16){
const uint16_t testData[] = {
0,
1,
UINT8_MAX,
UINT16_MAX
};
int8_t buf[sizeof(uint16_t)];
uint_fast64_t i;
for(i = 0; i < sizeof(testData) / sizeof(testData[0]); i++){
const uint16_t val = testData[i];
#if __BYTE_ORDER == __LITTLE_ENDIAN
buf[1] = (val >> (8 * 0)) & 0xFF;
buf[0] = (val >> (8 * 1)) & 0xFF;
#elif __BYTE_ORDER == __BIG_ENDIAN
buf[0] = (val >> (8 * 0)) & 0xFF;
buf[1] = (val >> (8 * 1)) & 0xFF;
#elif __BYTE_ORDER == __PDP_ENDIAN
ERROR: PDP/mixed endianes is not supported at the moment.
#else
ERROR: Your system architectures endianes is not supported at the moment.
#endif
uint16_t ret;
if((ret = util_byteArrayTo_uint16(buf)) != val){
return TEST_FAILURE("Return value '%" PRIu16 " != '%" PRIu16 "'.", ret, val);
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_byteArrayTo_uint32){
const uint32_t testData[] = {
0,
1,
UINT8_MAX,
UINT16_MAX,
UINT32_MAX
};
int8_t buf[sizeof(uint32_t)];
uint_fast64_t i;
for(i = 0; i < sizeof(testData) / sizeof(testData[0]); i++){
const uint32_t val = testData[i];
#if __BYTE_ORDER == __LITTLE_ENDIAN
buf[3] = (val >> (8 * 0)) & 0xFF;
buf[2] = (val >> (8 * 1)) & 0xFF;
buf[1] = (val >> (8 * 2)) & 0xFF;
buf[0] = (val >> (8 * 3)) & 0xFF;
#elif __BYTE_ORDER == __BIG_ENDIAN
buf[0] = (val >> (8 * 0)) & 0xFF;
buf[1] = (val >> (8 * 1)) & 0xFF;
buf[2] = (val >> (8 * 2)) & 0xFF;
buf[3] = (val >> (8 * 3)) & 0xFF;
#elif __BYTE_ORDER == __PDP_ENDIAN
ERROR: PDP/mixed endianes is not supported at the moment.
#else
ERROR: Your system architectures endianes is not supported at the moment.
#endif
uint32_t ret;
if((ret = util_byteArrayTo_uint32(buf)) != val){
return TEST_FAILURE("Return value '%" PRIu32 " != '%" PRIu32 "'.", ret, val);
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_byteArrayTo_uint64){
const uint64_t testData[] = {
0,
1,
UINT8_MAX,
UINT16_MAX,
UINT32_MAX,
UINT64_MAX
};
int8_t buf[sizeof(uint64_t)];
uint_fast64_t i;
for(i = 0; i < sizeof(testData) / sizeof(testData[0]); i++){
const uint64_t val = testData[i];
#if __BYTE_ORDER == __LITTLE_ENDIAN
buf[7] = (val >> (8 * 0)) & 0xFF;
buf[6] = (val >> (8 * 1)) & 0xFF;
buf[5] = (val >> (8 * 2)) & 0xFF;
buf[4] = (val >> (8 * 3)) & 0xFF;
buf[3] = (val >> (8 * 4)) & 0xFF;
buf[2] = (val >> (8 * 5)) & 0xFF;
buf[1] = (val >> (8 * 6)) & 0xFF;
buf[0] = (val >> (8 * 7)) & 0xFF;
#elif __BYTE_ORDER == __BIG_ENDIAN
buf[0] = (val >> (8 * 0)) & 0xFF;
buf[1] = (val >> (8 * 1)) & 0xFF;
buf[2] = (val >> (8 * 2)) & 0xFF;
buf[3] = (val >> (8 * 3)) & 0xFF;
buf[4] = (val >> (8 * 4)) & 0xFF;
buf[5] = (val >> (8 * 5)) & 0xFF;
buf[6] = (val >> (8 * 6)) & 0xFF;
buf[7] = (val >> (8 * 7)) & 0xFF;
#elif __BYTE_ORDER == __PDP_ENDIAN
ERROR: PDP/mixed endianes is not supported at the moment.
#else
ERROR: Your system architectures endianes is not supported at the moment.
#endif
uint64_t ret;
if((ret = util_byteArrayTo_uint64(buf)) != val){
return TEST_FAILURE("Return value '%" PRIu64 " != '%" PRIu64 "'.", ret, val);
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_uint16ToByteArray){
const uint16_t testData[] = {
0,
1,
UINT8_MAX,
UINT16_MAX / 2,
UINT16_MAX
};
int8_t buf[sizeof(uint16_t)];
uint_fast64_t i;
for(i = 0; i < sizeof(testData) / sizeof(testData[0]); i++){
const uint16_t val = testData[i];
uint16_t ret;
if((ret = util_byteArrayTo_uint16(util_uint16ToByteArray(buf, val))) != val){
return TEST_FAILURE("Return value '%" PRIu16 " != '%" PRIu16 "'.", ret, val);
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_uint32ToByteArray){
const uint32_t testData[] = {
0,
1,
UINT8_MAX,
UINT16_MAX,
UINT32_MAX
};
int8_t buf[sizeof(uint32_t)];
uint_fast64_t i;
for(i = 0; i < sizeof(testData) / sizeof(testData[0]); i++){
const uint32_t val = testData[i];
uint32_t ret;
if((ret = util_byteArrayTo_uint32(util_uint32ToByteArray(buf, val))) != val){
return TEST_FAILURE("Return value '%" PRIu32 " != '%" PRIu32 "'.", ret, val);
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_uint64ToByteArray){
const uint64_t testData[] = {
0,
1,
UINT8_MAX,
UINT16_MAX,
UINT32_MAX,
UINT64_MAX
};
int8_t buf[sizeof(uint64_t)];
uint_fast64_t i;
for(i = 0; i < sizeof(testData) / sizeof(testData[0]); i++){
const uint64_t val = testData[i];
uint64_t ret;
if((ret = util_byteArrayTo_uint64(util_uint64ToByteArray(buf, val))) != val){
return TEST_FAILURE("Return value '%" PRIu64 " != '%" PRIu64 "'.", ret, val);
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_findFirst){
const char s[] = "abcdef012ghi~jklno~p345~qrs";
if(util_findFirst(s, strlen(s), '~') != 12){
return TEST_FAILURE("Failed to find fisrt char:'~' in string:'%s'.", s);
}
if(util_findFirst(s, strlen(s), '/') != -1){
return TEST_FAILURE("Failed to not find char:'/' in string:'%s'.", s);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_findFirst_s){
const char a[] = "aabbccdd--11223344";
const int_fast64_t offset = util_findFirst_s(a, strlen(a), "--", 2);
if(offset != 8){
return TEST_FAILURE("Failed to find fisrt string: '--' in string:'%s'.", a);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_findLast){
const char a[] = "01234...567";
const char b[] = "01234567";
if(util_findLast(a, strlen(a), '.') != 7){
return TEST_FAILURE("Failed to find last char:'.' in string:'%s'.", a);
}
int_fast64_t ret;
if((ret = util_findLast(b, strlen(b), '.')) != -1){
return TEST_FAILURE("Return value '%" PRIdFAST64 " != -1'.", ret);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_replace){
ERROR_CODE error;
char s[] = "--$errorCode--$errorCode--";
char a[64] = {0};
uint_fast64_t stringLength = strlen(s);
memcpy(a, s, stringLength + 1);
if((error = util_replace(a, 64, &stringLength, "$errorCode", strlen("$errorCode"), "404", strlen("404"))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to replace char in string:'%s'. '%s'.", a, util_toErrorString(error));
}
if(strcmp(a, "--404--404--") != 0){
return TEST_FAILURE("Return value '%s' != '--404--404--'.", a);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_getBaseDirectory){
ERROR_CODE error;
// Test_1.
{
char url[] = "/";
char* baseDirectory;
uint_fast64_t baseDirectoryLength;
if((error = util_getBaseDirectory(&baseDirectory, &baseDirectoryLength, url, strlen(url))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to get base directory of path: '%s'. '%s'.", url, util_toErrorString(error));
}
if(baseDirectoryLength != 1){
return TEST_FAILURE("Base directory length '%" PRIdFAST64 "' != '%d'", baseDirectoryLength, 1);
}
if(strncmp(url, baseDirectory, baseDirectoryLength) != 0){
return TEST_FAILURE("'util_getBaseDirectory' '%s' != '%s'.", url, baseDirectory);
}
}
// Test_2.
{
char url[] = "/extractShowInfo";
char* baseDirectory;
uint_fast64_t baseDirectoryLength;
if((error = util_getBaseDirectory(&baseDirectory, &baseDirectoryLength, url, strlen(url))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to get base directory of path: '%s'. '%s'.", url, util_toErrorString(error));
}
if(baseDirectoryLength != 16){
return TEST_FAILURE("Base directory length '%" PRIdFAST64 "' != '%d'", baseDirectoryLength, 16);
}
if(strncmp(url, baseDirectory, baseDirectoryLength) != 0){
return TEST_FAILURE("'util_getBaseDirectory' '%s' != '%s'.", baseDirectory, "/img");
}
}
// Test_3.
{
char url[] = "/git.html";
char* baseDirectory;
uint_fast64_t baseDirectoryLength;
if((error = util_getBaseDirectory(&baseDirectory, &baseDirectoryLength, url, strlen(url))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to get base directory of path: '%s'. '%s'.", url, util_toErrorString(error));
}
if(baseDirectoryLength != 1){
return TEST_FAILURE("Base directory length '%" PRIdFAST64 "' != '%d'", baseDirectoryLength, 1);
}
if(strncmp("/", baseDirectory, baseDirectoryLength) != 0){
return TEST_FAILURE("'util_getBaseDirectory' '%s' != '%s'.", baseDirectory, "/");
}
}
// Test_4.
{
char url[] = "/img/img_001.png";
char* baseDirectory;
uint_fast64_t baseDirectoryLength;
if((error = util_getBaseDirectory(&baseDirectory, &baseDirectoryLength, url, strlen(url))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to get base directory of path: '%s'. '%s'.", url, util_toErrorString(error));
}
if(baseDirectoryLength != 4){
return TEST_FAILURE("Base directory length '%" PRIdFAST64 "' != '%d'", baseDirectoryLength, 4);
}
if(strncmp("/img", baseDirectory, baseDirectoryLength) != 0){
return TEST_FAILURE("'util_getBaseDirectory' '%s' != '%s'.", baseDirectory, "/img");
}
}
// Test_5.
{
char url[] = "check.proxyradar.com:80";
char* baseDirectory;
uint_fast64_t baseDirectoryLength;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_INVALID_REQUEST_URL);
if((error = util_getBaseDirectory(&baseDirectory, &baseDirectoryLength, url, strlen(url))) != ERROR_INVALID_REQUEST_URL){
return TEST_FAILURE("Failed to throw an error for path: '%s'. Expected '%s' buit functiion returned '%s'.", url, util_toErrorString(ERROR_INVALID_REQUEST_URL), util_toErrorString(error));
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_trim){
char s[] = " 123_457 8910 ";
util_trim(s, strlen(s));
if(strcmp(s, "123_457 8910") != 0){
return TEST_FAILURE("'util_trim' '%s' != '%s'.", s, "123_457 8910");
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_getFileName){
char filePath[] = "~/Video/video_001.mkv";
const char* fileName = util_getFileName(filePath, strlen(filePath));
if(strcmp(fileName, "video_001.mkv") != 0){
return TEST_FAILURE("'util_getFileName' '%s' != '%s'.", fileName, "video_001.mkv");
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_formatNumber){
char s[UTIL_FORMATTED_NUMBER_LENGTH];
char* strings[] = {
"000",
"017",
"199",
"1_856",
"1_111_111",
"99_999_999_999"
};
uint_fast64_t numbers[] = {
0,
17,
199,
1856,
1111111,
99999999999
};
uint_fast64_t i;
for(i = 0; i < (sizeof(numbers) / sizeof(*numbers)); i++){
uint_fast64_t stringLength = UTIL_FORMATTED_NUMBER_LENGTH;
util_formatNumber(s, &stringLength, numbers[i]);
if(strncmp(s, strings[i], strlen(strings[i])) != 0){
return TEST_FAILURE("'util_formatNumber' '%s' != '%s'.", s, strings[i]);
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_toLowerChase){
char s[] = "AbCDEFg0123";
util_toLowerChase(s);
if(strncmp(s, "abcdefg0123", strlen(s)) != 0){
return TEST_FAILURE("'util_toLowerChase' '%s' != '%s'.", s, "abcdefg0123");
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_replaceAllChars){
char a[] = "010101110101";
util_replaceAllChars(a, '1', '0');
const char b[] = "000000000000";
if(strncmp(a, b, strlen(b)) != 0){
return TEST_FAILURE("'util_replaceAllChars' '%s' != '%s'.", a, b);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_append){
char a[11] = {'1', '2', '3', '4', '5'};
char b[] = "67890";
util_append(a, strlen(a), b, strlen(b));
if(strncmp(a, "1234567890", 11) != 0){
return TEST_FAILURE("'util_append' '%s' != '%s'.", a, "1234567890");
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_stringToInt){
ERROR_CODE error;
const char a[] = "27";
const char b[] = "a88b";
int_fast64_t value;
if((error = util_stringToInt(a, &value)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to convert value: '%s' to integer. '%s'.", a, util_toErrorString(error));
}
if(value != 27){
return TEST_FAILURE("Value '%" PRIdFAST64 "' != '%d'.", value, 27);
}
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_INVALID_STRING);
if((error = util_stringToInt(b, &value)) != ERROR_INVALID_STRING){
return TEST_FAILURE("'util_stringToInt' did not fail as expected with: '%s'. '%s'.","ERROR_INVALID_STRING", util_toErrorString(error));
}
if(value != 0){
return TEST_FAILURE("Value '%" PRIdFAST64 "' != '%d'.", value, 0);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_getFileExtension){
ERROR_CODE error;
char a[] = "The_Big_Bang_Theory_s10e05_the_hot_tub_contamination.mkv";
char b[] = "The_Big_Bang_Theory_s10e05_the_hot_tub_contamination";
char* fileExtension;
uint_fast64_t fileExtensionLength;
if((error = util_getFileExtension(&fileExtension, &fileExtensionLength, a, strlen(a))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to extract file extension from file: '%s'. '%s'.", a, util_toErrorString(error));
}
if(strncmp(fileExtension, "mkv", 3) != 0 && fileExtensionLength != 3){
return TEST_FAILURE("File extension '%s' != '%s'.", fileExtension, "mkv");
}
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_INVALID_STRING);
if((error = util_getFileExtension(&fileExtension, &fileExtensionLength, b, strlen(b))) == ERROR_NO_ERROR){
return TEST_FAILURE("'util_getFileExtension' did not fail as expected with 'ERROR_INVALID_STRING' function returned '%s'", util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_renameFile){
ERROR_CODE error;
#define TEST_FILE_NAME "/tmp/herder_util_test_renameFile_XXXXXX"
#define TEST_FILE_NEW_NAME "/tmp/herder_util_test_renameFile.xmpe"
char* filePath = alloca(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
char* newFileName = alloca(sizeof(*newFileName) * (strlen(TEST_FILE_NEW_NAME) + 1));
strcpy(newFileName, TEST_FILE_NEW_NAME);
#undef TEST_FILE_NAME
#undef TEST_FILE_NEW_NAME
const int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
if((error = util_renameFile(filePath, newFileName)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to rename file: '%s'. '%s'.", filePath, util_toErrorString(error));
}
if(util_fileExists(filePath)){
return TEST_FAILURE("Failed to rename file to:'%s'.", filePath);
}
if(!util_fileExists(newFileName)){
return TEST_FAILURE("Failed to rename file to:'%s'.", newFileName);
}
if(util_deleteFile(newFileName) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete file:'%s'.", newFileName);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_renameFileRelative){
ERROR_CODE error;
#define TEST_DIR_NAME "/tmp/"
#define TEST_FILE_NAME "herder_util_test_renameFileRelative_XXXXXX"
#define TEST_NEW_FILE_NAME "herder_util_test_renameFileRelative.xmpe"
char* dir = malloc(sizeof(*dir) * (strlen(TEST_DIR_NAME) + 1));
strcpy(dir, TEST_DIR_NAME);
char* fileName = malloc(sizeof(*fileName) * (strlen(TEST_FILE_NAME) + 1));
strcpy(fileName, TEST_FILE_NAME);
char* filePath = malloc(sizeof(*filePath) * (strlen(TEST_DIR_NAME) + strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_DIR_NAME);
strcpy(filePath + strlen(TEST_DIR_NAME), TEST_FILE_NAME);
char* newFileName = malloc(sizeof(*newFileName) * (strlen(TEST_NEW_FILE_NAME) + 1));
strcpy(newFileName, TEST_NEW_FILE_NAME);
char* newFilePath = malloc(sizeof(*newFilePath) * (strlen(TEST_DIR_NAME) + strlen(TEST_FILE_NAME) + 1));
strcpy(newFilePath, TEST_DIR_NAME);
strcpy(newFilePath + strlen(TEST_DIR_NAME), TEST_NEW_FILE_NAME);
#undef TEST_DIR_NAME
#undef TEST_FILE_NAME
#undef TEST_NEW_FILE_NAME
const int fileDescriptor = open(filePath, O_RDONLY | O_CREAT);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
if((error = util_renameFileRelative(dir, fileName, newFileName)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to rename file:'%s'. '%s'.", fileName, util_toErrorString(error));
}
if(util_fileExists(fileName)){
return TEST_FAILURE("Failed to rename file:'%s'.", fileName);
}
if(!util_fileExists(newFilePath)){
return TEST_FAILURE("Failed to rename file to:'%s'.", newFilePath);
}
if(util_deleteFile(newFilePath) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete file:'%s'.", newFilePath);
}
free(dir);
free(fileName);
free(filePath);
free(newFileName);
free(newFilePath);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_getFileDirectory){
ERROR_CODE error;
char path[] = "/home/user/file.xmp";
char* dir = alloca(sizeof(*dir) * (strlen(path) + 1));
if((error = util_getFileDirectory(dir, path, strlen(path))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to extract files directory from path: '%s'. '%s'.", path, util_toErrorString(error));
}
if(strcmp(dir, "/home/user") != 0){
return TEST_FAILURE("File directory '%s' != '%s'.", dir, "/home/user");
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_fileExists){
#define TEST_FILE_NAME "/tmp/herder_util_test_fileExists_XXXXXX"
#define TEST_FILE_NEW_NAME "/tmp/herder_util_test_fileExists.tmp"
char* filePath = alloca(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
char* newFileName = alloca(sizeof(*newFileName) * (strlen(TEST_FILE_NEW_NAME) + 1));
strcpy(newFileName, TEST_FILE_NEW_NAME);
#undef TEST_FILE_NAME
const int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
close(fileDescriptor);
ERROR_CODE error;
if((error = util_renameFile(filePath, newFileName)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to rename file: '%s'. '%s'.", filePath, util_toErrorString(error));
}
// Test_0.
{
if(!util_fileExists(newFileName)){
return TEST_FAILURE("Failed to confirm file:'%s' exists.", filePath);
}
}
// Test_1.
{
if(util_fileExists(filePath)){
return TEST_FAILURE("Failed to confirm file:'%s' exists.", filePath);
}
}
if(util_deleteFile(newFileName) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete file:'%s'.", newFileName);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_blockAlloc){
ERROR_CODE error;
void* buffer;
if((error = util_blockAlloc(&buffer, 2048)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to allocate buffer. '%s'.", util_toErrorString(error));
}
if((error = util_unMap(buffer, 2048)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to free buffer. '%s'.", util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_concatenate){
char a[] = "01234";
char b[] = "56789";
char c[11];
ERROR_CODE error;
if((error = util_concatenate(c, a, strlen(a), b, strlen(b) + 1)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to concatenate strings. '%s'.", util_toErrorString(error));
}
if(strncmp(c, "0123456789", 11) != 0){
return TEST_FAILURE("Failed to concatenate strings. '%s' != '0123456789'.", c);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_stringCopy){
char a[] = "012345";
char b[7] = {0};
util_stringCopy(a, b, strlen(a) + 1);
if(strncmp(a, b, strlen(a) + 1) != 0){
return TEST_FAILURE("Failed to copy string. '%s' != '012345'.", b);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_fileCopy){
#define TEST_FILE_NAME "/tmp/herder_util_test_fileExists_XXXXXX"
#define TEST_FILE_NEW_NAME "/tmp/herder_util_test_fileExists.tmp"
char* filePath = alloca(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
char* newFileName = alloca(sizeof(*newFileName) * (strlen(TEST_FILE_NEW_NAME) + 1));
strcpy(newFileName, TEST_FILE_NEW_NAME);
const int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file:'%s' [%s].", filePath, strerror(errno));
}
const int_fast64_t bufferLength = strlen(TEST_FILE_NAME) + 1;
char* buffer = alloca(sizeof(*buffer) * bufferLength);
strncpy(buffer, TEST_FILE_NAME, bufferLength);
if(write(fileDescriptor, buffer, sizeof(char) * bufferLength) != bufferLength){
return TEST_FAILURE("Failed to write to temporary file:'%s'.", filePath);
}
close(fileDescriptor);
ERROR_CODE error;
if((error = util_fileCopy(filePath, newFileName)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to copy file from '%s' to '%s'.", filePath, newFileName);
}
if(!util_fileExists(newFileName)){
return TEST_FAILURE("Failed to copy file file:'%s' does not exist.", newFileName);
}
int fd = open(newFileName, O_RDONLY);
if(fd == 0){
return TEST_FAILURE("Failed to open file:'%s'.", newFileName);
}
memset(buffer, 0, bufferLength);
if(read(fd, buffer, sizeof(char) * bufferLength) != (ssize_t) (sizeof(char) * bufferLength)){
return TEST_FAILURE("Failed to read from file:'%s'.", newFileName);
}
close(fd);
if(strncmp(buffer, TEST_FILE_NAME, bufferLength) != 0){
return TEST_FAILURE("'%s' != '%s'.", buffer, TEST_FILE_NAME);
}
if(util_deleteFile(filePath) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete file:'%s'.", filePath);
}
if(util_deleteFile(newFileName) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete file:'%s'.", newFileName);
}
#undef TEST_FILE_NAME
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_deleteFile){
#define TEST_FILE_NAME "/tmp/herder_util_test_deleteFile_XXXXXX"
char* filePath = alloca(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
#undef TEST_FILE_NAME
const int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
close(fileDescriptor);
ERROR_CODE error;
if((error = util_deleteFile(filePath)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete file:'%s'. '%s'", filePath, util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_deleteDirectory){
// Test_0.
{
#define TMP_DIRECTORY_NAME "/tmp/herder_util_test_deleteDirectory_0_XXXXXX"
char* tmpPath = alloca(sizeof(*tmpPath) * (strlen(TMP_DIRECTORY_NAME) + 1));
strcpy(tmpPath, TMP_DIRECTORY_NAME);
#undef TMP_DIRECTORY_NAME
const char* dir = mkdtemp(tmpPath);
if(dir == NULL){
return TEST_FAILURE("Failed to create unique directory name. '%s'", strerror(errno));
}
ERROR_CODE error;
if((error = util_deleteDirectory(dir, false, false)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete directory '%s' [%s].", dir, util_toErrorString(error));
}
if(util_directoryExists(dir)){
return TEST_FAILURE("Failed to delete directory:'%s'.", dir);
}
}
// Test_1.
{
#define TMP_DIRECTORY_NAME "/tmp/herder_util_test_deleteDirectory_1_XXXXXX"
char* tmpPath = alloca(sizeof(*tmpPath) * (strlen(TMP_DIRECTORY_NAME) + 1));
strcpy(tmpPath, TMP_DIRECTORY_NAME);
#undef TMP_DIRECTORY_NAME
const char* dir = mkdtemp(tmpPath);
if(dir == NULL){
return TEST_FAILURE("Failed to create unique directory name. '%s'", strerror(errno));
}
ERROR_CODE error;
if((error = util_deleteDirectory(dir, true, false)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete directory '%s' [%s].", dir, util_toErrorString(error));
}
if(!util_directoryExists(dir)){
return TEST_FAILURE("Failed to delete directory:'%s'.", dir);
}
if((error = util_deleteDirectory(dir, false, false)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete directory '%s' [%s].", dir, util_toErrorString(error));
}
// TODO: Add directory into tmp dir.
}
// Test_2.
{
#define TMP_DIRECTORY_NAME "/tmp/herder_util_test_deleteDirectory_2_XXXXXX"
char* tmpPath = alloca(sizeof(*tmpPath) * (strlen(TMP_DIRECTORY_NAME) + 1));
strcpy(tmpPath, TMP_DIRECTORY_NAME);
#undef TMP_DIRECTORY_NAME
const char* dir = mkdtemp(tmpPath);
if(dir == NULL){
return TEST_FAILURE("Failed to create unique directory name. '%s'", strerror(errno));
}
ERROR_CODE error;
if((error = util_deleteDirectory(dir, false, true)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete directory '%s' [%s].", dir, util_toErrorString(error));
}
if(util_directoryExists(dir)){
return TEST_FAILURE("Failed to delete directory:'%s'.", dir);
}
// TODO: Add tmp file into tmp dir.
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_hash){
char a[] = "0123456789";
char b[] = "0132456780";
const int32_t hash = util_hash((uint8_t*) a, sizeof(*a) * strlen(a));
if(hash != util_hash((uint8_t*) a, sizeof(*a) * strlen(a))){
return TEST_FAILURE("Failed to hash '%s'.", a);
}
if(hash == util_hash((uint8_t*) b, sizeof(*b) * strlen(b))){
return TEST_FAILURE("Failed to hash collision for '%s' and '%s'.", a, b);
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_createDirectory){
#define TMP_DIRECTORY_NAME "/tmp/herder_util_test_deleteDirectory_0_XXXXXX"
char* tmpPath = alloca(sizeof(*tmpPath) * (strlen(TMP_DIRECTORY_NAME) + 1));
strcpy(tmpPath, TMP_DIRECTORY_NAME);
#undef TMP_DIRECTORY_NAME
const char* dir = mkdtemp(tmpPath);
if(dir == NULL){
return TEST_FAILURE("Failed to create unique directory name. '%s'", strerror(errno));
}
ERROR_CODE error;
if((error = util_deleteDirectory(dir, false, false)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete directory '%s' [%s].", dir, util_toErrorString(error));
}
if((error = util_createDirectory(dir)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to create directory '%s' [%s].", dir, util_toErrorString(error));
}
if(!util_directoryExists(dir)){
return TEST_FAILURE("Failed to delete directory:'%s'.", dir);
}
if((error = util_deleteDirectory(dir, false, false)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete directory '%s' [%s].", dir, util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_createAllDirectories){
const char dir[] = "/tmp/util_createAllDirectories/0/1/2/3/";
const uint_fast64_t dirLength = strlen(dir);
ERROR_CODE error;
if((error = util_createAllDirectories(dir, dirLength)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to create directory structure '%s' [%s].", dir, util_toErrorString(error));
}
if(!util_directoryExists("/tmp/util_createAllDirectories/0/1/2/3/")){
return TEST_FAILURE("Failed to delete directory:'%s'.", "/tmp/util_createAllDirectories");
}
if((error = util_deleteDirectory("/tmp/util_createAllDirectories/", false, false)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete directory '%s' [%s].", "/tmp/util_createAllDirectories", util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_isDirectory){
// Test_0.
{
#define TMP_DIRECTORY_NAME "/tmp/herder_util_test_isDirectory_0_XXXXXX"
char* tmpPath = alloca(sizeof(*tmpPath) * (strlen(TMP_DIRECTORY_NAME) + 1));
strcpy(tmpPath, TMP_DIRECTORY_NAME);
#undef TMP_DIRECTORY_NAME
const char* dir = mkdtemp(tmpPath);
if(dir == NULL){
return TEST_FAILURE("Failed to create unique directory name. '%s'", strerror(errno));
}
if(!util_isDirectory(dir)){
return TEST_FAILURE("Failed to identify directory '%s'.", dir);
}
ERROR_CODE error;
if((error = util_deleteDirectory(dir, false, false)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete directory '%s' [%s].", dir, util_toErrorString(error));
}
}
// Test_1.
{
#define TEST_FILE_NAME "/tmp/herder_util_test_isDirectory_1_XXXXXX"
char* filePath = alloca(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
#undef TEST_FILE_NAME
const int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
close(fileDescriptor);
if(util_isDirectory(filePath)){
return TEST_FAILURE("Failed to identify directory '%s'.", filePath);
}
ERROR_CODE error;
if((error = util_deleteFile(filePath)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete file:'%s'. '%s'", filePath, util_toErrorString(error));
}
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(util_startsWith){
const char a[] = "0123456789";
if(!util_startsWith(a, '0')){
return TEST_FAILURE("Error '%c' = '%c'.", a[0], '0');
}
if(util_startsWith(a, 'a')){
return TEST_FAILURE("Error '%c' != '%c'.", a[0], 'a');
}
return TEST_SUCCESS;
}
// http.c
TEST_TEST_FUNCTION(http_addHeaderField){
#define BUFFER_SIZE 8192
void* buffer;
if(util_blockAlloc(&buffer, BUFFER_SIZE) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to allocate buffer of size %d bytes.", BUFFER_SIZE);
}
HTTP_Request request;
http_initRequest_(&request, buffer, BUFFER_SIZE, 0);
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD(request, Connection, connection);
const HTTP_HeaderField* headerFieldConnection = http_getHeaderField(&request, "Connection");
if(headerFieldConnection == NULL){
return TEST_FAILURE("Failed to retrieve headeer field: '%s'.", "Connection");
}
if(strncmp("close", headerFieldConnection->value, headerFieldConnection->valueLength) != 0){
return TEST_FAILURE("Header field value '%s' != '%s'.", headerFieldConnection->value, "close");
}
http_freeHTTP_Request(&request);
util_unMap(buffer, BUFFER_SIZE);
#undef BUFFER_SIZE
return TEST_SUCCESS;
}
// que.c
TEST_TEST_FUNCTION(que_deAndEnque){
Que que;
que_init(&que);
int a = 0;
int b = 1;
int c = 2;
que_enque(&que, &a);
que_enque(&que, &b);
que_enque(&que, &c);
int value;
if((value = *((int*)que_deque(&que))) != 0){
return TEST_FAILURE("'que_deque' '%d' != '%d'.", value, 0);
}
if((value = *((int*)que_deque(&que))) != 1){
return TEST_FAILURE("'que_deque' '%d' != '%d'.", value, 1);
}
if((value = *((int*)que_deque(&que))) != 2){
return TEST_FAILURE("'que_deque' '%d' != '%d'.", value, 2);
}
que_clear(&que);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(que_clear){
Que que;
que_init(&que);
int a = 0;
int b = 1;
int c = 2;
que_enque(&que, &a);
que_enque(&que, &b);
que_enque(&que, &c);
que_clear(&que);
if(que_deque(&que) != NULL){
return TEST_FAILURE("Failed to clear que, 'que_deque' did not return: '%s'", "NULL");
}
return TEST_SUCCESS;
}
// threadPool.c
local uint_fast64_t counter = 0;
local pthread_mutex_t counterLock;
local sem_t threadSync;
THREAD_POOL_RUNNABLE(test_threadPoolRunner){
pthread_mutex_lock(&counterLock);
uint_fast64_t i;
for(i = 0; i < 10; i++){
counter++;
}
pthread_mutex_unlock(&counterLock);
sem_post(&threadSync);
return NULL;
}
TEST_TEST_FUNCTION(threadPool_run){
ThreadPool threadPool;
threadPool_init(&threadPool, 4);
ERROR_CODE error;
if((error = pthread_mutex_init(&counterLock, NULL)) != 0){
return TEST_FAILURE("Failed to initialise 'pthread_mutex'. '%d'", error);
}
if((error = sem_init(&threadSync, 0, 0)) != 0){
return TEST_FAILURE("Failed to initialise 'semaphore'. '%d'", error);
}
threadPool_run(&threadPool, test_threadPoolRunner, NULL);
threadPool_run(&threadPool, test_threadPoolRunner, NULL);
threadPool_run(&threadPool, test_threadPoolRunner, NULL);
threadPool_run(&threadPool, test_threadPoolRunner, NULL);
uint_fast64_t i;
for(i = 4; i > 0; i--){
sem_wait(&threadSync);
}
if(counter != 40){
return TEST_FAILURE("Counter value '%" PRIdFAST64 "' != '%d'.", counter, 40);
}
pthread_mutex_destroy(&counterLock);
sem_destroy(&threadSync);
threadPool_free(&threadPool);
return TEST_SUCCESS;
}
// cache.c
TEST_TEST_FUNCTION(cache_load){
ERROR_CODE error;
#define TEST_FILE_NAME "/tmp/herder_cache_test_file_XXXXXX"
// TODO:(jan) Replace with temporary file.
char* filePath = malloc(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
#undef TEST_FILE_NAME
int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
uint8_t* buffer = malloc(sizeof(*buffer) * 256);
memset(buffer, 8, 64);
memset(buffer + 64, 16, 64);
memset(buffer + 128, 8, 64);
memset(buffer + 192, 32, 64);
if(write(fileDescriptor, buffer, 256) != 256){
return TEST_FAILURE("Failed to write media library file version. Expected to write %d bytes.", 256);
}
free(buffer);
Cache cache;
if((error = cache_init(&cache, 2, MB(8))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to initialise cache. '%s'", util_toErrorString(error));
}
char symbolicFileLocation[] = "/herderTestFile";
CacheObject* cacheObject;
if((error = cache_load(&cache, &cacheObject, filePath, strlen(filePath), symbolicFileLocation, strlen(symbolicFileLocation))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to load cache object. '%s'", util_toErrorString(error));
}
if(cacheObject->size != 256){
return TEST_FAILURE("Cache object size %" PRIdFAST64 " != %d", cacheObject->size, 256);
}
uint_fast16_t i;
for(i = 0; i < 256; i++){
if(i < 64){
if(cacheObject->data[i] != 8){
return TEST_FAILURE("failed to readcache object data '%d' != '%d'", cacheObject->data[i], 8);
}
}else if(i < 128){
if(cacheObject->data[i] != 16){
return TEST_FAILURE("failed to readcache object data '%d' != '%d'", cacheObject->data[i], 16);
}
}else if(i < 192){
if(cacheObject->data[i] != 8){
return TEST_FAILURE("failed to readcache object data '%d' != '%d'", cacheObject->data[i], 8);
}
}else if(i < 256){
if(cacheObject->data[i] != 32){
return TEST_FAILURE("failed to readcache object data '%d' != '%d'", cacheObject->data[i], 32);
}
}
}
if((error = util_deleteFile(filePath)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete test file: '%s'. '%s'.", filePath, util_toErrorString(error));
}
cache_free(&cache);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(cache_get){
ERROR_CODE error;
#define TEST_FILE_NAME "/tmp/herder_cache_get_test_file_XXXXXX"
// TODO:(jan) Replace with temporary file.
char* filePath = malloc(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
#undef TEST_FILE_NAME
int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
uint8_t* buffer = malloc(sizeof(*buffer) * 256);
memset(buffer, 8, 64);
memset(buffer + 64, 16, 64);
memset(buffer + 128, 8, 64);
memset(buffer + 192, 32, 64);
if(write(fileDescriptor, buffer, 256) != 256){
return TEST_FAILURE("Failed to write media library file version. Expected to write %d bytes.", 256);
}
free(buffer);
Cache cache;
if((error = cache_init(&cache, 2, MB(8))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to initialise cache. '%s'", util_toErrorString(error));
}
char symbolicFileLocation[] = "/herderTestFile";
CacheObject* o;
if((error = cache_load(&cache, &o, filePath, strlen(filePath), symbolicFileLocation, strlen(symbolicFileLocation))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to load cache object. '%s'", util_toErrorString(error));
}
CacheObject* cacheObject;
if((error = cache_get(&cache, &cacheObject, symbolicFileLocation, strlen(symbolicFileLocation))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retireve cache object. '%s'", util_toErrorString(error));
}
uint_fast16_t i;
for(i = 0; i < 256; i++){
if(i < 64){
if(cacheObject->data[i] != 8){
return TEST_FAILURE("failed to readcache object data '%d' != '%d'", cacheObject->data[i], 8);
}
}else if(i < 128){
if(cacheObject->data[i] != 16){
return TEST_FAILURE("failed to readcache object data '%d' != '%d'", cacheObject->data[i], 16);
}
}else if(i < 192){
if(cacheObject->data[i] != 8){
return TEST_FAILURE("failed to readcache object data '%d' != '%d'", cacheObject->data[i], 8);
}
}else if(i < 256){
if(cacheObject->data[i] != 32){
return TEST_FAILURE("failed to readcache object data '%d' != '%d'", cacheObject->data[i], 32);
}
}
}
if((error = util_deleteFile(filePath)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete test file: '%s'. '%s'.", filePath, util_toErrorString(error));
}
cache_free(&cache);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(cache_overflowBehaviour){
ERROR_CODE error;
Cache cache;
if((error = cache_init(&cache, 2, 400)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to initialise cache. '%s'", util_toErrorString(error));
}
char symbolicFileLocation_000[] = "/herderTestFile_000";
char* filePath_000;
{
// File_0.
#define TEST_FILE_NAME "/tmp/herder_cache_overflowBehaviour_000_XXXXXX"
// TODO:(jan) Replace with temporary file.
filePath_000 = malloc(sizeof(*filePath_000) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath_000, TEST_FILE_NAME);
#undef TEST_FILE_NAME
int fileDescriptor = mkstemp(filePath_000);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath_000, strerror(errno));
}
uint8_t* buffer = malloc(sizeof(*buffer) * 256);
memset(buffer, 8, 64);
memset(buffer + 64, 16, 64);
memset(buffer + 128, 8, 64);
memset(buffer + 192, 32, 64);
if(write(fileDescriptor, buffer, 256) != 256){
return TEST_FAILURE("Failed to write media library file version. Expected to write %d bytes.", 256);
}
free(buffer);
CacheObject* o;
if((error = cache_load(&cache, &o, filePath_000, strlen(filePath_000), symbolicFileLocation_000, strlen(symbolicFileLocation_000))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to load cache object. '%s'", util_toErrorString(error));
}
}
// File_1.
#define TEST_FILE_NAME "/tmp/herder_cache_overflowBehaviour_001_XXXXXX"
// TODO:(jan) Replace with temporary file.
char* filePath = malloc(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
#undef TEST_FILE_NAME
int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
uint8_t* buffer = malloc(sizeof(*buffer) * 256);
memset(buffer, 8, 64);
memset(buffer + 64, 16, 64);
memset(buffer + 128, 8, 64);
memset(buffer + 192, 32, 64);
if(write(fileDescriptor, buffer, 256) != 256){
return TEST_FAILURE("Failed to write media library file version. Expected to write %d bytes.", 256);
}
free(buffer);
char symbolicFileLocation[] = "/herderTestFile_001";
CacheObject* o;
if((error = cache_load(&cache, &o, filePath, strlen(filePath), symbolicFileLocation, strlen(symbolicFileLocation))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to load cache object. '%s'", util_toErrorString(error));
}
CacheObject* cacheObject;
if((error = cache_get(&cache, &cacheObject, symbolicFileLocation_000, strlen(symbolicFileLocation_000))) == ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retireve cache object. '%s'", util_toErrorString(error));
}
cache_free(&cache);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(cache_remove){
ERROR_CODE error;
#define TEST_FILE_NAME "/tmp/herder_cache_remove_test_file_XXXXXX"
// TODO:(jan) Replace with temporary file.
char* filePath = malloc(sizeof(*filePath) * (strlen(TEST_FILE_NAME) + 1));
strcpy(filePath, TEST_FILE_NAME);
#undef TEST_FILE_NAME
int fileDescriptor = mkstemp(filePath);
if(fileDescriptor < 1){
return TEST_FAILURE("Failed to create temporary file '%s' [%s].", filePath, strerror(errno));
}
uint8_t* buffer = malloc(sizeof(*buffer) * 256);
memset(buffer, 8, 64);
memset(buffer + 64, 16, 64);
memset(buffer + 128, 8, 64);
memset(buffer + 192, 32, 64);
if(write(fileDescriptor, buffer, 256) != 256){
return TEST_FAILURE("Failed to write media library file version. Expected to write %d bytes.", 256);
}
free(buffer);
Cache cache;
if((error = cache_init(&cache, 2, MB(8))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to initialise cache. '%s'", util_toErrorString(error));
}
char symbolicFileLocation[] = "/herderTestFile";
CacheObject* o;
if((error = cache_load(&cache, &o, filePath, strlen(filePath), symbolicFileLocation, strlen(symbolicFileLocation))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to load cache object. '%s'", util_toErrorString(error));
}
if((error = util_deleteFile(filePath)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to delete test file: '%s'. '%s'.", filePath, util_toErrorString(error));
}
if((error = cache_remove(&cache, o)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to remove cache object. '%s'", util_toErrorString(error));
}
CacheObject* cacheObject;
if((error = cache_get(&cache, &cacheObject, symbolicFileLocation, strlen(symbolicFileLocation))) == ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retireve cache object. '%s'", util_toErrorString(error));
}
cache_free(&cache);
return TEST_SUCCESS;
}
// propertyFile.c
TEST_TEST_SUIT_CONSTRUCT_FUNCTION(propertyFile, propertyFile){
ERROR_CODE error = ERROR_NO_ERROR;
char currentDir[PATH_MAX];
util_getCurrentWorkingDirectory(currentDir, PATH_MAX);
const uint_fast64_t currentDirLength = strlen(currentDir);
const uint_fast64_t propertyFilePathLength = currentDirLength + 31/*"/tmp/propertyFile_add_test_file"*/;
char* propertyFilePath = alloca(sizeof(*propertyFilePath) * (propertyFilePathLength + 1));
strncpy(propertyFilePath, currentDir, currentDirLength);
strncpy(propertyFilePath + currentDirLength, "/tmp/propertyFile_add_test_file", 32);
if(util_fileExists(propertyFilePath)){
if((error = util_deleteFile(propertyFilePath)) != ERROR_NO_ERROR){
goto label_return;
}
}
if((error = propertyFile_create(propertyFilePath, propertyFilePathLength)) != ERROR_NO_ERROR){
goto label_return;
}
*propertyFile = malloc(sizeof(PropertyFile));
if(*propertyFile == NULL){
error = ERROR_OUT_OF_MEMORY;
goto label_return;
}
if((error = propertyFile_init(*propertyFile, propertyFilePath)) != ERROR_NO_ERROR){
goto label_return;
}
label_return:
return ERROR(error);
}
TEST_TEST_SUIT_DESTRUCT_FUNCTION(propertyFile, propertyFile){
char currentDir[PATH_MAX];
util_getCurrentWorkingDirectory(currentDir, PATH_MAX);
const uint_fast64_t currentDirLength = strlen(currentDir);
const uint_fast64_t propertyFilePathLength = currentDirLength + 31/*"/tmp/propertyFile_add_test_file"*/;
char* propertyFilePath = alloca(sizeof(*propertyFilePath) * (propertyFilePathLength + 1));
strncpy(propertyFilePath, currentDir, currentDirLength);
strncpy(propertyFilePath + currentDirLength, "/tmp/propertyFile_add_test_file", 32);
propertyFile_free(propertyFile);
ERROR_CODE error;
error = util_deleteFile(propertyFilePath);
free(propertyFile);
return ERROR(error);
}
TEST_TEST_FUNCTION(propertyFile_create){
ERROR_CODE error;
char currentDir[PATH_MAX];
util_getCurrentWorkingDirectory(currentDir, PATH_MAX);
const uint_fast64_t currentDirLength = strlen(currentDir);
const uint_fast64_t propertyFilePathLength = currentDirLength + 34/*"/tmp/propertyFile_create_test_file"*/;
char* propertyFilePath = alloca(sizeof(*propertyFilePath) * (propertyFilePathLength + 1));
strncpy(propertyFilePath, currentDir, currentDirLength);
strncpy(propertyFilePath + currentDirLength, "/tmp/propertyFile_create_test_file", 35);
if(util_fileExists(propertyFilePath)){
if(!util_deleteFile(propertyFilePath)){
return TEST_FAILURE("Failed to delete old file '%s'.\n", propertyFilePath);
}
}
if((error = propertyFile_create(propertyFilePath, propertyFilePathLength)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to create property file '%s'. '%s'", propertyFilePath, util_toErrorString(error));
}
util_deleteFile(propertyFilePath);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(propertyFile_addProperty, PropertyFile, propertyFile){
ERROR_CODE error;
Property* testProperty;
if((error = propertyFile_addProperty(propertyFile, &testProperty, "testProperty", sizeof(uint64_t))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add property:'testProperty'. '%s'.", util_toErrorString(error));
}
int8_t* buffer = alloca(sizeof(uint16_t));
util_uint64ToByteArray(buffer, 19875431121);
propertyFile_setBuffer(testProperty, buffer);
propertyFile_freeProperty(testProperty);
free(testProperty);
Property* retrievedProperty;
if(propertyFile_getProperty(propertyFile, &retrievedProperty, "testProperty") != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retrieve property 'testProperty'. '%s'.", util_toErrorString(error));
}
propertyFile_freeProperty(retrievedProperty);
free(retrievedProperty);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(propertyFile_getProperty, PropertyFile, propertyFile){
ERROR_CODE error;
Property* testProperty;
if((error = propertyFile_addProperty(propertyFile, &testProperty, "testProperty", sizeof(uint64_t))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add property:'testProperty'. '%s'.", util_toErrorString(error));
}
int8_t* buffer = alloca(sizeof(uint16_t));
util_uint64ToByteArray(buffer, 19875431121);
propertyFile_setBuffer(testProperty, buffer);
propertyFile_freeProperty(testProperty);
free(testProperty);
Property* retrievedProperty;
if(propertyFile_getProperty(propertyFile, &retrievedProperty, "testProperty") != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retrieve property 'testProperty'. '%s'.", util_toErrorString(error));
}
propertyFile_freeProperty(retrievedProperty);
free(retrievedProperty);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(propertyFile_contains, PropertyFile, propertyFile){
ERROR_CODE error;
Property* testProperty;
if((error = propertyFile_addProperty(propertyFile, &testProperty, "testProperty", sizeof(uint64_t))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add property:'testProperty'. '%s'.", util_toErrorString(error));
}
int8_t* buffer = alloca(sizeof(uint16_t));
util_uint64ToByteArray(buffer, 19875431121);
propertyFile_setBuffer(testProperty, buffer);
propertyFile_freeProperty(testProperty);
free(testProperty);
if(!propertyFile_contains(propertyFile, "testProperty")){
return TEST_FAILURE("Failed to retrieve property 'testProperty'. '%s'.", util_toErrorString(error));
}
if(!propertyFile_contains(propertyFile, "testProperty_2")){
return TEST_FAILURE("Failed to retrieve property 'testProperty'. '%s'.", util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(propertyFile_removeProperty, PropertyFile, propertyFile){
ERROR_CODE error;
Property* testProperty;
propertyFile_addProperty(propertyFile, &testProperty, "testProperty", sizeof(uint64_t));
int8_t* buffer = alloca(sizeof(uint16_t));
util_uint64ToByteArray(buffer, 222333444555);
propertyFile_setBuffer(testProperty, buffer);
if((error = propertyFile_removeProperty(testProperty)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to remove property 'testProperty'. '%s'.", util_toErrorString(error));
}
propertyFile_freeProperty(testProperty);
free(testProperty);
Property* retrievedProperty;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if((error = propertyFile_getProperty(propertyFile, &retrievedProperty, "testProperty")) != ERROR_ENTRY_NOT_FOUND){
propertyFile_freeProperty(retrievedProperty);
free(retrievedProperty);
return TEST_FAILURE("'propertyFile_getProperty' did not fail as expected with 'ERROR_ENTRY_NOT_FOUND' function returned '%s'", util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(propertyFile_createAndSetStringProperty, PropertyFile, propertyFile){
ERROR_CODE error;
#define TEST_STRING "test_123"
Property* testProperty = NULL;
if((error = propertyFile_createAndSetStringProperty(propertyFile, &testProperty, "testProperty", TEST_STRING, strlen(TEST_STRING))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add property:'testProperty'. '%s'.", util_toErrorString(error));
}
propertyFile_freeProperty(testProperty);
free(testProperty);
Property* retrievedProperty;
if(propertyFile_getProperty(propertyFile, &retrievedProperty, "testProperty") != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retrieve property 'testProperty'. '%s'.", util_toErrorString(error));
}
if(strncmp(TEST_STRING , (char*) retrievedProperty->buffer, strlen(TEST_STRING) + 1) != 0){
return TEST_FAILURE("Error 'testProperty' value '%s' != '%s'.", (char*) retrievedProperty->buffer, TEST_STRING);
}
#undef TEST_STRING
propertyFile_freeProperty(retrievedProperty);
free(retrievedProperty);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(propertyFile_createAndSetDirectoryProperty, PropertyFile, propertyFile){
ERROR_CODE error;
#define IMPORT_DIRECTORY "/home/ex05/herder/import"
Property* testProperty = NULL;
if((error = propertyFile_createAndSetDirectoryProperty(propertyFile, &testProperty, "testProperty", IMPORT_DIRECTORY, strlen(IMPORT_DIRECTORY))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add property:'testProperty'. '%s'.", util_toErrorString(error));
}
propertyFile_freeProperty(testProperty);
free(testProperty);
Property* retrievedProperty;
if(propertyFile_getProperty(propertyFile, &retrievedProperty, "testProperty") != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retrieve property 'testProperty'. '%s'.", util_toErrorString(error));
}
if(strncmp(IMPORT_DIRECTORY "/", (char*) retrievedProperty->buffer, strlen(IMPORT_DIRECTORY) + 2) != 0){
return TEST_FAILURE("Error 'testProperty' value '%s' != '%s'.", (char*) retrievedProperty->buffer, IMPORT_DIRECTORY "/");
}
#undef IMPORT_DIRECTORY
propertyFile_freeProperty(retrievedProperty);
free(retrievedProperty);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(propertyFile_createAndSetUINT16Property, PropertyFile, propertyFile){
ERROR_CODE error;
#define TEST_VALUE 124
Property* testProperty = NULL;
if((error = propertyFile_createAndSetUINT16Property(propertyFile, &testProperty, "testProperty", TEST_VALUE)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add property:'testProperty'. '%s'.", util_toErrorString(error));
}
propertyFile_freeProperty(testProperty);
free(testProperty);
Property* retrievedProperty;
if(propertyFile_getProperty(propertyFile, &retrievedProperty, "testProperty") != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retrieve property 'testProperty'. '%s'.", util_toErrorString(error));
}
const uint16_t retrievedValue = util_byteArrayTo_uint16(retrievedProperty->buffer);
if(retrievedValue != TEST_VALUE){
return TEST_FAILURE("Error 'testProperty' value '%" PRIu16 "' != '%" PRIu16" '.", retrievedValue, TEST_VALUE);
}
#undef TEST_VALUE
propertyFile_freeProperty(retrievedProperty);
free(retrievedProperty);
return TEST_SUCCESS;
}
// herder.c
TEST_TEST_FUNCTION(herder_constructFilePath){
EpisodeInfo info;
mediaLibrary_initEpisodeInfo(&info);
char showName[] = "American Dad";
char episodeName[] = "The last Smith";
char fileExtension[] = "mkv";
info.showName = showName;
info.showNameLength = strlen(showName);
info.name = episodeName;
info.nameLength = strlen(episodeName);
info.season = 2;
info.episode = 14;
info.fileExtension = fileExtension;
info.fileExtensionLength = strlen(fileExtension);
char* path;
uint_fast64_t pathLength;
HERDER_CONSTRUCT_RELATIVE_FILE_PATH(&path, &pathLength, &info);
if(strcmp(path, "American_Dad/American_Dad - Season_02/American_Dad_s02e14_The_last_Smith.mkv") != 0){
return TEST_FAILURE("'%s' does not equal '%s'.", path, "American_Dad/American_Dad - Season_02/American_Dad_s02e14_The_last_Smith.mkv");
}
return TEST_SUCCESS;
}
// mediaLibrary.c
TEST_TEST_SUIT_CONSTRUCT_FUNCTION(mediaLibrary, library){
ERROR_CODE error = ERROR_NO_ERROR;
char currentDir[PATH_MAX];
util_getCurrentWorkingDirectory(currentDir, PATH_MAX);
const uint_fast64_t currentDirLength = strlen(currentDir);
const uint_fast64_t libraryFileLocationLength = currentDirLength + 5/*"/tmp/"*/;
char* libraryFileLocation = alloca(sizeof(*libraryFileLocation) * (libraryFileLocationLength + 1));
strncpy(libraryFileLocation, currentDir, currentDirLength);
strncpy(libraryFileLocation + currentDirLength, "/tmp/", 6);
*library = malloc(sizeof(MediaLibrary));
if((error = mediaLibrary_init(*library, libraryFileLocation, libraryFileLocationLength)) != ERROR_NO_ERROR){
goto label_error;
}
label_error:
return ERROR(error);
}
TEST_TEST_SUIT_DESTRUCT_FUNCTION(mediaLibrary, library){
ERROR_CODE error;
mediaLibrary_free(library);
char currentDir[PATH_MAX];
util_getCurrentWorkingDirectory(currentDir, PATH_MAX);
const uint_fast64_t currentDirLength = strlen(currentDir);
const uint_fast64_t libraryFileLocationLength = currentDirLength + 5/*"/tmp/"*/;
char* libraryFileLocation = alloca(sizeof(*libraryFileLocation) * (libraryFileLocationLength + 1));
strncpy(libraryFileLocation, currentDir, currentDirLength);
strncpy(libraryFileLocation + currentDirLength, "/tmp/", 6);
char* libraryFilePath = alloca(sizeof(*libraryFilePath) * (libraryFileLocationLength + 8/*lib_data*/ + 1));
strncpy(libraryFilePath, libraryFileLocation, libraryFileLocationLength);
strncpy(libraryFilePath + libraryFileLocationLength, "lib_data", 9);
if(util_fileExists(libraryFilePath)){
if((error = util_deleteFile(libraryFilePath)) != ERROR_NO_ERROR){
UTIL_LOG_ERROR_("Failed to delete media library file. '%s'.", libraryFilePath);
}
}
free(library);
return ERROR(error);
}
TEST_TEST_FUNCTION_(mediaLibrary_getShow, MediaLibrary, library){
ERROR_CODE error;
char showName[] = "American Dad";
const uint_fast64_t showNameLength = strlen(showName);
Show* show;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if((error = medialibrary_getShow(library, &show, showName, showNameLength)) != ERROR_ENTRY_NOT_FOUND){
return TEST_FAILURE("'medialibrary_getShow' did not fail as expected with 'ERROR_ENTRY_NOT_FOUND' function returned '%s'", util_toErrorString(error));
}
if((error = mediaLibrary_addShow(library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add show: '%s'. '%s'.", showName, util_toErrorString(error));
}
if((error = medialibrary_getShow(library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retrieve show '%s' from media library. '%s'.", showName, util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(mediaLibrary_getSeason, MediaLibrary, library){
ERROR_CODE error;
char showName[] = "American Dad";
const uint_fast64_t showNameLength = strlen(showName);
Show* americanDad;
if((error = mediaLibrary_addShow(library, &americanDad, showName, showNameLength)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add show: '%s'. '%s'.", showName, util_toErrorString(error));
}
Season* season_1;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if((error = medialibrary_getSeason(americanDad, &season_1, 1)) != ERROR_ENTRY_NOT_FOUND){
return TEST_FAILURE("'mediaLiobrary_getSeason' did not fail as expected with 'ERROR_ENTRY_NOT_FOUND' function returned '%s'", util_toErrorString(error));
}
if((error = mediaLibrary_addSeason(library, &season_1, americanDad, 1)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add season 01 to '%s'. '%s'.", showName, util_toErrorString(error));
}
if((error = medialibrary_getSeason(americanDad, &season_1, 1)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retrieve season '%d' from media library. '%s'.", 1, util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(mediaLibrary_addEpisode, MediaLibrary, library){
ERROR_CODE error;
char showName[] = "American Dad";
const uint_fast64_t showNameLength = strlen(showName);
Show* americanDad;
if((error = mediaLibrary_addShow(library, &americanDad, showName, showNameLength)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add show: '%s'. '%s'.", showName, util_toErrorString(error));
}
Season* season_01;
if(mediaLibrary_addSeason(library, &season_01, americanDad, 1) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add season 01 to '%s'. '%s'.", showName, util_toErrorString(error));
}
Episode* episode;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if((error = mediaLibrary_getEpisode(season_01, &episode, 15)) != ERROR_ENTRY_NOT_FOUND){
return TEST_FAILURE("'mediaLiobrary_getEpisode' did not fail as expected with 'ERROR_ENTRY_NOT_FOUND' function returned '%s'", util_toErrorString(error));
}
char episodeName[] = "Threat Levels";
const uint_fast64_t episodeNameLength = strlen(episodeName);
if(mediaLibrary_addEpisode(library, &episode, americanDad, season_01, 15, episodeName, episodeNameLength, ".mkv", 4, true) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add episode '%s' to media library. '%s'.", episodeName, util_toErrorString(error));
}
if(mediaLibrary_getEpisode(season_01, &episode, 15) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to retrieve episode '%s' from media library. '%s'.", episodeName, util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(medialibrary_removeEpisode, MediaLibrary, library){
ERROR_CODE error;
const char showName[] = "<NAME>";
const uint_fast64_t showNameLength = strlen(showName);
Show* show;
if((error = mediaLibrary_addShow(library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add show: '%s'. '%s'.", showName, util_toErrorString(error));
}
Season* season_01;
if(mediaLibrary_addSeason(library, &season_01, show, 1) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add season 01 to '%s'. '%s'.", showName, util_toErrorString(error));
}
const char episodeName[] = "<NAME>";
const uint_fast64_t episodeNameLength = strlen(episodeName);
Episode* episode_01;
if(mediaLibrary_addEpisode(library, &episode_01, show, season_01, 1, episodeName, episodeNameLength, ".mkv", 4, true) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add episode '%s' to media library. '%s'.", episodeName, util_toErrorString(error));
}
if(medialibrary_removeEpisode(library, show, season_01, episode_01, true) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to remove episode '%s' from media library. '%s'.", episodeName, util_toErrorString(error));
}
if(!LINKED_LIST_IS_EMPTY(&show->seasons)){
return TEST_FAILURE("Failed to remove episode '%s' from media library. '%s'.", episodeName, util_toErrorString(error));
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION_(medialibrary_removeEpisodeFrromLibraryFile, MediaLibrary, library){
ERROR_CODE error;
const char showName[] = "<NAME>";
const uint_fast64_t showNameLength = strlen(showName);
Show* show;
if((error = mediaLibrary_addShow(library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add show:'%s'. '%s'.", showName, util_toErrorString(error));
}
Season* season_01;
if((error = mediaLibrary_addSeason(library, &season_01, show, 1)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add season 01 to '%s'. '%s'.", showName, util_toErrorString(error));
}
const char episodeName[] = "<NAME>";
const uint_fast64_t episodeNameLength = strlen(episodeName);
Episode* episode_01;
if((error = mediaLibrary_addEpisode(library, &episode_01, show, season_01, 1, episodeName, episodeNameLength, ".mkv", 4, true)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to add episode '%s' to media library. '%s'.", episodeName, util_toErrorString(error));
}
if(medialibrary_removeEpisodeFrromLibraryFile(library, show, season_01, episode_01) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to remove episode '%s' from library file. '%s'.", episode_01->name, util_toErrorString(error));
}
// TODO: Reload library and check if episode was removed. (jan - 2019.08.08)
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(mediaLibrary_extractShowName){
ERROR_CODE error;
LinkedList shows;
linkedList_init(&shows);
Show familyGuy;
familyGuy.name = "<NAME>";
familyGuy.nameLength = strlen(familyGuy.name);
linkedList_add(&shows, &familyGuy);
Show americanDad;
americanDad.name = "American Dad";
americanDad.nameLength = strlen(americanDad.name);
linkedList_add(&shows, &americanDad);
Show avatar;
avatar.name = "Avatar - The Last Airbender";
avatar.nameLength = strlen(avatar.name);
linkedList_add(&shows, &avatar);
EpisodeInfo info = {0};
char fileName_0[] = "American_Dad_Rogers_Spot";
if((error = mediaLibrary_extractShowName(&info, &shows, fileName_0, strlen(fileName_0))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to extract show name from string:'%s'. '%s'.", fileName_0, util_toErrorString(error));
}
if(strncmp(info.showName, americanDad.name, americanDad.nameLength + 1) != 0){
return TEST_FAILURE("Extracted value '%s' != '%s'.", info.name, americanDad.name);
}
if(strncmp(fileName_0, "Rogers_Spot", strlen("Rogers_Spot") + 1) != 0){
return TEST_FAILURE("Extracted value '%s' != '%s'.", fileName_0, "Rogers_Spot");
}
mediaLibrary_freeEpisodeInfo(&info);
memset(&info, 0, sizeof(info));
char fileName_1[] = "Family_Guy_s01e01_Death_Has_a_Shadow.avi";
if(mediaLibrary_extractShowName(&info, &shows, fileName_1, strlen(fileName_1)) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to extract show name from string:'%s'. '%s'.", fileName_1, util_toErrorString(error));
}
if(strncmp(info.showName, familyGuy.name, familyGuy.nameLength + 1) != 0){
return TEST_FAILURE("Extracted value '%s' != '%s'.", info.name, familyGuy.name);
}
if(strncmp(fileName_1, "s01e01_Death_Has_a_Shadow.avi", strlen("s01e01_Death_Has_a_Shadow.avi") + 1) != 0){
return TEST_FAILURE("Extracted value '%s' != '%s'.", fileName_0, "s01e01_Death_Has_a_Shadow.avi");
}
mediaLibrary_freeEpisodeInfo(&info);
memset(&info, 0, sizeof(info));
char fileName_2[] = "s01e01_Death_Has_a_Shadow.avi";
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_INCOMPLETE);
if(mediaLibrary_extractShowName(&info, &shows, fileName_2, strlen(fileName_2)) != ERROR_INCOMPLETE){
return TEST_FAILURE("Extracting a show name from string:'%s' did not fail as expected. '%s'.", fileName_2, util_toErrorString(error));
}
mediaLibrary_freeEpisodeInfo(&info);
linkedList_free(&shows);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(mediaLibrary_extractPrefixedNumber){
ERROR_CODE error;
char a[] = "American_Dad_s01e02_Threat_Levels.mkv";
int_fast16_t val;
if((error = mediaLibrary_extractPrefixedNumber(a, strlen(a), &val, 's')) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to extract prefixed number from string:'%s'. '%s'.", a, util_toErrorString(error));
}
if(val != 1){
return TEST_FAILURE("Extracted value '%" PRIdFAST16 "' != '%d'.", val, 1);
}
if(strncmp(a, "American_Dad_e02_Threat_Levels.mkv", strlen("American_Dad_e02_Threat_Levels.mkv") != 0)){
return TEST_FAILURE("'%" PRIdFAST16 "' != '%d'.", val, 2);
}
if((error = mediaLibrary_extractPrefixedNumber(a, strlen(a), &val, 'e')) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to extract prefixed number from string:'%s'. '%s'.", a, util_toErrorString(error));
}
if(val != 2){
return TEST_FAILURE("Extracted value '%" PRIdFAST16 "' != '%d'.", val, 2);
}
if(strncmp(a, "American_Dad__Threat_Levels.mkv", strlen("American_Dad__Threat_Levels.mkv") != 0)){
return TEST_FAILURE("'%s' != '%s'.", a, "American_Dad__Threat_Levels.mkv");
}
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(mediaLibrary_extractEpisodeInfo){
char a[] = "American_Dad_s01e01_Threat_Levels.mkv";
LinkedList shows;
linkedList_init(&shows);
const char showName[] = "American Dad";
Show americanDad;
medialibrary_initShow(&americanDad, showName, strlen(showName));
linkedList_add(&shows, &americanDad);
EpisodeInfo info;
mediaLibrary_initEpisodeInfo(&info);
ERROR_CODE error;
if((error = mediaLibrary_extractEpisodeInfo(&info, &shows, a, strlen(a))) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to extract episode info. '%s'.", util_toErrorString(error));
}
if(info.season != 1){
return TEST_FAILURE("Failed to extract season number '%" PRIdFAST16 "' != '%d'.", info.season, 1);
}
if(info.episode != 1){
return TEST_FAILURE("Failed to extract episode number '%" PRIdFAST16 "' != '%d'.", info.episode, 1);
}
if(strncmp(showName, info.showName, strlen(showName))){
return TEST_FAILURE("Failed to extract show name '%s' != '%s'.", info.showName, showName);
}
if(strncmp("Threat Levels", info.name, strlen("Threat Levels"))){
return TEST_FAILURE("Failed to extract episode name '%s' != '%s'.", info.name, "Threat Levels");
}
mediaLibrary_freeEpisodeInfo(&info);
linkedList_free(&americanDad.seasons);
free(americanDad.name);
linkedList_free(&shows);
return TEST_SUCCESS;
}
TEST_TEST_FUNCTION(mediaLibrary_sortEpisodes){
LinkedList unsortedEpisdoes;
linkedList_init(&unsortedEpisdoes);
Episode s01e04;
medialibrary_initEpisode(&s01e04, 4, "Francine's Flashback", strlen("Francine's Flashback"), "mkv", 3);
linkedList_add(&unsortedEpisdoes, &s01e04);
Episode s01e05;
medialibrary_initEpisode(&s01e05, 5, "<NAME>", strlen("R<NAME>ger"), "mkv", 3);
linkedList_add(&unsortedEpisdoes, &s01e05);
Episode s01e01;
medialibrary_initEpisode(&s01e01, 1, "Pilot", strlen("Pilot"), "mkv", 3);
linkedList_add(&unsortedEpisdoes, &s01e01);
Episode s01e03;
medialibrary_initEpisode(&s01e03, 3, "Stan Knows Best", strlen("Stan Knows Best"), "mkv", 3);
linkedList_add(&unsortedEpisdoes, &s01e03);
Episode s01e02;
medialibrary_initEpisode(&s01e02, 2, "Threat Levels", strlen("Threat Levels"), "mkv", 3);
linkedList_add(&unsortedEpisdoes, &s01e02);
Episode** episodes = alloca(sizeof(Episode) * 5);
mediaLibrary_sortEpisodes(&episodes, &unsortedEpisdoes);
uint_fast64_t i;
for(i = 0; i < 5; i++){
if(episodes[i]->number != i + 1){
return TEST_FAILURE("Failed to sort episode;'%" PRIiFAST64 "'", i + 1);
}
}
mediaLibrary_freeEpisode(&s01e04);
mediaLibrary_freeEpisode(&s01e05);
mediaLibrary_freeEpisode(&s01e01);
mediaLibrary_freeEpisode(&s01e03);
mediaLibrary_freeEpisode(&s01e02);
linkedList_free(&unsortedEpisdoes);
return TEST_SUCCESS;
}
// server.c
TEST_TEST_FUNCTION(server_addContext){
bool ret = true;
char* userHome = util_getHomeDirectory();
const uint_fast64_t userHomeLength = strlen(userHome);
char* serverRootDirectory = alloca(sizeof(*serverRootDirectory) * (userHomeLength + 12/*/herder/www/*/ + 1));
strncpy(serverRootDirectory, userHome, userHomeLength);
strncpy(serverRootDirectory + userHomeLength, "/herder/www/", 13);
const uint_fast64_t serverRootDirectoryLength = strlen(serverRootDirectory);
HerderServer server;
ERROR_CODE error;
if((error = server_init(&server, serverRootDirectory, serverRootDirectoryLength, 8088) != ERROR_NO_ERROR)){
ret = false;
goto label_free;
}
#define BUFFER_SIZE 8096
void* buffer;
if(util_blockAlloc(&buffer, BUFFER_SIZE) != ERROR_NO_ERROR){
goto label_free;
}
const char requestURL[] = "/img/img_001.png";
HTTP_Request request;
http_initRequest(&request, requestURL, strlen(requestURL), buffer, 8096, HTTP_VERSION_1_0, REQUEST_TYPE_GET);
ContextHandler* contextHandler;
if((error = server_getContext(&server, &contextHandler, &request)) == ERROR_NO_ERROR){
ret = false;
goto label_free;
}
if((error = server_addContext(&server, "/img", server_defaultContextHandler)) != ERROR_NO_ERROR){
ret = false;
goto label_free;
}
if((error = server_getContext(&server, &contextHandler, &request)) != ERROR_NO_ERROR){
ret = false;
goto label_free;
}
if(contextHandler == NULL){
ret = false;
goto label_free;
}
// Test_2.
{
const char requestURL[] = "check.proxyradar.com:80";
UTIL_LOG_CONSOLE_(LOG_DEBUG, "Test:'%s'", requestURL);
http_freeHTTP_Request(&request);
http_initRequest(&request, requestURL, strlen(requestURL), buffer, 8096, HTTP_VERSION_1_0, REQUEST_TYPE_GET);
ContextHandler* contextHandler;
if((error = server_getContext(&server, &contextHandler, &request)) == ERROR_NO_ERROR){
ret = false;
UTIL_LOG_CONSOLE(LOG_DEBUG, "GET_CONTEXT.");
goto label_free;
}
if(contextHandler != NULL){
ret = false;
goto label_free;
}
}
label_free:
http_freeHTTP_Request(&request);
server_free(&server);
util_unMap(buffer, BUFFER_SIZE);
#undef BUFFER_SIZE
return ret;
}
local SERVER_CONTEXT_HANDLER(server_testContextHandler){
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
const char str[] = "Test !~!";
const uint_fast64_t stringLength = strlen(str);
memcpy(response->data + response->dataLength, str, stringLength + 1);
response->dataLength += stringLength + 1;
return ERROR(ERROR_NO_ERROR);
}
local THREAD_POOL_RUNNABLE(server_thread){
char* userHome = util_getHomeDirectory();
const uint_fast64_t userHomeLength = strlen(userHome);
char* serverRootDirectory = alloca(sizeof(*serverRootDirectory) * (userHomeLength + 12/*/herder/www/*/ + 1));
strncpy(serverRootDirectory, userHome, userHomeLength);
strncpy(serverRootDirectory + userHomeLength, "/herder/www/", 13);
const uint_fast64_t serverRootDirectoryLength = strlen(serverRootDirectory);
HerderServer server;
ERROR_CODE error;
if((error = server_init(&server, serverRootDirectory, serverRootDirectoryLength, 8888) != ERROR_NO_ERROR)){
goto label_free;
}
server_addContext(&server, "/test", server_testContextHandler);
server_start(&server);
label_free:
server_free(&server);
return NULL;
}
TEST_TEST_FUNCTION(server_send){
ERROR_CODE error;
ThreadPool threadPool;
threadPool_init(&threadPool, 1);
threadPool_run(&threadPool, server_thread, NULL);
sleep(2);
#define BUFFER_SIZE 8096
void* requestBuffer;
if((error = util_blockAlloc(&requestBuffer, BUFFER_SIZE)) != ERROR_NO_ERROR){
return TEST_FAILURE("ERROR:'%s'.", util_toErrorString(error));
}
const char url[] = "/test";
const uint_fast64_t urlLength = strlen(url);
HTTP_Request request;
if((error = http_initRequest(&request, url, urlLength, requestBuffer, BUFFER_SIZE, HTTP_VERSION_1_1, REQUEST_TYPE_GET)) != ERROR_NO_ERROR){
return TEST_FAILURE("ERROR:'%s'.", util_toErrorString(error));
}
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD(request, Connection, connection);
void* responseBuffer;
if((error = util_blockAlloc(&responseBuffer, BUFFER_SIZE)) != ERROR_NO_ERROR){
return TEST_FAILURE("ERROR:'%s'.", util_toErrorString(error));
}
HTTP_Response response;
http_initResponse(&response, responseBuffer, BUFFER_SIZE);
int_fast32_t socketFD;
if(http_openConnection(&socketFD, "localhost", 8888) != ERROR_NO_ERROR){
return TEST_FAILURE("Failed to open connection to '%s:%d'.", "localhost", 8888);
}
http_sendRequest(&request, &response, socketFD);
http_closeConnection(socketFD);
http_freeHTTP_Request(&request);
http_freeHTTP_Response(&response);
threadPool_free(&threadPool);
util_unMap(responseBuffer, BUFFER_SIZE);
util_unMap(requestBuffer, BUFFER_SIZE);
#undef BUFFER_SIZE
return TEST_SUCCESS;
}
// main
int main(void){
TEST_BEGIN();
TEST_SUIT_BEGIN("arrayList");
TEST(arraylist_iteration);
TEST(arraylist_fixedSizedStackList);
TEST(arraylist_get);
TEST_SUIT_END();
TEST_SUIT_BEGIN_(linkedList);
TEST(linkedList_iteration);
TEST(linkedList_remove);
TEST_SUIT_END();
TEST_SUIT_BEGIN("util");
// ByteArray to Integer conversions.
TEST(util_byteArrayTo_uint16);
TEST(util_byteArrayTo_uint32);
TEST(util_byteArrayTo_uint64);
// Integer to ByteArray conversions.
TEST(util_uint16ToByteArray);
TEST(util_uint32ToByteArray);
TEST(util_uint64ToByteArray);
TEST(util_formatNumber);
// String utils.
TEST(util_findFirst);
TEST(util_findFirst_s);
TEST(util_findLast);
TEST(util_replace);
TEST(util_trim);
TEST(util_toLowerChase);
TEST(util_replaceAllChars);
TEST(util_append);
TEST(util_stringToInt);
TEST(util_getFileExtension);
TEST(util_concatenate);
TEST(util_stringCopy);
TEST(util_startsWith);
// File I/O.
TEST(util_getBaseDirectory);
TEST(util_getFileName);
TEST(util_renameFile);
TEST(util_renameFileRelative);
TEST(util_getFileDirectory);
TEST(util_fileExists);
TEST(util_fileCopy);
TEST(util_deleteFile);
TEST(util_deleteDirectory);
TEST(util_createDirectory);
TEST(util_createAllDirectories);
TEST(util_isDirectory);
// Other.
TEST(util_hash);
TEST(util_blockAlloc);
TEST_SUIT_END();
TEST_SUIT_BEGIN("argumentParser");
TEST(argumentParser_parse);
TEST_SUIT_END();
TEST_SUIT_BEGIN("http");
TEST(http_addHeaderField);
TEST_SUIT_END();
TEST_SUIT_BEGIN("que");
TEST(que_deAndEnque);
TEST(que_clear);
TEST_SUIT_END();
TEST_SUIT_BEGIN("threadPool");
TEST(threadPool_run);
TEST_SUIT_END();
TEST_SUIT_BEGIN("cache");
TEST(cache_load);
TEST(cache_get);
TEST(cache_remove);
TEST(cache_overflowBehaviour);
TEST_SUIT_END();
TEST_SUIT_BEGIN_(propertyFile);
__TEST_NO_SETUP__(); TEST(propertyFile_create);
TEST(propertyFile_addProperty);
TEST(propertyFile_createAndSetUINT16Property);
TEST(propertyFile_createAndSetStringProperty);
TEST(propertyFile_createAndSetDirectoryProperty);
TEST(propertyFile_removeProperty);
TEST(propertyFile_getProperty);
TEST(propertyFile_contains);
TEST_SUIT_END();
TEST_SUIT_BEGIN_(mediaLibrary);
TEST(mediaLibrary_getShow);
TEST(mediaLibrary_getSeason);
TEST(mediaLibrary_addEpisode);
TEST(medialibrary_removeEpisode);
TEST(medialibrary_removeEpisodeFrromLibraryFile);
TEST_NO_SETUP(mediaLibrary_extractShowName);
TEST_NO_SETUP(mediaLibrary_extractPrefixedNumber);
TEST_NO_SETUP(mediaLibrary_extractEpisodeInfo);
TEST_NO_SETUP(mediaLibrary_sortEpisodes);
TEST_SUIT_END();
TEST_SUIT_BEGIN("herder");
TEST(herder_constructFilePath);
TEST_SUIT_END();
/* TEST_SUIT_BEGIN("server");
// Note:(jan) Running the server in valgrind takes to long, probably due to the 'accept' call having to be interrupted in the server loop.
TEST(server_addContext);
// Note:(jan) No need to run this, as this was not meant to be an automated test, and needed console output in 'http.c' that is no longer present to be useful.
// TEST(server_send);
TEST_SUIT_END(); */
TEST_END();
}
|
Ex05/herder
|
src/mediaLibrary.c
|
<reponame>Ex05/herder
#ifndef MEDIA_LIBRARY_C
#define MEDIA_LIBRARY_C
#include "mediaLibrary.h"
#include "linkedList.c"
#include "util.c"
#define LIBRARY_FILE_NAME "lib_data"
// TODO: Decide if we want to use the '({ })' gcc extension here to be able to return an error code from here. (jan - 2019.05.17)
#define MEDIA_LIBRARY_READ_FROM_LIBRARY_FILE(error, file, name, type) do { \
int8_t readBuffer[sizeof(type)]; \
if(fread(readBuffer, sizeof(type), 1, file) != 1){ \
error = ERROR_READ_ERROR; \
}else{ \
*name = util_byteArrayTo_ ## type(readBuffer); \
\
error = ERROR_NO_ERROR; \
} \
}while(0)
local const Version MEDIA_LIBRARY_FILE_VERSION = {0, 1, 0};
local ERROR_CODE mediaLibrary_extractShowName(EpisodeInfo*, LinkedList*, char*, const uint_fast64_t);
local ERROR_CODE mediaLibrary_extractEpisodeNumber(EpisodeInfo*, char*, const uint_fast64_t);
local ERROR_CODE mediaLibrary_extractEpisodeName(EpisodeInfo*, char*, const uint_fast64_t);
local ERROR_CODE mediaLibrary_extractSeasonNumber(EpisodeInfo*, char*, const uint_fast64_t);
local ERROR_CODE mediaLibrary_containsShow(LinkedList*, Show**, const char*, const uint_fast64_t);
local ERROR_CODE medialibrary_initShow(Show*, const char*, const uint_fast64_t);
local ERROR_CODE medialibrary_initEpisode(Episode*, const uint_fast16_t, const char*, const uint_fast64_t, const char*, const uint_fast16_t);
local ERROR_CODE medialibrary_initSeason(Season*, const uint_fast16_t);
local bool mediaLibrary_isCharcterWordDelimiter(char);
local void mediaLibrary_freeShow(Show*);
local void mediaLibrary_freeSeason(Season*);
local void mediaLibrary_freeEpisode(Episode*);
local ERROR_CODE mediaLibrary_readStringFromLibraryFile(FILE*, char**, uint_fast64_t);
local ERROR_CODE mediaLibrary_readShowNameLength(FILE*, uint_fast64_t*);
local ERROR_CODE mediaLibrary_readShowName(FILE*, char**, uint_fast64_t);
local ERROR_CODE mediaLibrary_readSeasonNumber(FILE*, uint_fast16_t*);
local ERROR_CODE mediaLibrary_readEpisodeNumber(FILE*, uint_fast16_t*);
local ERROR_CODE mediaLibrary_readEpisodeNumber(FILE*, uint_fast16_t*);
local ERROR_CODE mediaLibrary_readEpisodeNameLength(FILE*, uint_fast64_t*);
local ERROR_CODE mediaLibrary_readEpisodeName(FILE*, char**, uint_fast64_t);
local ERROR_CODE mediaLibrary_readFileExtensionLength(FILE*, uint_fast16_t*);
local ERROR_CODE mediaLibrary_readFileExtension(FILE*, char**, uint_fast64_t);
local ERROR_CODE medialibrary_removeShowFrromLibraryFile(MediaLibrary*, const char*);
local ERROR_CODE medialibrary_removeEpisodeFrromLibraryFile(MediaLibrary*, Show*, const Season*, const Episode*);
// TODO:(jan) Clean up this mess.
ERROR_CODE mediaLibrary_init(MediaLibrary* library, const char* libraryLocation, const uint_fast64_t libraryLocationLength){
ERROR_CODE error = ERROR_NO_ERROR;
memset(library, 0, sizeof(*library));
linkedList_init(&library->shows);
if(!util_fileExists(libraryLocation)){
if((error = util_createDirectory(libraryLocation)) != ERROR_NO_ERROR){
return ERROR(error);
}else{
UTIL_LOG_INFO_("Successfully created directory: '%s'.", libraryLocation);
}
}
library->libraryFileLocation = malloc(sizeof(*library->libraryFileLocation) * (libraryLocationLength + 1));
if(library->libraryFileLocation == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(library->libraryFileLocation, libraryLocation, libraryLocationLength + 1);
library->libraryFileLocationLength = libraryLocationLength;
const uint_fast64_t libraryFileNameLength = strlen(LIBRARY_FILE_NAME);
const uint_fast64_t libraryFileLength = libraryLocationLength + libraryFileNameLength;
char* libraryFile = alloca(sizeof(*libraryFile) * (libraryFileLength + 1));
strncpy(libraryFile, libraryLocation, libraryLocationLength);
strncpy(libraryFile + libraryLocationLength, LIBRARY_FILE_NAME, libraryFileNameLength);
libraryFile[libraryFileLength] = '\0';
if(!util_fileExists(libraryFile)){
FILE* file = fopen(libraryFile, "w+");
if(file == NULL){
UTIL_LOG_ERROR_("Failed to create file: '%s' - '%s'.", libraryFile, strerror(errno));
return ERROR(ERROR_FAILED_TO_CREATE_FILE);
}
library->libraryFile = file;
uint_fast8_t buffer[] = {
MEDIA_LIBRARY_FILE_VERSION.release,
MEDIA_LIBRARY_FILE_VERSION.update,
MEDIA_LIBRARY_FILE_VERSION.hotfix
};
if(fwrite(buffer, sizeof(MEDIA_LIBRARY_FILE_VERSION), 1, file) != 1){
UTIL_LOG_ERROR("Failed to write media library file version.");
return ERROR(ERROR_WRITE_ERROR);
}
if(fflush(file) != 0){
return ERROR(ERROR_DISK_ERROR);
}
}else{
FILE* file = fopen(libraryFile, "r+");
if(file == NULL){
return ERROR(ERROR_FAILED_TO_OPEN_FILE);
}
library->libraryFile = file;
if(fread(&library->version, sizeof(library->version), 1, file) != 1){
UTIL_LOG_ERROR("Failed to read media library file version.");
return ERROR(ERROR_READ_ERROR);
}
if(MEDIA_LIBRARY_FILE_VERSION.release != library->version.release && MEDIA_LIBRARY_FILE_VERSION.update == library->version.update && MEDIA_LIBRARY_FILE_VERSION.hotfix == library->version.hotfix){
UTIL_LOG_ERROR_("Version missmatch [%" PRIu8 ".%" PRIu8 ".%" PRIu8"].", library->version.release, library->version.update, library->version.hotfix);
return ERROR(ERROR_VERSION_MISSMATCH);
}
for(;;){
// Show_Name.
uint_fast64_t showNameLength;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_END_OF_FILE);
if((error = mediaLibrary_readShowNameLength(file, &showNameLength)) != ERROR_NO_ERROR){
if(error == ERROR_END_OF_FILE){
break;
}
goto label_return;
}
char* showName;
showName = alloca(sizeof(*showName) * (showNameLength + 1));
if((error = mediaLibrary_readShowName(file, &showName, showNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
const bool entryWasRemoved = showNameLength != 0 && *showName == '\0';
Show* show;
if(!entryWasRemoved && (error = mediaLibrary_addShow(library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
if(error != ERROR_DUPLICATE_ENTRY){
return ERROR(error);
}
}
// Season_Number.
uint_fast16_t seasonNumber;
if((error = mediaLibrary_readSeasonNumber(file, &seasonNumber)) != ERROR_NO_ERROR){
goto label_return;
}
Season* season;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if(!entryWasRemoved && (error = medialibrary_getSeason(show, &season, seasonNumber)) != ERROR_NO_ERROR){
if(error == ERROR_ENTRY_NOT_FOUND){
if((error = mediaLibrary_addSeason(library, &season, show, seasonNumber)) != ERROR_NO_ERROR){
goto label_return;
}
}else{
goto label_return;
}
}
// Episode_Number.
uint_fast16_t episodeNumber;
if((error = mediaLibrary_readEpisodeNumber(file, &episodeNumber)) != ERROR_NO_ERROR){
goto label_return;
}
// Episode_Name.
uint_fast64_t episodeNameLength;
if((error = mediaLibrary_readEpisodeNameLength(file, &episodeNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
char* episodeName;
episodeName = alloca(sizeof(*episodeName) * (episodeNameLength + 1));
if((error = mediaLibrary_readEpisodeName(file, &episodeName, episodeNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
// File_Extension.
uint_fast16_t fileExtensionLength;
if((error = mediaLibrary_readFileExtensionLength(file, &fileExtensionLength)) != ERROR_NO_ERROR){
goto label_return;
}
char* fileExtension;
fileExtension = alloca(sizeof(*fileExtension) * (fileExtensionLength + 1));
if((error = mediaLibrary_readFileExtension(file, &fileExtension, fileExtensionLength)) != ERROR_NO_ERROR){
goto label_return;
}
Episode* episode;
if(!entryWasRemoved){
error = mediaLibrary_addEpisode(library, &episode, show, season, episodeNumber, episodeName, episodeNameLength, fileExtension, fileExtensionLength, false);
}
label_return:
if(error != ERROR_NO_ERROR){
return ERROR(error);
}
}
}
return ERROR(ERROR_NO_ERROR);
}
inline void mediaLibrary_freeShow(Show* show){
LinkedListIterator seasonIterator;
linkedList_initIterator(&seasonIterator, &show->seasons);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&seasonIterator)){
Season* season = LINKED_LIST_ITERATOR_NEXT(&seasonIterator);
LinkedListIterator epsisodeIterator;
linkedList_initIterator(&epsisodeIterator, &season->episodes);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&epsisodeIterator)){
Episode* episode = LINKED_LIST_ITERATOR_NEXT(&epsisodeIterator);
mediaLibrary_freeEpisode(episode);
free(episode);
}
mediaLibrary_freeSeason(season);
free(season);
}
linkedList_free(&show->seasons);
free(show->name);
}
inline void mediaLibrary_freeSeason(Season* season){
linkedList_free(&season->episodes);
}
inline void mediaLibrary_freeEpisode(Episode* episode){
free(episode->name);
free(episode->fileExtension);
}
inline void mediaLibrary_free(MediaLibrary* library){
LinkedListIterator it;
linkedList_initIterator(&it, &library->shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
mediaLibrary_freeShow(show);
free(show);
}
linkedList_free(&library->shows);
if(library->libraryFile != NULL){
fclose(library->libraryFile);
}
free(library->libraryFileLocation);
}
inline ERROR_CODE mediaLibrary_extractEpisodeInfo(EpisodeInfo* info, LinkedList* shows, char* fileName, const uint_fast64_t fileNameLength){
// NOTE:(jan) All the strlen calls are needed, as each of the 'medialibrary_extract...' calls modify the file name.
ERROR_CODE error = ERROR_NO_ERROR;
if(mediaLibrary_extractSeasonNumber(info, fileName, strlen(fileName)) != ERROR_NO_ERROR){
error = ERROR_INCOMPLETE;
}
if(mediaLibrary_extractEpisodeNumber(info, fileName, strlen(fileName)) != ERROR_NO_ERROR){
error = ERROR_INCOMPLETE;
}
if(mediaLibrary_extractShowName(info, shows, fileName, strlen(fileName)) != ERROR_NO_ERROR){
error = ERROR_INCOMPLETE;
}
if(mediaLibrary_extractEpisodeName(info, fileName, strlen(fileName)) != ERROR_NO_ERROR){
error = ERROR_INCOMPLETE;
}
return error;
}
inline ERROR_CODE mediaLibrary_extractEpisodeName(EpisodeInfo* info, char* fileName, uint_fast64_t fileNameLength){
fileName = util_trim(fileName, fileNameLength);
char* s;
while((s = strstr(fileName, "__")) != NULL){
util_stringCopy(s, s + 1, strlen(s));
}
if(*fileName == '_'){
util_stringCopy(fileName, fileName + 1, strlen(fileName));
}
fileNameLength = strlen(fileName);
int_fast64_t fileExtensionOffset = util_findLast(fileName, fileNameLength, '.');
if(fileExtensionOffset != -1){
fileName[fileExtensionOffset] = '\0';
fileNameLength--;
}
if(fileNameLength <= 0){
info->nameLength = 0;
info->name = NULL;
return ERROR(ERROR_INCOMPLETE);
}
info->name = malloc(sizeof(*info->name) * (fileNameLength + 1));
if(info->name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(info->name, fileName, fileNameLength + 1);
util_replaceAllChars(info->name, '_', ' ');
info->nameLength = fileNameLength;
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_extractPrefixedNumber(char* fileName, uint_fast64_t fileNameLength, int_fast16_t* value, const char prefix){
char* lowerChaseFileName = alloca(sizeof(*lowerChaseFileName) * (fileNameLength + 1));
util_stringCopy(lowerChaseFileName, fileName, fileNameLength + 1);
util_toLowerChase(lowerChaseFileName);
int_fast64_t offset;
int_fast64_t writeOffset = 0;
while((offset = util_findFirst(lowerChaseFileName, fileNameLength, prefix)) != -1){
lowerChaseFileName += ++offset;
fileNameLength -= offset;
writeOffset += offset;
uint_fast64_t i;
for(i = 0; i < fileNameLength; i++){
const char c = lowerChaseFileName[i];
if(isdigit(c) == 0){
break;
}
}
if(i > 0){
char* numberString = alloca(sizeof(*numberString) * (i + 1));
strncpy(numberString, lowerChaseFileName, i);
numberString[i] = '\0';
util_stringCopy(fileName + writeOffset - 1, fileName + writeOffset + i, strlen(fileName + writeOffset) + 1 - i);
char* endPtr;
*value = strtol(numberString, &endPtr, 10);
if((*value == 0 && endPtr == numberString) || *value == LONG_MIN || *value == LONG_MAX){
*value = 0;
return ERROR_(ERROR_CONVERSION_ERROR, "'%s' is not a valid number.", numberString);
}
return ERROR(ERROR_NO_ERROR);
}
}
*value = 0;
return ERROR(ERROR_ENTRY_NOT_FOUND);
}
inline ERROR_CODE mediaLibrary_extractEpisodeNumber(EpisodeInfo* info, char* fileName, const uint_fast64_t fileNameLength){
ERROR_CODE error;
if((error = mediaLibrary_extractPrefixedNumber(fileName, fileNameLength, &info->episode, 'e')) != ERROR_NO_ERROR){
return ERROR(error);
}
if(info->episode == 0){
return ERROR(ERROR_INCOMPLETE);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_extractSeasonNumber(EpisodeInfo* info, char* fileName, const uint_fast64_t fileNameLength){
ERROR_CODE error;
if((error = mediaLibrary_extractPrefixedNumber(fileName, fileNameLength, &info->season, 's')) != ERROR_NO_ERROR){
return ERROR(error);
}
if(info->season == 0){
return ERROR(ERROR_INCOMPLETE);
}
return ERROR(ERROR_NO_ERROR);
}
// TODO:(jan) Refactor this mess and add some guidance for readers.
ERROR_CODE mediaLibrary_extractShowName(EpisodeInfo* info, LinkedList* shows, char* fileName, const uint_fast64_t fileNameLength){
uint_fast64_t endIndex = 0;
// We need the trailing '/0' of the file name to terminate our loop.
uint_fast64_t remainingCharacter = fileNameLength + 1;
// Split the filename into easily searchable word chunks.
LinkedList wordList;
linkedList_init(&wordList);
char* lowerCaseFileName = alloca(sizeof(*lowerCaseFileName) * (fileNameLength + 1));
strncpy(lowerCaseFileName, fileName, fileNameLength + 1);
util_toLowerChase(lowerCaseFileName);
while(remainingCharacter > 0){
char c;
do{
c = lowerCaseFileName[endIndex++];
}while(c != '\0' && !mediaLibrary_isCharcterWordDelimiter(c));
if(endIndex == 1){
goto label_continue;
}
if(endIndex > 2){
char* wordChunk = alloca(sizeof(*wordChunk) * endIndex);
memcpy(wordChunk, lowerCaseFileName, endIndex - 1);
wordChunk[endIndex - 1] = '\0';
linkedList_add(&wordList, wordChunk);
}
label_continue:
lowerCaseFileName += endIndex;
remainingCharacter -= endIndex;
endIndex = 0;
}
// Iterate over each word chunk and search the existing shows names for the best match.
LinkedListIterator showIterator;
linkedList_initIterator(&showIterator, shows);
uint_fast32_t maxHits = 0;
Show* mostLikely = NULL;
LinkedListIterator wordListIterator;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&showIterator)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&showIterator);
char* lowerChaseShowName = alloca(sizeof(*lowerChaseShowName) * (show->nameLength + 1));
strncpy(lowerChaseShowName, show->name, show->nameLength + 1);
util_toLowerChase(lowerChaseShowName);
linkedList_initIterator(&wordListIterator, &wordList);
uint_fast32_t hits = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&wordListIterator)){
char* wordChunk = LINKED_LIST_ITERATOR_NEXT(&wordListIterator);
if(strstr(lowerChaseShowName, wordChunk) != NULL){
hits++;
}
}
if(hits > maxHits){
mostLikely = show;
maxHits = hits;
}
}
linkedList_free(&wordList);
if(mostLikely != NULL){
info->showName = malloc(sizeof(*info->showName) * (mostLikely->nameLength + 1));
if(info->showName == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(info->showName, mostLikely->name, mostLikely->nameLength + 1);
info->showNameLength = mostLikely->nameLength;
// Remove show name from file name.
char* lowerCaseFileName = alloca(sizeof(*lowerCaseFileName) * (fileNameLength + 1));
strncpy(lowerCaseFileName, fileName, fileNameLength + 1);
util_toLowerChase(lowerCaseFileName);
char* lowerCaseShowName = alloca(sizeof(*lowerCaseShowName) * (mostLikely->nameLength + 1));
strncpy(lowerCaseShowName, mostLikely->name, mostLikely->nameLength + 1);
util_toLowerChase(lowerCaseShowName);
char* beginIndex = strstr(lowerCaseFileName, lowerCaseShowName);
if(beginIndex != NULL){
const intptr_t offset = beginIndex - lowerCaseFileName;
const bool leadingWordDelimiterPresent = (fileName + offset)[mostLikely->nameLength] == '_';
util_stringCopy(fileName + offset, (fileName + offset + (leadingWordDelimiterPresent? 1 : 0)) + mostLikely->nameLength, strlen(fileName + offset) + 1 - mostLikely->nameLength - (leadingWordDelimiterPresent? 1 : 0));
}else{
util_replaceAllChars(lowerCaseShowName, ' ', '_');
beginIndex = strstr(lowerCaseFileName, lowerCaseShowName);
if(beginIndex != NULL){
const intptr_t offset = beginIndex - lowerCaseFileName;
const bool leadingWordDelimiterPresent = (fileName + offset)[mostLikely->nameLength] == '_';
util_stringCopy(fileName + offset, (fileName + offset + (leadingWordDelimiterPresent? 1 : 0)) + mostLikely->nameLength, strlen(fileName + offset) + 1 - mostLikely->nameLength - (leadingWordDelimiterPresent? 1 : 0));
}
}
return ERROR(ERROR_NO_ERROR);
}
info->showName = NULL;
info->showNameLength = 0;
return ERROR(ERROR_INCOMPLETE);
}
inline bool mediaLibrary_isCharcterWordDelimiter(char c){
return c == '.' || c == ' ' || c == '_';
}
inline ERROR_CODE mediaLibrary_addShow(MediaLibrary* library, Show** show, const char* name, const uint_fast64_t nameLength){
*show = NULL;
char* noneWhiteSpaceName = alloca(sizeof(*noneWhiteSpaceName) * (nameLength + 1));
memcpy(noneWhiteSpaceName, name, nameLength);
noneWhiteSpaceName[nameLength] = '\0';
uint64_t noneWhiteSpaceNameLength = nameLength;
do{
ERROR_CODE error;
if((error = util_replace(noneWhiteSpaceName, nameLength + 1, &noneWhiteSpaceNameLength, " ", 2, " ", 1)) != ERROR_NO_ERROR){
return ERROR(error);
}
}
while(noneWhiteSpaceNameLength < nameLength);
ERROR_CODE error;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if((error = mediaLibrary_containsShow(&library->shows, show, noneWhiteSpaceName, noneWhiteSpaceNameLength)) == ERROR_NO_ERROR){
// NOTE: One could make a strong argument here to return "ERROR_DUPLICATE_ENTRY' but the current eco-system does not support nested suppresion of error. But because the caller can not distinguish from the outside, we are for now just gona pretend everything is 'OK' and return 'ERROR_NO_ERROR'. (jan - 2019.09.04)*/
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_DUPLICATE_ENTRY);
return ERROR(ERROR_DUPLICATE_ENTRY);
}
*show = malloc(sizeof(**show));
if(*show == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
medialibrary_initShow(*show, noneWhiteSpaceName, noneWhiteSpaceNameLength);
linkedList_add(&library->shows, *show);
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_removeShow(MediaLibrary* library, const char* name, const uint_fast64_t nameLength){
Show* show = NULL;
char* noneWhiteSpaceName = alloca(sizeof(*noneWhiteSpaceName) * (nameLength + 1));
memcpy(noneWhiteSpaceName, name, nameLength);
noneWhiteSpaceName[nameLength] = '\0';
uint64_t noneWhiteSpaceNameLength = nameLength;
do{
ERROR_CODE error;
if((error = util_replace(noneWhiteSpaceName, nameLength + 1, &noneWhiteSpaceNameLength, " ", 2, " ", 1)) != ERROR_NO_ERROR){
return ERROR(error);
}
}
while(noneWhiteSpaceNameLength < nameLength);
ERROR_CODE error;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if((error = mediaLibrary_containsShow(&library->shows, &show, noneWhiteSpaceName, noneWhiteSpaceNameLength)) == ERROR_ENTRY_NOT_FOUND){
return ERROR(error);
}
linkedList_remove(&library->shows, show);
const bool isShowEmpty = LINKED_LIST_IS_EMPTY(&show->seasons);
LinkedListIterator seasonIterator;
linkedList_initIterator(&seasonIterator, &show->seasons);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&seasonIterator)){
Season* season = LINKED_LIST_ITERATOR_NEXT(&seasonIterator);
LinkedListIterator episodeIterator;
linkedList_initIterator(&episodeIterator, &season->episodes);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&episodeIterator)){
Episode* episode = LINKED_LIST_ITERATOR_NEXT(&episodeIterator);
mediaLibrary_freeEpisode(episode);
free(episode);
}
mediaLibrary_freeSeason(season);
free(season);
}
if(!isShowEmpty){
if((error = medialibrary_removeShowFrromLibraryFile(library, name)) != ERROR_NO_ERROR){
goto label_freeShow;
}
}
label_freeShow:
mediaLibrary_freeShow(show);
free(show);
return ERROR(error);
}
ERROR_CODE medialibrary_removeEpisode(MediaLibrary* library, Show* show, Season* season, Episode* episode, const bool removeFromDisk){
ERROR_CODE error;
if((error = linkedList_remove(&season->episodes, episode)) != ERROR_NO_ERROR){
UTIL_LOG_ERROR("Failed to remove episode from season.");
goto label_return;
}
if(removeFromDisk){
if((error = medialibrary_removeEpisodeFrromLibraryFile(library, show, season, episode)) != ERROR_NO_ERROR){
goto label_return;
}
}
if(LINKED_LIST_IS_EMPTY(&season->episodes)){
if((error = linkedList_remove(&show->seasons, season)) != ERROR_NO_ERROR){
UTIL_LOG_ERROR_("Failed to remove empty season %" PRIuFAST16" from from.", season->number);
goto label_return;
}
linkedList_free(&season->episodes);
free(season);
}
mediaLibrary_freeEpisode(episode);
free(episode);
label_return:
return ERROR(error);
}
ERROR_CODE medialibrary_removeEpisodeFrromLibraryFile(MediaLibrary* library, Show* show, const Season* season, const Episode* episode){
ERROR_CODE error = ERROR_NO_ERROR;
FILE* file = library->libraryFile;
if(fseek(file, 0, SEEK_SET) != 0){
error = ERROR_DISK_ERROR;
goto label_return;
}
if(fseek(file, sizeof(library->version), SEEK_CUR) != 0){
error = ERROR_DISK_ERROR;
goto label_return;
}
const int_fast8_t writeBuffer[1] = {0};
for(;;){
uint_fast8_t fillZero = 1;
// Show_Name.
uint_fast64_t showNameLength;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_END_OF_FILE);
if((error = mediaLibrary_readShowNameLength(file, &showNameLength)) != ERROR_NO_ERROR){
if(error == ERROR_END_OF_FILE){
error = ERROR_NO_ERROR;
break;
}
goto label_return;
}
const long showNameOffset = ftell(file);
char* showName;
showName = alloca(sizeof(*showName) * (showNameLength + 1));
if((error = mediaLibrary_readShowName(file, &showName, showNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
if(strncmp(showName, show->name, show->nameLength + 1) == 0){
fillZero <<= 1;
}
// Season_Number.
uint_fast16_t seasonNumber;
if((error = mediaLibrary_readSeasonNumber(file, &seasonNumber)) != ERROR_NO_ERROR){
goto label_return;
}
if(seasonNumber == season->number){
fillZero <<= 1;
}
// Episode_Number.
uint_fast16_t episodeNumber;
if((error = mediaLibrary_readEpisodeNumber(file, &episodeNumber)) != ERROR_NO_ERROR){
goto label_return;
}
if(episodeNumber == episode->number){
fillZero <<= 1;
}
// Episode_Name.
uint_fast64_t episodeNameLength;
if((error = mediaLibrary_readEpisodeNameLength(file, &episodeNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
if(fseek(file, episodeNameLength + 1, SEEK_CUR) != 0){
ERROR(error = ERROR_DISK_ERROR);
goto label_return;
}
// File_Extension.
uint_fast16_t fileExtensionLength;
if((error = mediaLibrary_readFileExtensionLength(file, &fileExtensionLength)) != ERROR_NO_ERROR){
goto label_return;
}
if(fseek(file, fileExtensionLength + 1, SEEK_CUR) != 0){
ERROR(error = ERROR_DISK_ERROR);
goto label_return;
}
#define FILL_WITH_ZERO 8
if(fillZero == FILL_WITH_ZERO){
// Overwrite entry.
if(fseek(file, showNameOffset, SEEK_SET) != 0){
ERROR(error = ERROR_DISK_ERROR);
goto label_return;
}
// Show_Name.
if(fwrite(writeBuffer, 1, showNameLength + 1, file) != showNameLength + 1){
ERROR(error = ERROR_WRITE_ERROR);
goto label_return;
}
// Season_Number.
if(fwrite(writeBuffer, 1, sizeof(uint16_t), file) != sizeof(uint16_t)){
ERROR(error = ERROR_WRITE_ERROR);
goto label_return;
}
// Episode_Number.
if(fwrite(writeBuffer, 1, sizeof(uint16_t), file) != sizeof(uint16_t)){
ERROR(error = ERROR_WRITE_ERROR);
goto label_return;
}
// Episode_Name.
if(fseek(file, sizeof(uint64_t), SEEK_CUR) != 0){
ERROR(error = ERROR_DISK_ERROR);
goto label_return;
}
if(fwrite(writeBuffer, 1, episodeNameLength + 1, file) != episodeNameLength + 1){
ERROR(error = ERROR_WRITE_ERROR);
goto label_return;
}
// File_Extension.
if(fseek(file, sizeof(uint16_t), SEEK_CUR) != 0){
ERROR(error = ERROR_DISK_ERROR);
goto label_return;
}
if(fwrite(writeBuffer, fileExtensionLength + 1, 1, file) != 1){
ERROR(error = ERROR_WRITE_ERROR);
goto label_return;
}
break;
}
#undef FILL_WITH_ZERO
}
label_return:
return ERROR(error);
}
ERROR_CODE medialibrary_removeShowFrromLibraryFile(MediaLibrary* library, const char* show){
ERROR_CODE error = ERROR_NO_ERROR;
const uint_fast64_t showLength = strlen(show);
FILE* file = library->libraryFile;
if(fseek(file, 0, SEEK_SET) != 0){
error = ERROR_DISK_ERROR;
goto label_return;
}
if(fseek(file, sizeof(library->version), SEEK_CUR) != 0){
error = ERROR_DISK_ERROR;
goto label_return;
}
const int_fast8_t writeBuffer[1] = {0};
for(;;){
// Show_Name.
uint_fast64_t showNameLength;
if((error = mediaLibrary_readShowNameLength(file, &showNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
char* showName;
showName = alloca(sizeof(*showName) * (showNameLength + 1));
if((error = mediaLibrary_readShowName(file, &showName, showNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
const long showNameOffset = ftell(file) - showNameLength;
bool fillZero;
if((fillZero = strncmp(show, showName, showLength) == 0)){
// Overwrite showName.
if(fseek(file, showNameOffset, SEEK_SET) != 0){
error = ERROR_DISK_ERROR;
ERROR(error);
goto label_return;
}
if(fwrite(writeBuffer, 1, showNameLength + 1, file) != showNameLength + 1){
error = ERROR_WRITE_ERROR;
ERROR(error);
goto label_return;
}
// Season_Number.
if(fwrite(writeBuffer, 1, sizeof(uint16_t), file) != sizeof(uint16_t)){
error = ERROR_WRITE_ERROR;
ERROR(error);
goto label_return;
}
// Episode_Number.
if(fwrite(writeBuffer, 1, sizeof(uint16_t), file) != sizeof(uint16_t)){
error = ERROR_WRITE_ERROR;
ERROR(error);
goto label_return;
}
}else{
// Skip Season_Number & Episode_Number.
if(fseek(file, sizeof(uint16_t) * 2, SEEK_CUR) != 0){
error = ERROR_DISK_ERROR;
ERROR(error);
goto label_return;
}
}
// Episode_Name.
uint_fast64_t episodeNameLength;
if((error = mediaLibrary_readEpisodeNameLength(file, &episodeNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
if(fillZero){
if(fwrite(writeBuffer, 1, episodeNameLength + 1, file) != episodeNameLength + 1){
error = ERROR_WRITE_ERROR;
ERROR(error);
goto label_return;
}
}else{
if(fseek(file, episodeNameLength + 1, SEEK_CUR) != 0){
error = ERROR_DISK_ERROR;
ERROR(error);
goto label_return;
}
}
// File_Extension.
uint_fast16_t fileExtensionLength;
if((error = mediaLibrary_readFileExtensionLength(file, &fileExtensionLength)) != ERROR_NO_ERROR){
goto label_return;
}
if(fillZero){
if(fwrite(writeBuffer, fileExtensionLength + 1, 1, file) != 1){
error = ERROR_WRITE_ERROR;
ERROR(error);
goto label_return;
}
}else{
if(fseek(file, fileExtensionLength + 1, SEEK_CUR) != 0){
error = ERROR_DISK_ERROR;
ERROR(error);
goto label_return;
}
}
label_return:
if(error != ERROR_NO_ERROR){
return ERROR(error);
}
}
char* noWhiteSpaceShowName = alloca(sizeof(*noWhiteSpaceShowName) * (showLength + 1/*'/'*/ + 1));
strncpy(noWhiteSpaceShowName, show, showLength + 1);
util_replaceAllChars(noWhiteSpaceShowName, ' ', '_');
noWhiteSpaceShowName[showLength] = '/';
const uint_fast64_t showPathLength = library->libraryFileLocationLength + showLength;
char* showPath;
showPath = alloca(sizeof(*showPath) * (showPathLength + 1));
strncpy(showPath, library->libraryFileLocation, library->libraryFileLocationLength);
strncpy(showPath + library->libraryFileLocationLength, noWhiteSpaceShowName, showLength + 2);
return ERROR(util_deleteDirectory(showPath, false, false));
}
inline ERROR_CODE medialibrary_getShow(MediaLibrary* library, Show** show, const char* name, const uint_fast64_t nameLength){
char* noneWhiteSpaceName = alloca(sizeof(*noneWhiteSpaceName) * (nameLength + 1));
strncpy(noneWhiteSpaceName, name, nameLength + 1);
return mediaLibrary_containsShow(&library->shows, show, noneWhiteSpaceName, nameLength);
}
inline ERROR_CODE medialibrary_initShow(Show* show, const char* name, const uint_fast64_t nameLength){
show->name = malloc(sizeof(*show->name) * (nameLength + 1));
if(show->name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
show->nameLength = nameLength;
strncpy(show->name, name, nameLength + 1);
linkedList_init(&show->seasons);
return ERROR_NO_ERROR;
}
inline ERROR_CODE mediaLibrary_containsShow(LinkedList* shows, Show** show, const char* name, const uint_fast64_t nameLength){
LinkedListIterator it;
linkedList_initIterator(&it, shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show_ = LINKED_LIST_ITERATOR_NEXT(&it);
if(show_->nameLength == nameLength && strncmp(name, show_->name, nameLength) == 0){
*show = show_;
return ERROR(ERROR_NO_ERROR);
}
}
*show = NULL;
return ERROR_(ERROR_ENTRY_NOT_FOUND, "Show: '%s'", name);
}
inline ERROR_CODE mediaLibrary_addSeason(MediaLibrary* library, Season** season, Show* show, const uint_fast16_t number){
ERROR_CODE error = ERROR_NO_ERROR;
*season = malloc(sizeof(**season));
if(*season == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
if((error = medialibrary_initSeason(*season, number)) != ERROR_NO_ERROR){
goto label_return;
}
if((error = linkedList_add(&show->seasons, *season)) != ERROR_NO_ERROR){
goto label_return;
}
label_return:
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE medialibrary_getSeason(Show* show, Season** season, const uint_fast16_t number){
LinkedListIterator it;
linkedList_initIterator(&it, &show->seasons);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Season* season_ = LINKED_LIST_ITERATOR_NEXT(&it);
if(season_->number == number){
*season = season_;
return ERROR(ERROR_NO_ERROR);
}
}
*season = NULL;
return ERROR(ERROR_ENTRY_NOT_FOUND);
}
inline ERROR_CODE medialibrary_initSeason(Season* season, const uint_fast16_t number){
ERROR_CODE error = ERROR_NO_ERROR;
memset(season, 0, sizeof(*season));
season->number = number;
error = linkedList_init(&season->episodes);
return ERROR(error);
}
ERROR_CODE mediaLibrary_addEpisode(MediaLibrary* library, Episode** episode, Show* show, Season* season, const uint_fast16_t number, const char* name, const uint_fast64_t nameLength, const char* fileExtension,const uint_fast16_t fileExtensionLength, const bool saveToDisk){
ERROR_CODE error = ERROR_NO_ERROR;
*episode = malloc(sizeof(**episode));
if(episode == NULL){
error = ERROR_OUT_OF_MEMORY;
goto label_return;
}
if((error = medialibrary_initEpisode(*episode, number, name, nameLength, fileExtension, fileExtensionLength)) != ERROR_NO_ERROR){
goto label_return;
}
if((error = linkedList_add(&season->episodes, *episode)) != ERROR_NO_ERROR){
goto label_return;
}
if(saveToDisk){
if((error = mediaLibrary_saveEpisodeToDisk(library, show, season, *episode)) != ERROR_NO_ERROR){
goto label_return;
}
UTIL_LOG_DEBUG_("Added Episode:%02" PRIuFAST16 " '%s' of Season:%02" PRIuFAST16 " to '%s'.", (*episode)->number, (*episode)->name, season->number, show->name);
}
label_return:
return ERROR(error);
}
ERROR_CODE mediaLibrary_saveEpisodeToDisk(MediaLibrary* library, Show* show, Season* season, Episode* episode){
FILE* file = library->libraryFile;
if(fseek(file, 0, SEEK_END) != 0){
return ERROR_(ERROR_DISK_ERROR, "%s", strerror(errno));
}
int_fast8_t writeBuffer[sizeof(uint64_t)];
// Show_Name.
util_uint64ToByteArray(writeBuffer, show->nameLength);
if(fwrite(writeBuffer, sizeof(uint64_t), 1, file) != 1){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write show name length to library file. '%s'.", strerror(errno));
}
if(fwrite(show->name, show->nameLength + 1, 1, file) != 1){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write show name length to library file. '%s'.", strerror(errno));
}
// Season_Number.
util_uint16ToByteArray(writeBuffer, season->number);
if(fwrite(writeBuffer, sizeof(uint16_t), 1, file) != 1){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write season number to library file. '%s'.", strerror(errno));
}
// Episode_Number.
util_uint16ToByteArray(writeBuffer, episode->number);
if(fwrite(writeBuffer, sizeof(uint16_t), 1, file) != 1){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write episode number to library file. '%s'.", strerror(errno));
}
// Episode_Name.
util_uint64ToByteArray(writeBuffer, episode->nameLength);
if(fwrite(writeBuffer, sizeof(uint64_t), 1, file) != 1){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write episode name length to library file. '%s'.", strerror(errno));
}
if(fwrite(episode->name, episode->nameLength + 1, 1, file) != 1){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write episode name to library file. '%s'.", strerror(errno));
}
// FileExtension
util_uint16ToByteArray(writeBuffer, episode->fileExtensionLength);
if(fwrite(writeBuffer, sizeof(uint16_t), 1, file) != 1){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write file extension length to library file. '%s'.", strerror(errno));
}
if(fwrite(episode->fileExtension, episode->fileExtensionLength + 1, 1, file) != 1){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write file extension to library file. '%s'.", strerror(errno));
}
if(fflush(file) != 0){
return ERROR_(ERROR_DISK_ERROR, "Failed to flush IO-Stream. '%s'.", strerror(errno));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_getEpisode(Season* season, Episode** episode, const uint_fast16_t number){
LinkedListIterator it;
linkedList_initIterator(&it, &season->episodes);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Episode* episode_ = LINKED_LIST_ITERATOR_NEXT(&it);
if(episode_->number == number){
*episode = episode_;
return ERROR(ERROR_NO_ERROR);
}
}
*episode = NULL;
return ERROR(ERROR_ENTRY_NOT_FOUND);
}
inline ERROR_CODE medialibrary_initEpisode(Episode* episode, const uint_fast16_t number, const char* name, const uint_fast64_t nameLength, const char* fileExtension, const uint_fast16_t fileExtensionLength){
ERROR_CODE error = ERROR_NO_ERROR;
episode->nameLength = nameLength;
episode->number = number;
episode->fileExtensionLength = fileExtensionLength;
episode->name = malloc(sizeof(*episode->name) * (nameLength + 1));
if(episode->name == NULL){
error = ERROR_OUT_OF_MEMORY;
goto label_return;
}
strncpy(episode->name, name, nameLength + 1);
episode->fileExtension = malloc(sizeof(*episode->fileExtension) * (fileExtensionLength + 1));
if(episode->fileExtension == NULL){
error = ERROR_OUT_OF_MEMORY;
goto label_return;
}
strncpy(episode->fileExtension, fileExtension, fileExtensionLength + 1);
label_return:
return ERROR(error);
}
inline ERROR_CODE mediaLibrary_initEpisodeInfo(EpisodeInfo* info){
memset(info, 0, sizeof(*info));
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_initEpisodeInfo_(EpisodeInfo* info, char* filePath, const uint_fast64_t filePathLength){
mediaLibrary_initEpisodeInfo(info);
info->name = malloc(sizeof(*info->name) * (filePathLength + 1));
if(info->name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(info->name, filePath, filePathLength + 1);
info->pathLength = filePathLength;
return ERROR(ERROR_NO_ERROR);
}
inline void mediaLibrary_fillEpisodeInfo(EpisodeInfo* info, Show* show, Season* season, Episode* episode){
info->showName = show->name;
info->showNameLength = show->nameLength;
info->season = season->number;
info->episode = episode->number;
info->name = episode->name;
info->nameLength = episode->nameLength;
info->fileExtension = episode->fileExtension;
info->fileExtensionLength = episode->fileExtensionLength;
}
inline void mediaLibrary_freeEpisodeInfo(EpisodeInfo* info){
free(info->showName);
free(info->name);
free(info->path);
}
inline ERROR_CODE mediaLibrary_readStringFromLibraryFile(FILE* file, char** s, uint_fast64_t length){
if(fread(*s, length + 1, 1, file) != 1){
return ERROR(ERROR_READ_ERROR);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_readShowNameLength(FILE* file, uint_fast64_t* showNameLength){
ERROR_CODE error;
MEDIA_LIBRARY_READ_FROM_LIBRARY_FILE(error, file, showNameLength, uint64_t);
if(error != ERROR_NO_ERROR){
if(feof(file) != 0){
return ERROR(ERROR_END_OF_FILE);
}else{
return ERROR_(error, "Failed to read show name length. [%s]", util_toErrorString(error));
}
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_readShowName(FILE* file, char** showName, uint_fast64_t showNameLength){
ERROR_CODE error;
if((error = mediaLibrary_readStringFromLibraryFile(file, showName, showNameLength)) != ERROR_NO_ERROR){
return ERROR_(error, "Failed to read show name. [%s]", util_toErrorString(error));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_readSeasonNumber(FILE* file, uint_fast16_t* seasonNumber){
ERROR_CODE error;
MEDIA_LIBRARY_READ_FROM_LIBRARY_FILE(error, file, seasonNumber, uint16_t);
if(error != ERROR_NO_ERROR){
return ERROR_(error, "Failed to read season number. [%s]", util_toErrorString(error));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_readEpisodeNumber(FILE* file, uint_fast16_t* episodeNumber){
ERROR_CODE error;
MEDIA_LIBRARY_READ_FROM_LIBRARY_FILE(error, file, episodeNumber, uint16_t);
if(error != ERROR_NO_ERROR){
return ERROR_(error, "Failed to read episode number. [%s]", util_toErrorString(error));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_readEpisodeNameLength(FILE* file, uint_fast64_t* episodeNameLength){
ERROR_CODE error;
MEDIA_LIBRARY_READ_FROM_LIBRARY_FILE(error, file, episodeNameLength, uint64_t);
if(error != ERROR_NO_ERROR){
return ERROR_(error, "Failed to read episode name length. [%s]", util_toErrorString(error));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_readEpisodeName(FILE* file, char** episodeName, uint_fast64_t episodeNameLength){
ERROR_CODE error;
if((error = mediaLibrary_readStringFromLibraryFile(file, episodeName, episodeNameLength)) != ERROR_NO_ERROR){
return ERROR_(error, "Failed to read episode name. [%s]", util_toErrorString(error));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_readFileExtensionLength(FILE* file, uint_fast16_t* fileExtensionLength){
ERROR_CODE error;
MEDIA_LIBRARY_READ_FROM_LIBRARY_FILE(error, file, fileExtensionLength, uint16_t);
if(error != ERROR_NO_ERROR){
return ERROR_(error, "Failed to read file extension length. [%s]", util_toErrorString(error));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE mediaLibrary_readFileExtension(FILE* file, char** fileExtension, uint_fast64_t fileExtensionLength){
ERROR_CODE error;
if((error = mediaLibrary_readStringFromLibraryFile(file, fileExtension, fileExtensionLength)) != ERROR_NO_ERROR){
return ERROR_(error, "Failed to read file extension. [%s]", util_toErrorString(error));
}
return ERROR(ERROR_NO_ERROR);
}
// TODO: Implement better/faster sorting algorithm. (jan - 2019.04.24)
ERROR_CODE mediaLibrary_sortSeasons(Season** sortedSeasons[], LinkedList* seasons){
Season** toBeSorted = *sortedSeasons;
LinkedListIterator it;
linkedList_initIterator(&it, seasons);
toBeSorted[0] = LINKED_LIST_ITERATOR_NEXT(&it);
register uint_fast64_t endIndex = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Season* current = LINKED_LIST_ITERATOR_NEXT(&it);
if(current->number >= toBeSorted[endIndex]->number){
// Add new largest element to end of list.
toBeSorted[endIndex + 1] = current;
}else{
// Search for place to insert new element.
register uint_fast64_t insertionIndex = 0;
while(current->number > toBeSorted[insertionIndex]->number){
insertionIndex++;
}
// Insert new element and move the rest up one place in the list.
Season* tmp = toBeSorted[insertionIndex];
toBeSorted[insertionIndex] = current;
for(insertionIndex += 1; insertionIndex <= endIndex; insertionIndex++){
Season* swap = toBeSorted[insertionIndex];
toBeSorted[insertionIndex] = tmp;
tmp = swap;
}
toBeSorted[insertionIndex] = tmp;
}
endIndex++;
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE mediaLibrary_sortEpisodes(Episode** sortedEpisodes[], LinkedList* episodes){
Episode** toBeSorted = *sortedEpisodes;
LinkedListIterator it;
linkedList_initIterator(&it, episodes);
toBeSorted[0] = LINKED_LIST_ITERATOR_NEXT(&it);
register uint_fast64_t endIndex = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Episode* current = LINKED_LIST_ITERATOR_NEXT(&it);
if(current->number >= toBeSorted[endIndex]->number){
// Add new largest element to end of list.
toBeSorted[endIndex + 1] = current;
}else{
// Search for place to insert new element.
register uint_fast64_t insertionIndex = 0;
while(current->number > toBeSorted[insertionIndex]->number){
insertionIndex++;
}
// Insert new element and move the rest up one place in the list.
Episode* tmp = toBeSorted[insertionIndex];
toBeSorted[insertionIndex] = current;
for(insertionIndex += 1; insertionIndex <= endIndex; insertionIndex++){
Episode* swap = toBeSorted[insertionIndex];
toBeSorted[insertionIndex] = tmp;
tmp = swap;
}
toBeSorted[insertionIndex] = tmp;
}
endIndex++;
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE mediaLibrary_renameEpisode(MediaLibrary* library, Show* show, Season* season, Episode* episode, char* newEpisodeName, const uint_fast64_t newEpisodeNameLength){
ERROR_CODE error;
// Remove old episdoe from disk.
if((error = medialibrary_removeEpisodeFrromLibraryFile(library, show, season, episode)) != ERROR_NO_ERROR){
goto label_return;
}
// Update in memory representation.
free(episode->name);
episode->name = malloc(sizeof(*episode->name * (newEpisodeNameLength + 1)));
if(episode->name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(episode->name, newEpisodeName, newEpisodeNameLength + 1);
episode->nameLength = newEpisodeNameLength;
// Readd entry with new name to library file on disk.
if((error = mediaLibrary_saveEpisodeToDisk(library, show, season, episode)) != ERROR_NO_ERROR){
goto label_return;
}
label_return:
return ERROR(error);
}
#undef PROPERTY_LIBRARY_DIRECTORY_NAME
#undef PROPERTY_IMPORT_DIRECTORY_NAME
#endif
|
Ex05/herder
|
src/threadPool.h
|
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <pthread.h>
#include <semaphore.h>
#include "util.h"
#include "que.h"
typedef struct{
pthread_t* threads;
uint_fast16_t numWorkers;
pthread_mutex_t lock;
sem_t numJobs;
sem_t alive;
Que jobQue;
}ThreadPool;
#define THREAD_POOL_RUNNABLE(functionName) void* functionName(void* data)
#define THREAD_POOL_RUNNABLE_(functionName, dataType, varName) void* functionName(dataType* varName)
typedef THREAD_POOL_RUNNABLE(Runnable);
typedef struct{
void* buffer;
void* data;
Runnable* runnable;
}Job;
ERROR_CODE threadPool_init(ThreadPool*, const uint_fast16_t);
void threadPool_free(ThreadPool*);
ERROR_CODE threadPool_run(ThreadPool*, Runnable*, void*);
#endif
|
Ex05/herder
|
src/util.h
|
<reponame>Ex05/herder
#ifndef UTIL_H
#define UTIL_H
// Use print MACROS for types like uint_fast64_t
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdint.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <syslog.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <endian.h>
#include <limits.h>
#include <time.h>
#include <pwd.h>
#include <fcntl.h>
#include <sys/param.h>
/* void foo(char arg[__require 10])
Require an array with atleast 10 elements.
*/
#define __require static
#define local static
#define localPersistent static
#define UTIL_FORMATTED_NUMBER_LENGTH 33
#define KB(x) ((x) << 10)
#define MB(x) ((x) << 20)
#define GB(x) ((x) << 30)
#define UTIL_MAX_ERROR_MSG_LENGTH 256
#define UTIL_FLAG(name, size) uint8_t name:size
// Note: These redefenition are needed for the 'read from library file' macros in mediaLibrary.c. And are an exception to the rule off the all caps macro style. (jan - 2019.05.17)
#define util_byteArrayTo_uint16_t util_byteArrayTo_uint16
#define util_byteArrayTo_uint32_t util_byteArrayTo_uint32
#define util_byteArrayTo_uint64_t util_byteArrayTo_uint64
typedef enum{
ERROR_NO_ERROR = 0,
ERROR_ERROR,
ERROR_OUT_OF_MEMORY,
ERROR_BUFFER_OVERFLOW,
ERROR_TO_MANY_ELEMENTS,
ERROR_FAILED_TO_UNMAP_MEMORY,
ERROR_INVALID_REQUEST_URL,
ERROR_PTHREAD_THREAD_CREATION_FAILED,
ERROR_PTHREAD_MUTEX_INITIALISATION_FAILED,
ERROR_PTHREAD_SEMAPHOR_INITIALISATION_FAILED,
ERROR_UNIX_DOMAIN_SOCKET_INITIALISATION_FAILED,
ERROR_FAILED_TO_BIND_SERVER_SOCKET,
ERROR_FAILED_TO_LISTEN_ON_SERVER_SOCKET,
ERROR_FAILED_TO_FORK_PROCESS,
ERROR_FAILED_TO_CREATE_NEW_SESSION,
ERROR_FAILED_TO_CHANGE_PROCESS_WORKING_DIRECTORY,
ERROR_FAILED_TO_LOCK_FILE,
ERROR_FAILED_TO_RETRIEVE_ADDRESS_INFORMATION,
ERROR_FAILED_TO_CONNECT,
ERROR_WRITE_ERROR,
ERROR_READ_ERROR,
ERROR_EMPTY_RESPONSE,
ERROR_INSUFICIENT_MESSAGE_LENGTH,
ERROR_INVALID_STATUS_CODE,
ERROR_VERSION_MISSMATCH,
ERROR_INVALID_HEADER_FIELD,
ERROR_MAX_HEADER_FIELDS_REACHED,
ERROR_INVALID_CONTENT_LENGTH,
ERROR_MAX_MESSAGE_SIZE_EXCEEDED,
ERROR_FAILED_TO_CLOSE_SOCKET,
ERROR_FAILED_TO_APPEMD_SIGNAL_HANDLER,
ERROR_HTTP_RESPONSE_SIZE_EXCEEDED,
ERROR_HTTP_REQUEST_SIZE_EXCEEDED,
ERROR_INCOMPLETE,
ERROR_FAILED_TO_CREATE_FILE,
ERROR_DUPLICATE_ENTRY,
ERROR_PROPERTY_NOT_SET,
ERROR_SERVER_ERROR,
ERROR_UNAVAILABLE,
ERROR_FAILED_TO_RETRIEV_FILE_INFO,
ERROR_FAILED_TO_LOAD_FILE,
ERROR_FAILED_TO_CLOSE_FILE,
ERROR_MISSING_DIRECTORY,
ERROR_REMOTE_PORT_PROPERTY_NO_SET,
ERROR_REMOTE_HOST_PROPERTY_NO_SET,
ERROR_INVALID_RETURN_CODE,
ERROR_DISK_ERROR,
ERROR_ENTRY_NOT_FOUND,
ERROR_LIBRARY_DIRECTORY_NOT_SET,
ERROR_FAILED_TO_CREATE_DIRECTORY,
ERROR_FAILED_TO_OPEN_FILE,
ERROR_M_PROTECT,
ERROR_MEMORY_ALLOCATION_ERROR,
ERROR_UNKNOWN_SHOW,
ERROR_ALREADY_EXIST,
ERROR_FAILED_TO_COPY_FILE,
ERROR_FAILED_TO_DELETEFILE,
ERROR_CONVERSION_ERROR,
ERROR_FAILED_TO_ADD_PROPERTY,
ERROR_FAILED_TO_REMOVE_PROPERTY,
ERROR_INVALID_COMMAND_USAGE,
ERROR_FAILED_TO_UPDATE_PROPERTY,
ERROR_INVALID_STRING,
ERROR_INVALID_VALUE,
ERROR_FUNCTION_NOT_IMPLEMENTED,
ERROR_FAILED_TO_OPEN_DIRECTORY,
ERROR_NAME_MISSMATCH,
ERROR_END_OF_FILE,
ERROR_FAILED_TO_DELETE_DIRECTORY,
ERROR_FAILED_TO_REMOVE_NODE,
ERROR_NO_VALID_ARGUMENT,
ERROR_INVALID_FILE_EXTENSION,
ERROR_FAILED_TO_RENAME_FILE,
}ERROR_CODE;
ERROR_CODE util_formatNumber(char*, uint_fast64_t*, const int_fast64_t);
const char* util_toErrorString(const ERROR_CODE);
#define ERROR_CALLBACK(functionName) void functionName(const int_fast32_t errorCode, const char* file, const int line, char* errorMessage)
typedef ERROR_CALLBACK(ErrorCallback);
typedef struct {
int_fast32_t errorType;
union{
struct{
UTIL_FLAG(supressNextError, 1);
UTIL_FLAG(supressAllErrors, 1);
UTIL_FLAG(supressNextErrorOfType, 1);
};
uint8_t flags;
};
}ERROR_Supressor;
ERROR_Supressor global_errorSupressionStruct = {0};
#define __UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(error) do{ \
global_errorSupressionStruct.supressNextErrorOfType = true; \
global_errorSupressionStruct.errorType = error; \
} while(0)
#define __UTIL_SUPRESS_NEXT_ERROR__(void) do{ \
global_errorSupressionStruct.supressNextError = true; \
}while(0)
#define __UTIL_DISABLE_ERROR_LOGGING__(void) do{ \
global_errorSupressionStruct.supressAllErrors = true; \
}while(0)
#define __UTIL_ENABLE_ERROR_LOGGING__(void) do{ \
global_errorSupressionStruct.supressAllErrors = false; \
}while(0)
#ifdef DEBUG
static ERROR_CALLBACK(globbal_errorCallback){
if(errorCode != ERROR_NO_ERROR && (
!global_errorSupressionStruct.supressAllErrors &&
!global_errorSupressionStruct.supressNextError && (
!global_errorSupressionStruct.supressNextErrorOfType &&
global_errorSupressionStruct.errorType != errorCode))){
util_toErrorString(errorCode);
syslog(LOG_ERR, "%s:%d %s [%" PRIdFAST32 "]%s%s.", file, line, util_toErrorString(errorCode), errorCode, errorMessage[0] == '\0' ? "" : " ", errorMessage);
}
global_errorSupressionStruct.supressNextErrorOfType = false;
global_errorSupressionStruct.supressNextError = false;
return;
}
static ErrorCallback* errorCallback_ = globbal_errorCallback;
#define GLOBAL_ERROR_CALLBACK errorCallback_
#endif
local ERROR_CODE util_error(const ERROR_CODE, const char*, const int, char*, ...);
inline ERROR_CODE util_error(const ERROR_CODE error, const char* file, const int line, char* format, ...){
#ifdef DEBUG
char* msg = alloca(sizeof(*msg) * UTIL_MAX_ERROR_MSG_LENGTH);
va_list args;
va_start(args, format);
vsnprintf(msg, UTIL_MAX_ERROR_MSG_LENGTH, format, args);
va_end(args);
GLOBAL_ERROR_CALLBACK(error, file, line, msg);
#endif
return error;
}
#define ERROR(error) util_error(error, __FILE__, __LINE__, "")
#define ERROR_(error, format, ...) util_error(error, __FILE__, __LINE__, format, __VA_ARGS__)
#define UTIL_LOG(level, formatString, ...) syslog(level, "%s:%d " formatString, __FILE__, __LINE__, __VA_ARGS__)
#define UTIL_LOG_CONSOLE_(level, formatString, ...) do{ \
UTIL_LOG(level, formatString, __VA_ARGS__); \
printf(formatString "\n", __VA_ARGS__); \
} while(0)
#define UTIL_LOG_CONSOLE(level, formatString) do{ \
UTIL_LOG(level, "%s", formatString); \
printf("%s\n", formatString); \
} while(0)
#define UTIL_LOG_NOTICE_(formatString, ...) UTIL_LOG(LOG_NOTICE, formatString, __VA_ARGS__)
#define UTIL_LOG_NOTICE(formatString) UTIL_LOG(LOG_NOTICE, "%s", formatString)
#define UTIL_LOG_INFO_(formatString, ...) UTIL_LOG(LOG_INFO, formatString, __VA_ARGS__)
#define UTIL_LOG_INFO(formatString) UTIL_LOG(LOG_INFO, "%s", formatString)
#define UTIL_LOG_ALERT_(formatString, ...) UTIL_LOG(LOG_ALERT, formatString, __VA_ARGS__)
#define UTIL_LOG_ALERT(formatString) UTIL_LOG(LOG_ALERT, "%s", formatString)
#define UTIL_LOG_CRITICAL_(formatString, ...) UTIL_LOG(LOG_CRIT, formatString, __VA_ARGS__)
#define UTIL_LOG_CRITICAL(formatString) UTIL_LOG(LOG_CRIT, "%s", formatString)
#define UTIL_LOG_WARNING_(formatString, ...) UTIL_LOG(LOG_WARNING, formatString, __VA_ARGS__)
#define UTIL_LOG_WARNING(formatString) UTIL_LOG(LOG_WARNING, "%s", formatString)
#define UTIL_LOG_DEBUG_(formatString, ...) UTIL_LOG(LOG_DEBUG, formatString, __VA_ARGS__)
#define UTIL_LOG_DEBUG(formatString) UTIL_LOG(LOG_DEBUG, "%s", formatString)
#define UTIL_LOG_ERROR_(formatString, ...) UTIL_LOG(LOG_ERR, formatString, __VA_ARGS__)
#define UTIL_LOG_ERROR(formatString) UTIL_LOG(LOG_ERR, "%s", formatString)
#define UTIL_ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0]))
#define UTIL_UINT16_STRING_LENGTH 5
#define UTIL_DIRECTORIES_ONLY 0
#define UTIL_FILES_ONLY 1
#include "linkedList.h"
int_fast32_t util_fileExists(const char*);
int_fast32_t util_directoryExists(const char*);
ERROR_CODE util_blockAlloc(void**, const uint_fast64_t);
ERROR_CODE util_unMap(void*, const uint_fast64_t);
ERROR_CODE util_concatenate(char*, const char*, const uint_fast64_t, const char*, const uint_fast64_t);
uint_fast16_t util_byteArrayTo_uint16(const int8_t*);
uint_fast32_t util_byteArrayTo_uint32(const int8_t*);
uint_fast64_t util_byteArrayTo_uint64(const int8_t*);
int8_t* util_uint16ToByteArray(int8_t*, const uint_fast16_t);
int8_t* util_uint32ToByteArray(int8_t*, const uint_fast32_t);
int8_t* util_uint64ToByteArray(int8_t*, const uint_fast64_t);
void util_toLowerChase(char*);
void util_stringCopy(char*, char*, uint_fast64_t);
int_fast64_t util_findFirst(const char*, const uint_fast64_t, const char);
int_fast64_t util_findFirst_s(const char*, const uint_fast64_t, const char*, const uint_fast64_t);
int_fast64_t util_findLast(const char*, const uint_fast64_t, const char);
ERROR_CODE util_fileCopy(const char*, const char*);
uint_fast32_t util_getFileSystemBlockSize(const char*);
ERROR_CODE util_deleteFile(const char*);
ERROR_CODE util_deleteDirectory(const char*, const bool, const bool);
void util_replaceAllChars(char*, const char, const char);
void util_append(char*, const uint_fast64_t, char*, const uint_fast64_t);
int util_hash(uint8_t*, uint_fast64_t);
int util_hashString(const char*, uint_fast64_t);
ERROR_CODE util_createDirectory(const char*);
ERROR_CODE util_createAllDirectories(const char*, const uint_fast64_t);
bool util_isDirectory(const char*);
bool util_startsWith(const char*, const char);
int_fast32_t util_getNumAvailableProcessorCores(void);
ERROR_CODE util_getBaseDirectory(char**, uint_fast64_t*, char*, uint_fast64_t);
ERROR_CODE util_replace(char*, const uint_fast64_t, uint_fast64_t*, const char*, const uint_fast64_t, const char*, const uint_fast64_t);
char* util_trim(char*, const uint_fast64_t);
void util_printBuffer(void*, uint_fast64_t);
char* util_getHomeDirectory(void);
char* util_getFileName(char*, const uint_fast64_t);
ERROR_CODE util_readUserInput(char**, int_fast64_t*);
ERROR_CODE util_stringToInt(const char*, int64_t*);
ERROR_CODE util_getCurrentWorkingDirectory(char*, const uint_fast64_t);
ERROR_CODE util_getFileExtension(char**, uint_fast64_t*, char*, const uint_fast64_t);
ERROR_CODE util_renameFile(char*, char*);
ERROR_CODE util_renameFileRelative(char*, char*, char*);
ERROR_CODE util_getFileDirectory(char*, char*, const uint_fast64_t);
ERROR_CODE util_walkDirectory(LinkedList*, const char*, bool);
#undef UTIL_MAX_ERROR_MSG_LENGTH
#endif
|
Ex05/herder
|
src/propertyFile.c
|
<reponame>Ex05/herder
#ifndef PROPERTY_FILE_C
#define PROPERTY_FILE_C
#include "propertyFile.h"
#include "linkedList.c"
#define PAGE_ENTRY_SIZE (sizeof(uint64_t) * 4)
local const Version VERSION = {1, 0, 0};
local ERROR_CODE propertyFile_initProperty(Property*, PropertyFileEntry*, PropertyFile*);
local ERROR_CODE propertyFile_addPropertyPage(PropertyFile*, PropertyPage**);
local ERROR_CODE propertyFile_initPropertyPage(PropertyPage*, const uint8_t, const uint_fast64_t);
ERROR_CODE propertyFile_init(PropertyFile* propertyFile, const char* fileName){
propertyFile->file = fopen(fileName, "r+");
if(propertyFile->file == NULL){
return ERROR(ERROR_FAILED_TO_OPEN_FILE);
}
ERROR_CODE error;
if((error = linkedList_init(&propertyFile->pages) != ERROR_NO_ERROR)){
return error;
}
FILE* file = propertyFile->file;
if(fread(&propertyFile->version, 1, sizeof(propertyFile->version), file) != sizeof(propertyFile->version)){
return ERROR_(ERROR_READ_ERROR, "Failed to read property file version. '%s'", fileName);
}
if(VERSION.release != propertyFile->version.release && VERSION.update == propertyFile->version.update && VERSION.hotfix == propertyFile->version.hotfix){
return ERROR_(ERROR_VERSION_MISSMATCH, "Version miss match [%" PRIu8 ".%" PRIu8 ".%" PRIu8 "].", propertyFile->version.release, propertyFile->version.update, propertyFile->version.hotfix);
}
if(fread(&propertyFile->maxPageEntries, 1, sizeof(propertyFile->maxPageEntries), file) != sizeof(propertyFile->maxPageEntries)){
return ERROR_(ERROR_READ_ERROR, "Failed to read Max_Page_Entries. '%s'.", fileName);
}
int8_t readBuffer[sizeof(uint64_t)];
for(;;){
PropertyPage* propertyPage = malloc(sizeof(*propertyPage));
if(propertyPage == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
propertyFile_initPropertyPage(propertyPage, propertyFile->maxPageEntries, ftell(file));
linkedList_add(&propertyFile->pages, propertyPage);
int i;
for(i = 0; i < propertyFile->maxPageEntries; i++){
PropertyFileEntry* entry = propertyPage->entries[i];
entry->entryOffset = ftell(file);
// Name_Size.
if(fread(readBuffer, 1, sizeof(uint64_t), file) != sizeof(uint64_t)){
return ERROR_(ERROR_READ_ERROR, "Failed to read Name_Size. '%s'", fileName);
}
entry->nameLength = util_byteArrayTo_uint64(readBuffer);
// Name_Offset.
if(fread(readBuffer, 1, sizeof(uint64_t), file) != sizeof(uint64_t)){
return ERROR_(ERROR_READ_ERROR, "Failed to read Name_Offset. '%s'", fileName);
}
entry->nameOffset = util_byteArrayTo_uint64(readBuffer);
// Data_Size.
if(fread(readBuffer, 1, sizeof(uint64_t), file) != sizeof(uint64_t)){
return ERROR_(ERROR_READ_ERROR, "Failed to read Data_Size. '%s'", fileName);
}
entry->length = util_byteArrayTo_uint64(readBuffer);
// Data_Offset.
if(fread(readBuffer, 1, sizeof(uint64_t), file) != sizeof(uint64_t)){
return ERROR_(ERROR_READ_ERROR, "Failed to read Data_Offset. '%s'", fileName);
}
entry->dataOffset = util_byteArrayTo_uint64(readBuffer);
if(entry->nameOffset != 0 && entry->nameLength != 0){
const uint_fast64_t fileOffset = ftell(file);
if(fseek(file, entry->nameOffset, SEEK_SET) != 0){
return ERROR_(ERROR_DISK_ERROR, "%s", strerror(errno));
}
entry->name = malloc(sizeof(*entry->name) * (entry->nameLength + 1));
if(entry->name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
entry->name[entry->nameLength] = '\0';
if(fread(entry->name, sizeof(*entry->name), entry->nameLength, file) != entry->nameLength){
return ERROR_(ERROR_READ_ERROR, "Failed to read entry name. '%s'", fileName);
}
if(fseek(file, fileOffset, SEEK_SET) != 0){
return ERROR_(ERROR_DISK_ERROR, "%s", strerror(errno));
}
}else{
entry->name = NULL;
}
propertyPage->entries[i] = entry;
}
if(fread(readBuffer, 1, sizeof(uint64_t), file) != sizeof(uint64_t)){
return ERROR_(ERROR_READ_ERROR, "Failed to read next page offset. '%s'", fileName);
}
const uint_fast64_t nextPageOffset = util_byteArrayTo_uint64(readBuffer);
if(nextPageOffset == 0){
break;
}
if(fseek(file, nextPageOffset, SEEK_SET) == -1){
return ERROR_(ERROR_DISK_ERROR, "Failed to seek to the next page ffset. [%" PRIdFAST64 "] '%s'.", nextPageOffset, fileName);
}
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE propertyFile_create(const char* fileName, const uint8_t numPageEntries){
FILE* file = fopen(fileName, "a");
if(file == NULL){
return ERROR_(ERROR_FAILED_TO_CREATE_FILE, " %s '%s'", strerror(errno), fileName);
}
// Current code/PropertyFile version.
uint8_t buffer[PAGE_ENTRY_SIZE] = {0};
buffer[0] = VERSION.release;
buffer[1] = VERSION.update;
buffer[2] = VERSION.hotfix;
if(fwrite(buffer, 1, sizeof(Version), file) != sizeof(Version)){
return ERROR_(ERROR_WRITE_ERROR, "%s.", strerror(errno));
}
memset(buffer, 0, sizeof(Version));
// Max_Page_Entries.
buffer[0] = numPageEntries;
if(fwrite(buffer, 1, sizeof(numPageEntries), file) != sizeof(numPageEntries)){
return ERROR_(ERROR_WRITE_ERROR, "%s.", strerror(errno));
}
buffer[0] = 0;
// Empty page entries.
uint8_t i;
for(i = 0; i < numPageEntries; i++){
if(fwrite(buffer, 1, PAGE_ENTRY_SIZE, file) != PAGE_ENTRY_SIZE){
return ERROR_(ERROR_WRITE_ERROR, "%s.", strerror(errno));
}
}
// Next_Page.
if(fwrite(buffer, 1, sizeof(uint64_t), file) != sizeof(uint64_t)){
return ERROR_(ERROR_WRITE_ERROR, "%s.", strerror(errno));
}
if(fflush(file) != 0){
return ERROR(ERROR_DISK_ERROR);
}
if(fclose(file) != 0){
return ERROR(ERROR_DISK_ERROR);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE propertyFile_getProperty(PropertyFile* propertyFile, Property** property, const char* name){
LinkedListIterator it;
linkedList_initIterator(&it, &propertyFile->pages);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
PropertyPage* propertyPage = LINKED_LIST_ITERATOR_NEXT(&it);
uint_fast8_t i;
for(i = 0; i < propertyFile->maxPageEntries; i++){
PropertyFileEntry* entry = propertyPage->entries[i];
if(entry->name != NULL && strncmp(entry->name, name, entry->nameLength) == 0){
Property* _property = malloc(sizeof(*_property));
if(_property == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
propertyFile_initProperty(_property, entry, propertyFile);
*property = _property;
return ERROR(ERROR_NO_ERROR);
}
}
}
*property = NULL;
return ERROR_(ERROR_ENTRY_NOT_FOUND, "Entry: '%s'", name);
}
inline ERROR_CODE propertyFile_initProperty(Property* property, PropertyFileEntry* entry, PropertyFile* propertyFile){
property->entry = entry;
property->callBack = propertyFile;
property->buffer = malloc(sizeof(*property->buffer) * entry->length);
if(property->buffer == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
if(fseek(propertyFile->file, entry->dataOffset, SEEK_SET) != 0){
return ERROR_(ERROR_DISK_ERROR, "%s", strerror(errno));
}
if(fread(property->buffer, 1, entry->length, propertyFile->file) != entry->length){
return ERROR_(ERROR_DISK_ERROR, "Failed to read property data. '%s'.", strerror(errno));
}
return ERROR(ERROR_NO_ERROR);
}
inline void propertyFile_free(PropertyFile* propertyFile){
fclose(propertyFile->file);
LinkedListIterator it;
linkedList_initIterator(&it, &propertyFile->pages);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
PropertyPage* propertyPage = LINKED_LIST_ITERATOR_NEXT(&it);
uint_fast8_t i;
for(i = 0; i < propertyFile->maxPageEntries; i++){
PropertyFileEntry* entry = propertyPage->entries[i];
free(entry->name);
free(entry);
}
free(propertyPage->entries);
free(propertyPage);
}
linkedList_free(&propertyFile->pages);
}
inline bool propertyFile_contains(PropertyFile* propertyFile, const char* name){
LinkedListIterator it;
linkedList_initIterator(&it, &propertyFile->pages);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
PropertyPage* propertyPage = LINKED_LIST_ITERATOR_NEXT(&it);
uint_fast8_t i;
for(i = 0; i < propertyFile->maxPageEntries; i++){
PropertyFileEntry* entry = propertyPage->entries[i];
if(entry->name != NULL && strncmp(entry->name, name, entry->nameLength) == 0){
return true;
}
}
}
return false;
}
ERROR_CODE propertyFile_addProperty(PropertyFile* propertyFile, Property** property, const char* name, const uint_fast64_t size){
*property = NULL;
if(propertyFile_contains(propertyFile, name)){
return ERROR(ERROR_DUPLICATE_ENTRY);
}
PropertyFileEntry* entry = NULL;
LinkedListIterator it;
linkedList_initIterator(&it, &propertyFile->pages);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
PropertyPage* propertyPage = LINKED_LIST_ITERATOR_NEXT(&it);
int i;
for(i = 0; i < propertyFile->maxPageEntries; i++){
PropertyFileEntry* _entry = propertyPage->entries[i];
if(_entry->name == NULL && _entry->entryOffset != 0){
entry = _entry;
goto label_entryFound;
}
}
}
if(entry == NULL){
ERROR_CODE error;
PropertyPage* propertyPage;
if((error = propertyFile_addPropertyPage(propertyFile, &propertyPage)) != ERROR_NO_ERROR){
return ERROR(error);
}
entry = propertyPage->entries[0];
}
label_entryFound:
entry->length = size;
entry->nameLength = strlen(name);
entry->name = malloc(sizeof(*entry->name) * (entry->nameLength + 1));
if(entry->name == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(entry->name, name, sizeof(*entry->name) * (entry->nameLength + 1));
if(fseek(propertyFile->file, 0, SEEK_END) != 0){
return ERROR_(ERROR_DISK_ERROR, "%s", strerror(errno));
}
entry->nameOffset = ftell(propertyFile->file);
if(fwrite(entry->name, sizeof(*entry->name), entry->nameLength, propertyFile->file) != entry->nameLength){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write entry name '%s' to propertyFile", name);
}
uint8_t* voidBuffer = alloca(entry->length);
memset(voidBuffer, 0, entry->length);
entry->dataOffset = ftell(propertyFile->file);
if(fwrite(voidBuffer, 1, entry->length, propertyFile->file) != entry->length){
UTIL_LOG_ERROR("Failed to write empty propertyData.");
return ERROR(ERROR_WRITE_ERROR);
}
// Update entry on disk.
if(fseek(propertyFile->file, entry->entryOffset, SEEK_SET) != 0){
return ERROR_(ERROR_DISK_ERROR, "Failed to write propertyData of proeprty '%s' to disk.", name);
}
int8_t writeBuffer[sizeof(uint64_t)];
// Name_Size.
util_uint64ToByteArray(writeBuffer, entry->nameLength);
if(fwrite(writeBuffer, 1, sizeof(entry->nameLength), propertyFile->file) != sizeof(entry->nameLength)){
UTIL_LOG_ERROR("");
return ERROR_(ERROR_WRITE_ERROR, "Failed to write entry name size of property '%s' to propertyFile.", name);
}
// Name_Offset.
util_uint64ToByteArray(writeBuffer, entry->nameOffset);
if(fwrite(writeBuffer, 1, sizeof(entry->nameOffset), propertyFile->file) != sizeof(entry->nameOffset)){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write entry name offset of '%s' to propertyFile.", name);
}
// Data_Size.
util_uint64ToByteArray(writeBuffer, entry->length);
if(fwrite(writeBuffer, 1, sizeof(entry->length), propertyFile->file) != sizeof(entry->length)){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write entry size of property '%s' to propertyFile.", name);
}
// Data_Offset.
util_uint64ToByteArray(writeBuffer, entry->dataOffset);
if(fwrite(writeBuffer, 1, sizeof(entry->dataOffset), propertyFile->file) != sizeof(entry->dataOffset)){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write entry data offset of property '%s' to propertyFile.", name);
}
*property = malloc(sizeof(**property));
if(*property == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
propertyFile_initProperty(*property, entry, propertyFile);
return ERROR(ERROR_NO_ERROR);
}
inline void propertyFile_freeProperty(Property* property){
free(property->buffer);
}
inline ERROR_CODE propertyFile_setBuffer(Property* property, int8_t* buffer){
const uint_fast64_t bufferSize = property->entry->length;
memcpy(property->buffer, buffer, bufferSize);
FILE* file = property->callBack->file;
if(fseek(file, property->entry->dataOffset, SEEK_SET) != 0){
return ERROR(ERROR_DISK_ERROR);
}
if(fwrite(property->buffer, 1, bufferSize, file) != bufferSize){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write property data to file. '%s'.", strerror(errno));
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE propertyFile_addPropertyPage(PropertyFile* propertyFile, PropertyPage** propertyPage){
FILE* file = propertyFile->file;
LinkedListIterator it;
linkedList_initIterator(&it, &propertyFile->pages);
uint_fast64_t prevPageOffset;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Node* node = linkedList_iteratorNextNode(&it);
if(node->next == NULL){
prevPageOffset = ((PropertyPage*) node)->offset;
}
}
*propertyPage = malloc(sizeof(**propertyPage));
if(*propertyPage == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
propertyFile_initPropertyPage(*propertyPage, propertyFile->maxPageEntries, ftell(file));
int8_t* writeBuffer = alloca(PAGE_ENTRY_SIZE);
memset(writeBuffer, 0 , PAGE_ENTRY_SIZE);
uint_fast8_t i;
for(i = 0; i < propertyFile->maxPageEntries; i++){
(*propertyPage)->entries[i]->entryOffset = ftell(file);
if(fwrite(writeBuffer, 1, PAGE_ENTRY_SIZE, file) != PAGE_ENTRY_SIZE){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write empty property entry to file. '%s'", strerror(errno));
}
}
if(fwrite(writeBuffer, 1, sizeof(uint64_t), file) != sizeof(uint64_t)){
return ERROR_(ERROR_WRITE_ERROR, "Failed to write propertyPage offset to file. '%s'.", strerror(errno));
}
ERROR_CODE error;
if((error = linkedList_add(&propertyFile->pages, *propertyPage)) != ERROR_NO_ERROR){
return ERROR(error);
}
if(fseek(file, prevPageOffset + (PAGE_ENTRY_SIZE * propertyFile->maxPageEntries), SEEK_SET) != 0){
return ERROR_(ERROR_DISK_ERROR, "%s", strerror(errno));
}
util_uint64ToByteArray(writeBuffer, (*propertyPage)->offset);
if(fwrite(writeBuffer, 1, sizeof(uint64_t), file) != sizeof(uint64_t)){
return ERROR_(ERROR_WRITE_ERROR, "Failed to update previous propertyPage offset. '%s'.", strerror(errno));
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE propertyFile_initPropertyPage(PropertyPage* propertyPage, const uint8_t maxPageEntries, const uint_fast64_t pageOffset){
propertyPage->entries = malloc(sizeof(*propertyPage->entries) * maxPageEntries);
if(propertyPage->entries == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
propertyPage->offset = pageOffset;
uint_fast8_t i;
for(i = 0; i < maxPageEntries; i++){
propertyPage->entries[i] = malloc(sizeof(PropertyFileEntry));
if(propertyPage->entries[i] == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
}
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE propertyFile_removeProperty(Property* property){
FILE* file = property->callBack->file;
LinkedListIterator it;
linkedList_initIterator(&it, &property->callBack->pages);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
PropertyPage* propertyPage = LINKED_LIST_ITERATOR_NEXT(&it);
int i;
for(i = 0; i < property->callBack->maxPageEntries; i++){
PropertyFileEntry* entry = propertyPage->entries[i];
if(entry->name != NULL && strncmp(entry->name, property->entry->name, property->entry->nameLength) == 0){
int8_t* writeBuffer = alloca(property->entry->length);
memset(writeBuffer, 0, property->entry->length);
// Clear data on disk.
if(fseek(file, property->entry->dataOffset, SEEK_SET) != 0){
return ERROR_(ERROR_WRITE_ERROR, "Failed to move file pointer to property data on disk. '%s'.", strerror(errno));
}
if(fwrite(writeBuffer, 1, property->entry->length, file) != property->entry->length){
return ERROR_(ERROR_WRITE_ERROR, "Failed to erase property data on disk. '%s'.", strerror(errno));
}
// Clear entry name on disk.
if(property->entry->nameLength > property->entry->length){
writeBuffer = alloca(property->entry->nameLength);
memset(writeBuffer, 0, property->entry->nameLength);
}
if(fseek(file, property->entry->nameOffset, SEEK_SET) != 0){
return ERROR_(ERROR_DISK_ERROR, "%s", strerror(errno));
}
if(fwrite(writeBuffer, 1, property->entry->nameLength, file) != property->entry->nameLength){
return ERROR_(ERROR_WRITE_ERROR, "Failed to erase property name on disk. '%s'.", strerror(errno));
}
// Clear entry on disk.
if(PAGE_ENTRY_SIZE > property->entry->length && PAGE_ENTRY_SIZE > property->entry->nameLength){
writeBuffer = alloca(PAGE_ENTRY_SIZE);
memset(writeBuffer, 0, PAGE_ENTRY_SIZE);
}
if(fseek(file, property->entry->entryOffset, SEEK_SET) != 0){
return ERROR_(ERROR_DISK_ERROR, "%s", strerror(errno));
}
if(fwrite(writeBuffer, 1, PAGE_ENTRY_SIZE, file) != PAGE_ENTRY_SIZE){
return ERROR_(ERROR_WRITE_ERROR, "Failed to clear property entry on disk. '%s'.", strerror(errno));
}
free(property->entry->name);
// Clear entry that is referenced in the propertyPage.
memset(property->entry, 0, sizeof(*property->entry));
return ERROR(ERROR_NO_ERROR);
}
}
}
return ERROR(ERROR_NO_ERROR);
}
#undef PAGE_ENTRY_SIZE
inline ERROR_CODE propertyFile_propertySet(Property* property, const char* propertyName){
if(PROPERTY_IS_NOT_SET(property)){
UTIL_LOG_CONSOLE_(LOG_ERR, "ERROR: Property \"%s\" not set.", propertyName);
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_PROPERTY_NOT_SET);
return ERROR(ERROR_PROPERTY_NOT_SET);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE propertyFile_createAndSetDirectoryProperty(PropertyFile* properties, Property** property, const char* propertyName, const char* value, const uint_fast64_t valueLength){
// Note: Make sure 'slashTerminated' is clamped to '0 - 1' so we can use it later to add/subtract depending on whether the string was slash termianted or not. (jan - 2018.10.20)
const bool slashTerminated = (value[valueLength - 1] == '/') & 0x01;
const uint_fast64_t propertyStringLength = valueLength + !slashTerminated;
char* propertyString;
if(slashTerminated){
propertyString = alloca(sizeof(*propertyString) * (valueLength + 1));
memmove(propertyString, value, valueLength + 1);
}else{
propertyString = alloca(sizeof(*propertyString) * (propertyStringLength + 1));
memcpy(propertyString, value, valueLength);
propertyString[propertyStringLength - 1] = '/';
propertyString[propertyStringLength] = '\0';
}
return ERROR(propertyFile_createAndSetStringProperty(properties, property, propertyName, propertyString, propertyStringLength));
}
inline ERROR_CODE propertyFile_createAndSetStringProperty(PropertyFile* properties, Property** property, const char* propertyName, const char* value, const uint_fast64_t valueLength){
ERROR_CODE error;
if((error = propertyFile_createProperty(properties, property, propertyName, sizeof(*value) * (valueLength + 1))) != ERROR_NO_ERROR){
return ERROR(error);
}
if(propertyFile_setBuffer(*property, (int8_t*) value) != ERROR_NO_ERROR){
return ERROR_(ERROR_FAILED_TO_UPDATE_PROPERTY, "'%s'", propertyName);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE propertyFile_createAndSetUINT16Property(PropertyFile* properties, Property** property, const char* propertyName, const uint16_t value){
ERROR_CODE error;
if((error = propertyFile_createProperty(properties, property, propertyName, sizeof(value))) != ERROR_NO_ERROR){
return ERROR(error);
}
int8_t* buffer = alloca(sizeof(value));
util_uint16ToByteArray(buffer, value);
if(propertyFile_setBuffer(*property, buffer) != ERROR_NO_ERROR){
return ERROR_(ERROR_FAILED_TO_UPDATE_PROPERTY, "'%s'", propertyName);
}
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE propertyFile_createProperty(PropertyFile* properties, Property** property, const char* propertyName, const uint_fast64_t size){
if(PROPERTY_IS_NOT_SET(*property)){
if(propertyFile_addProperty(properties, property, propertyName, size) != ERROR_NO_ERROR){
return ERROR_(ERROR_FAILED_TO_ADD_PROPERTY, "'%s'", propertyName);
}
}else{
if((*property)->entry->length != size){
if(propertyFile_removeProperty(*property) != ERROR_NO_ERROR){
return ERROR_(ERROR_FAILED_TO_REMOVE_PROPERTY, "'%s'", propertyName);
}
propertyFile_freeProperty(*property);
free(*property);
if(propertyFile_addProperty(properties, property, propertyName, size) != ERROR_NO_ERROR){
return ERROR_(ERROR_FAILED_TO_ADD_PROPERTY, "'%s'", propertyName);
}
}
}
return ERROR(ERROR_NO_ERROR);
}
#endif
|
Ex05/herder
|
src/server.h
|
<reponame>Ex05/herder
#ifndef SERVER_H
#define SERVER_H
#include "util.h"
#include "threadPool.h"
#include "http.h"
#include "linkedList.h"
#include "mediaLibrary.h"
#include "cache.h"
#include <sys/un.h>
#include <netinet/in.h>
#include <sys/inotify.h>
typedef struct {
int sockFD;
struct sockaddr_in sockAddr;
uint_fast16_t port;
ThreadPool threadPool;
volatile bool alive;
LinkedList contexts;
MediaLibrary library;
Cache cache;
char* rootDirectory;
uint_fast64_t rootDirectoryLength;
}HerderServer;
typedef struct{
int sockFD;
struct sockaddr_in socket;
HerderServer* server;
}Client;
#define SERVER_CONTEXT_HANDLER(functionName) ERROR_CODE functionName(HerderServer* server, HTTP_Request* request, HTTP_Response* response)
typedef SERVER_CONTEXT_HANDLER(ContextHandler);
typedef struct{
char* location;
uint_fast64_t locationLength;
ContextHandler* contextHandler;
}Context;
ERROR_CODE server_init(HerderServer*, const char*, const uint_fast64_t, uint_fast16_t);
ERROR_CODE server_start(HerderServer*);
ERROR_CODE server_stop(HerderServer*);
void server_free(HerderServer*);
ERROR_CODE server_addContext(HerderServer*, const char*, ContextHandler*);
ERROR_CODE server_getContext(HerderServer*, ContextHandler**, HTTP_Request*);
ERROR_CODE server_constructErrorPage(HerderServer*,HTTP_Request*, HTTP_Response*, HTTP_StatusCode);
ERROR_CODE server_defaultContextHandler(HerderServer*, HTTP_Request*, HTTP_Response*);
#endif
|
Ex05/herder
|
src/server.c
|
#ifndef SERVER_C
#define SERVER_C
// POSIX Version ¢2008
#define _XOPEN_SOURCE 700
// For mmap flags that are not in the POSIX-Standard.
#define _GNU_SOURCE
#include "server.h"
#include "que.c"
#include "threadPool.c"
#include "http.c"
#include "mediaLibrary.c"
#include "cache.c"
#include "propertyFile.c"
#include "argumentParser.c"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SERVER_DAEMON_NAME "herderServerDaemon"
#define SERVER_WEB_DIRECTORY "www/"
#define SERVER_USAGE_ARGUMENT_HELP "-?, -h, --help"
#define SERVER_USAGE_ARGUMENT_SET_SERVER_ROOT_DIRECTORY "--setServerRootDirectory <path>"
#define SERVER_USAGE_ARGUMENT_SET_SERVER_EXTERNAL_PORT "--setServerExternalPort <port>"
#define SERVER_USAGE_ARGUMENT_SHOW_SETTINGS "--showSettings <path>"
#define PROPERTY_FILE_NAME "server_settings"
#define SERVER_PROPERTY_SERVER_ROOT_DIRECTORY_NAME "serverRootDirectory"
#define PROPERTY_SERVER_EXTERNAL_PORT_NAME "serverExternalPort"
local void server_initClient(Client*, HerderServer*);
local ERROR_CODE server_initContext(Context*, const char*, const uint_fast64_t, ContextHandler*);
local void server_freeContext(Context*);
local ERROR_CODE server_getFile(HerderServer*, CacheObject**, char*, const uint_fast64_t);
local void server_daemonize(const char* workingDirectory);
local void server_inotifyEventHandler(HerderServer*, struct inotify_event*);
local void server_inotifyEventHandlerDirectoryCreated(HerderServer*, struct inotify_event*);
local void server_inotifyEventHandlerDirectoryDeleted(HerderServer*, struct inotify_event*);
local void server_inotifyEventHandlerFileCreated(HerderServer*, struct inotify_event*);
local void server_inotifyEventHandlerFileDeleted(HerderServer*, struct inotify_event*);
local void server_inotifyEventHandlerFileModified(HerderServer*, struct inotify_event*);
local HerderServer server;
local int watchDescriptor;
local LinkedList watches;
typedef struct{
char* directory;
uint_fast64_t directoryNameLength;
int id;
}INOTIFY_Watch;
local void server_iniInotifyWatch(INOTIFY_Watch*, char*, const uint_fast64_t);
local void server_iniInotifyWatch(INOTIFY_Watch* watch, char* directoryName, const uint_fast64_t directoryNameLength){
watch->directory = directoryName;
watch->directoryNameLength = directoryNameLength;
}
THREAD_POOL_RUNNABLE_(server_inotifyWatch, Job, job){
HerderServer* server = job->data;
char buffer[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
if((watchDescriptor = inotify_init()) == -1){
UTIL_LOG_ERROR_("Failed to initialise 'inotify'. [%s]", strerror(errno));
return NULL;
}
if(linkedList_init(&watches) != ERROR_NO_ERROR){
return NULL;
}
char* rootDirectory = malloc(sizeof(*rootDirectory) * server->rootDirectoryLength + 1);
if(rootDirectory == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return NULL;
}
memcpy(rootDirectory, server->rootDirectory, server->rootDirectoryLength + 1);
INOTIFY_Watch* watch = malloc(sizeof(*watch));
if(watch == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return NULL;
}
server_iniInotifyWatch(watch, rootDirectory, server->rootDirectoryLength);
if((watch->id = inotify_add_watch(watchDescriptor, rootDirectory, IN_CREATE | IN_DELETE | IN_DELETE_SELF| IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO | IN_MODIFY)) == -1){
UTIL_LOG_ERROR_("Failed to add watch to directory '%s'. [%s]", rootDirectory, strerror(errno));
return NULL;
}
if(linkedList_add(&watches, watch) != ERROR_NO_ERROR){
return NULL;
}
LinkedList directories;
linkedList_init(&directories);
if(util_walkDirectory(&directories, rootDirectory, UTIL_DIRECTORIES_ONLY) != ERROR_NO_ERROR){
return NULL;
}
LinkedListIterator directoryIterator;
linkedList_initIterator(&directoryIterator, &directories);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&directoryIterator)){
char* directory = LINKED_LIST_ITERATOR_NEXT(&directoryIterator);
INOTIFY_Watch* watch = malloc(sizeof(*watch));
if(watch == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return NULL;
}
server_iniInotifyWatch(watch, directory, strlen(directory));
if((watch->id = inotify_add_watch(watchDescriptor, directory, IN_CREATE | IN_DELETE | IN_DELETE_SELF| IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO)) == -1){
UTIL_LOG_ERROR_("Failed to add watch to directory '%s'. [%s]", directory, strerror(errno));
return NULL;
}
if(linkedList_add(&watches, watch) != ERROR_NO_ERROR){
return NULL;
}
}
linkedList_free(&directories);
// Event loop.
while(true){
const ssize_t length = read(watchDescriptor, buffer, sizeof(buffer));
if(length == -1 && errno != EAGAIN){
UTIL_LOG_ERROR_("Failed to read from 'inotify' event buffer for '%s'. [%s]","/tmp", strerror(errno));
return NULL;
}else if(length == 0){
break;
}
char* eventPointer = buffer;
while(eventPointer < buffer + length){
struct inotify_event * event = (struct inotify_event *) eventPointer;
if(event->len > 0){
server_inotifyEventHandler(server, event);
}
eventPointer += sizeof(*event) + event->len;
}
}
close(watchDescriptor);
LinkedListIterator watchIterator;
linkedList_initIterator(&watchIterator, &watches);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&watchIterator)){
INOTIFY_Watch* watch = LINKED_LIST_ITERATOR_NEXT(&watchIterator);
inotify_rm_watch(watchDescriptor, watch->id);
free(watch->directory);
free(watch);
}
return NULL;
}
local void server_inotifyEventHandler(HerderServer* server, struct inotify_event* event){
if(event->mask & IN_ISDIR){
if(event->mask & IN_CREATE){
server_inotifyEventHandlerDirectoryCreated(server, event);
}else if(event->mask & IN_DELETE){
server_inotifyEventHandlerDirectoryDeleted(server, event);
}
}else if(event->mask & IN_CREATE){
server_inotifyEventHandlerFileCreated(server, event);
}else if(event->mask & IN_MODIFY){
server_inotifyEventHandlerFileModified(server, event);
}else if(event->mask & IN_DELETE){
server_inotifyEventHandlerFileDeleted(server, event);
}
}
local void server_inotifyEventHandlerDirectoryCreated(HerderServer* server, struct inotify_event* event){
LinkedListIterator watchIterator;
linkedList_initIterator(&watchIterator, &watches);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&watchIterator)){
INOTIFY_Watch* watch = LINKED_LIST_ITERATOR_NEXT(&watchIterator);
if(watch->id == event->wd){
const uint_fast64_t sourceDirectoryLength = watch->directoryNameLength;
const uint_fast64_t eventNameLength = strlen(event->name);
const uint_fast64_t directoryLength = sourceDirectoryLength + eventNameLength + 1/*'/'*/;
char* dir = malloc(sizeof(dir) * (directoryLength + 1));
if(dir == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
}
memcpy(dir, watch->directory, sourceDirectoryLength);
memcpy(dir + sourceDirectoryLength, event->name, eventNameLength);
dir[directoryLength - 1] = '/';
dir[directoryLength] = '\0';
INOTIFY_Watch* watch = malloc(sizeof(*watch));
if(watch == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return;
}
watch->directory = dir;
watch->directoryNameLength = directoryLength;
if((watch->id = inotify_add_watch(watchDescriptor, watch->directory, IN_CREATE | IN_DELETE | IN_DELETE_SELF| IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO)) == -1){
UTIL_LOG_ERROR_("Failed to add watch to directory '%s'. [%s]", watch->directory, strerror(errno));
return;
}
if(linkedList_add(&watches, watch) != ERROR_NO_ERROR){
return;
}
}
}
}
void server_inotifyEventHandlerDirectoryDeleted(HerderServer* server, struct inotify_event* event){
LinkedListIterator watchIterator;
linkedList_initIterator(&watchIterator, &watches);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&watchIterator)){
INOTIFY_Watch* watch = LINKED_LIST_ITERATOR_NEXT(&watchIterator);
if(watch->id == event->wd){
const uint_fast64_t eventNameLength = strlen(event->name);
const uint_fast64_t directoryLength = watch->directoryNameLength + eventNameLength + 1;
char* directory = alloca(sizeof(*directory) * (directoryLength + 1));
memcpy(directory, watch->directory, watch->directoryNameLength);
memcpy(directory + watch->directoryNameLength ,event->name, eventNameLength);
directory[directoryLength - 1] = '/';
directory[directoryLength] = '\0';
linkedList_initIterator(&watchIterator, &watches);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&watchIterator)){
INOTIFY_Watch* _watch = LINKED_LIST_ITERATOR_NEXT(&watchIterator);
if(strncmp(directory, _watch->directory, directoryLength + 1) == 0){
if(inotify_rm_watch(watchDescriptor, _watch->id) != 0){
UTIL_LOG_ERROR(strerror(errno));
return;
}
if(linkedList_remove(&watches, _watch) != ERROR_NO_ERROR){
return;
}
free(_watch->directory);
free(_watch);
break;
}
}
break;
}
}
}
void server_inotifyEventHandlerFileCreated(HerderServer* server, struct inotify_event* event){
LinkedListIterator watchIterator;
linkedList_initIterator(&watchIterator, &watches);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&watchIterator)){
INOTIFY_Watch* watch = LINKED_LIST_ITERATOR_NEXT(&watchIterator);
if(watch->id == event->wd){
const uint_fast64_t eventNameLength = strlen(event->name);
const uint_fast64_t baseDirectoryLength = watch->directoryNameLength - (server->rootDirectoryLength - 1/*Keep the leading '/'.*/);
const uint_fast64_t symbolicFileLocationLength = baseDirectoryLength + eventNameLength;
char* symbolicFileLocation = alloca(sizeof(*symbolicFileLocation) * symbolicFileLocationLength + 1);
if(symbolicFileLocation == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return;
}
memcpy(symbolicFileLocation, watch->directory + (server->rootDirectoryLength - 1), baseDirectoryLength);
memcpy(symbolicFileLocation + baseDirectoryLength, event->name, eventNameLength);
symbolicFileLocation[symbolicFileLocationLength] = '\0';
const uint_fast64_t fileLocationLength = (server->rootDirectoryLength - 1) + symbolicFileLocationLength;
char* fileLocation = malloc(sizeof(*fileLocation) * (fileLocationLength + 1));
if(fileLocation == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return;
}
memcpy(fileLocation, server->rootDirectory,(server->rootDirectoryLength - 1));
memcpy(fileLocation + (server->rootDirectoryLength - 1), symbolicFileLocation, symbolicFileLocationLength);
fileLocation[fileLocationLength] = '\0';
CacheObject* cacheObject;
if(cache_load(&server->cache, &cacheObject, fileLocation, fileLocationLength, symbolicFileLocation, symbolicFileLocationLength) != ERROR_NO_ERROR){
return;
}
break;
}
}
}
void server_inotifyEventHandlerFileModified(HerderServer* server, struct inotify_event* event){
LinkedListIterator watchIterator;
linkedList_initIterator(&watchIterator, &watches);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&watchIterator)){
INOTIFY_Watch* watch = LINKED_LIST_ITERATOR_NEXT(&watchIterator);
if(watch->id == event->wd){
const uint_fast64_t eventNameLength = strlen(event->name);
const uint_fast64_t baseDirectoryLength = watch->directoryNameLength - (server->rootDirectoryLength - 1/*Keep the leading '/'.*/);
const uint_fast64_t symbolicFileLocationLength = baseDirectoryLength + eventNameLength;
char* symbolicFileLocation = alloca(sizeof(*symbolicFileLocation) * symbolicFileLocationLength + 1);
if(symbolicFileLocation == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return;
}
memcpy(symbolicFileLocation, watch->directory + (server->rootDirectoryLength - 1), baseDirectoryLength);
memcpy(symbolicFileLocation + baseDirectoryLength, event->name, eventNameLength);
symbolicFileLocation[symbolicFileLocationLength] = '\0';
const uint_fast64_t fileLocationLength = (server->rootDirectoryLength - 1) + symbolicFileLocationLength;
char* fileLocation = malloc(sizeof(*fileLocation) * (fileLocationLength + 1));
if(fileLocation == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return;
}
memcpy(fileLocation, server->rootDirectory,(server->rootDirectoryLength - 1));
memcpy(fileLocation + (server->rootDirectoryLength - 1), symbolicFileLocation, symbolicFileLocationLength);
fileLocation[fileLocationLength] = '\0';
CacheObject* cacheObject;
if(cache_get(&server->cache, &cacheObject, symbolicFileLocation, symbolicFileLocationLength) != ERROR_NO_ERROR){
return;
}
if(cacheObject != NULL){
if(cache_remove(&server->cache, cacheObject) != ERROR_NO_ERROR){
return;
}
}
if(cache_load(&server->cache, &cacheObject, fileLocation, fileLocationLength, symbolicFileLocation, symbolicFileLocationLength) != ERROR_NO_ERROR){
return;
}
break;
}
}
}
local void server_inotifyEventHandlerFileDeleted(HerderServer* server, struct inotify_event* event){
LinkedListIterator watchIterator;
linkedList_initIterator(&watchIterator, &watches);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&watchIterator)){
INOTIFY_Watch* watch = LINKED_LIST_ITERATOR_NEXT(&watchIterator);
if(watch->id == event->wd){
const uint_fast64_t eventNameLength = strlen(event->name);
const uint_fast64_t baseDirectoryLength = watch->directoryNameLength - (server->rootDirectoryLength - 1/*Keep the leading '/'.*/);
const uint_fast64_t symbolicFileLocationLength = baseDirectoryLength + eventNameLength;
char* symbolicFileLocation = malloc(sizeof(*symbolicFileLocation) * symbolicFileLocationLength + 1);
if(symbolicFileLocation == NULL){
UTIL_LOG_ERROR(util_toErrorString(ERROR_OUT_OF_MEMORY));
return;
}
memcpy(symbolicFileLocation, watch->directory + (server->rootDirectoryLength - 1), baseDirectoryLength);
memcpy(symbolicFileLocation + baseDirectoryLength, event->name, eventNameLength);
symbolicFileLocation[symbolicFileLocationLength] = '\0';
CacheObject* cacheObject;
if(cache_get(&server->cache, &cacheObject, symbolicFileLocation, symbolicFileLocationLength) != ERROR_NO_ERROR){
return;
}
if(cacheObject != NULL){
if(cache_remove(&server->cache, cacheObject) != ERROR_NO_ERROR){
return;
}
}
break;
}
}
}
SERVER_CONTEXT_HANDLER(server_defaultContextHandler){
uint_fast64_t fileLocationLength;
char* fileLocation;
ERROR_CODE error;
if(request->urlLength == 1 && request->requestURL[0] == '/'){
fileLocationLength = 11/*/index.html*/;
fileLocation = alloca(sizeof(*fileLocation) * (11/*/index.html*/ + 1));
memcpy(fileLocation, "/index.html", 11);
fileLocation[fileLocationLength] = '\0';
}else{
fileLocationLength = request->urlLength;
fileLocation = alloca(sizeof(*fileLocation) * (fileLocationLength + 1));
memcpy(fileLocation, request->requestURL, fileLocationLength);
fileLocation[fileLocationLength] = '\0';
}
CacheObject* cacheObject;
if((error = server_getFile(server, &cacheObject, fileLocation, fileLocationLength)) != ERROR_NO_ERROR){
if(error == ERROR_FAILED_TO_RETRIEV_FILE_INFO){
error = server_constructErrorPage(server, request, response, _400_BAD_REQUEST);
return ERROR(error);
}else{
error = server_constructErrorPage(server, request, response, _500_INTERNAL_SERVER_ERROR);
return ERROR(error);
}
}
UTIL_LOG_CONSOLE_(LOG_DEBUG, "URL:'%s', File:'%s'.", request->requestURL, fileLocation);
response->cacheObject = cacheObject;
response->dataLength += cacheObject->size;
response->staticContent = true;
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
response->contentType = http_getContentType(cacheObject->fileLocation + cacheObject->fileExtensionOffset, cacheObject->fileLocationLength - cacheObject->fileExtensionOffset);
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
return ERROR(ERROR_NO_ERROR);
}
local THREAD_POOL_RUNNABLE_(server_run, Job, job){
Client* client = job->data;
void* buffer = job->buffer;
char ip[INET_ADDRSTRLEN];
if(client->socket.sin_family == AF_INET){
inet_ntop(AF_INET, &(client->socket.sin_addr), ip, INET_ADDRSTRLEN);
}else{
memset(ip, 0, INET_ADDRSTRLEN);
}
HTTP_Request request;
http_initRequest_(&request, buffer, HTTP_PROCESSING_BUFFER_SIZE, 0);
ERROR_CODE error;
if((error = http_receiveRequest(&request, client->sockFD)) != ERROR_NO_ERROR){
UTIL_LOG_ERROR_("Failed to receive HTTP request. '%s' [%s].", request.requestURL, util_toErrorString(error));
}
HTTP_Response response;
http_initResponse(&response, buffer, HTTP_PROCESSING_BUFFER_SIZE);
if(error != ERROR_NO_ERROR){
error = server_constructErrorPage(client->server, &request, &response, _400_BAD_REQUEST);
}else{
ContextHandler* contextHandler;
// TODO:(jan) Check return value and send correct error page (ERROR_ENTRY_NOT_FOUND vs ERORR_INVALID_URL).
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if(server_getContext(client->server, &contextHandler, &request) != ERROR_NO_ERROR){
server_constructErrorPage(client->server, &request, &response, _400_BAD_REQUEST);
}
if(contextHandler == NULL){
server_constructErrorPage(client->server, &request, &response, _401_UNAUTHORIZED);
}else{
if((error = contextHandler(client->server, &request, &response)) != ERROR_NO_ERROR){
UTIL_LOG_ERROR(util_toErrorString(error));
}
}
}
if((error = http_sendResponse(&response, client->sockFD)) != ERROR_NO_ERROR){
UTIL_LOG_ERROR_("Failed to send HTTP response. %d", error);
}
http_freeHTTP_Response(&response);
close(client->sockFD);
http_freeHTTP_Request(&request);
free(client);
return NULL;
}
local void server_deamonSignalHandler(int signal, siginfo_t* info, void* context){
switch(signal){
case SIGPIPE:{
UTIL_LOG_INFO("SIGPIPE catched, ignoring broken pipe.");
break;
}case SIGHUP:{
UTIL_LOG_INFO("SIGHUP catched.");
break;
}case SIGINT:{
UTIL_LOG_INFO("SIGINT - Stopping server.");
server_stop(&server);
break;
}case SIGTERM:{
UTIL_LOG_INFO("Terminating Daemon.");
exit(EXIT_SUCCESS);
break;
}
}
}
local SERVER_CONTEXT_HANDLER(server_pageAdd){
if(request->type != REQUEST_TYPE_POST){
server_constructErrorPage(server, request, response, _405_METHOD_NOT_ALLOWED);
return ERROR(ERROR_NO_ERROR);
}
// TODO:(jan) Add error handling for to small/malformed requests.
uint_fast64_t readOffset = 0;
// ShowName.
const uint_fast64_t showNameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
char* showName = (char*) request->data + readOffset;
readOffset += showNameLength;
// EpisodeName.
const uint_fast64_t episodeNameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
char* episodeName = (char*) request->data + readOffset;
readOffset += episodeNameLength;
// Season.
const uint_fast16_t seasonNumber = util_byteArrayTo_uint16(request->data + readOffset);
readOffset += sizeof(uint16_t);
// Episode.
const uint_fast16_t episodeNumber = util_byteArrayTo_uint16(request->data + readOffset);
readOffset += sizeof(uint16_t);
// FileExtension.
const uint_fast16_t fileExtensionLength = util_byteArrayTo_uint16(request->data + readOffset);
readOffset += sizeof(uint16_t);
char* fileExtension = (char*) request->data + readOffset;
readOffset += fileExtensionLength;
ERROR_CODE error;
if(showNameLength == 0){
error = ERROR_INVALID_CONTENT_LENGTH;
goto label_return;
}
Show* show;
if((error = medialibrary_getShow(&server->library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
if((error = mediaLibrary_addShow(&server->library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
}
Season* season;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
if((error = medialibrary_getSeason(show, &season, seasonNumber)) != ERROR_NO_ERROR){
if((error = mediaLibrary_addSeason(&server->library, &season, show, seasonNumber)) != ERROR_NO_ERROR){
goto label_return;
}
}
Episode* episode;
if(mediaLibrary_getEpisode(season, &episode, episodeNumber) == ERROR_NO_ERROR){
error = strncmp(episode->name, episodeName, episode->nameLength + 1) ? ERROR_NAME_MISSMATCH : ERROR_DUPLICATE_ENTRY;
goto label_return;
}
if((error = mediaLibrary_addEpisode(&server->library, &episode, show, season, episodeNumber, episodeName, episodeNameLength, fileExtension, fileExtensionLength, true)) != ERROR_NO_ERROR){
goto label_return;
}
label_return:
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
util_uint64ToByteArray(response->data + response->dataLength, error);
response->dataLength += sizeof(uint64_t);
return ERROR(error);
}
local SERVER_CONTEXT_HANDLER(server_pageAddShow){
if(request->type != REQUEST_TYPE_POST){
server_constructErrorPage(server, request, response, _405_METHOD_NOT_ALLOWED);
return ERROR(ERROR_NO_ERROR);
}
uint_fast64_t readOffset = 0;
const uint_fast64_t showNameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
char* showName = (char*) request->data + readOffset;
readOffset += showNameLength;
Show* show;
ERROR_CODE error;
error = mediaLibrary_addShow(&server->library, &show, showName, showNameLength);
util_uint64ToByteArray(response->data + response->dataLength, error);
response->dataLength += sizeof(uint64_t);
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
return ERROR(ERROR_NO_ERROR);
}
local SERVER_CONTEXT_HANDLER(server_pageRemoveShow){
if(request->type != REQUEST_TYPE_POST){
server_constructErrorPage(server, request, response, _405_METHOD_NOT_ALLOWED);
return ERROR(ERROR_NO_ERROR);
}
uint_fast64_t readOffset = 0;
const uint_fast64_t showNameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
char* showName = (char*) request->data + readOffset;
readOffset += showNameLength;
ERROR_CODE error;
error = mediaLibrary_removeShow(&server->library, showName, showNameLength);
util_uint64ToByteArray(response->data + response->dataLength, error);
response->dataLength += sizeof(uint64_t);
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
return ERROR(ERROR_NO_ERROR);
}
local SERVER_CONTEXT_HANDLER(server_pageRemoveEpisode){
if(request->type != REQUEST_TYPE_POST){
server_constructErrorPage(server, request, response, _405_METHOD_NOT_ALLOWED);
return ERROR(ERROR_NO_ERROR);
}
// TODO:(jan) Add error handling for to small/malformed requests.
uint_fast64_t readOffset = 0;
// ShowName.
const uint_fast64_t showNameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
char* showName = (char*) request->data + readOffset;
readOffset += showNameLength;
// Season.
const uint_fast16_t seasonNumber = util_byteArrayTo_uint16(request->data + readOffset);
readOffset += sizeof(uint16_t);
// Episode.
const uint_fast16_t episodeNumber = util_byteArrayTo_uint16(request->data + readOffset);
readOffset += sizeof(uint16_t);
ERROR_CODE error;
if(showNameLength == 0){
error = ERROR_INVALID_CONTENT_LENGTH;
goto label_return;
}
Show* show;
if((error = medialibrary_getShow(&server->library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
Season* season;
if((error = medialibrary_getSeason(show, &season, seasonNumber)) != ERROR_NO_ERROR){
goto label_return;
}
Episode* episode;
if(mediaLibrary_getEpisode(season, &episode, episodeNumber) != ERROR_NO_ERROR){
goto label_return;
}
error = medialibrary_removeEpisode(&server->library, show, season, episode, true);
label_return:
util_uint64ToByteArray(response->data + response->dataLength, error);
response->dataLength += sizeof(uint64_t);
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
return ERROR(ERROR_NO_ERROR);
}
local SERVER_CONTEXT_HANDLER(server_pageShows){
if(request->type != REQUEST_TYPE_GET){
server_constructErrorPage(server, request, response, _405_METHOD_NOT_ALLOWED);
return ERROR(ERROR_NO_ERROR);
}
// NumShows.
util_uint64ToByteArray(response->data + response->dataLength, server->library.shows.length);
response->dataLength += sizeof(uint64_t);
LinkedListIterator it;
linkedList_initIterator(&it, &server->library.shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
util_uint64ToByteArray(response->data + response->dataLength, show->nameLength);
response->dataLength += sizeof(uint64_t);
memcpy(response->data + response->dataLength, show->name, show->nameLength);
response->dataLength += show->nameLength;
}
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
response->contentType = HTTP_CONTENT_TYPE_TEXT_HTML;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
return ERROR(ERROR_NO_ERROR);
}
local SERVER_CONTEXT_HANDLER(server_pageShowInfo){
if(request->type != REQUEST_TYPE_POST){
server_constructErrorPage(server, request, response, _405_METHOD_NOT_ALLOWED);
return ERROR(ERROR_NO_ERROR);
}
uint_fast64_t readOffset = 0;
const uint_fast64_t nameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
const char* showName = (char*) (request->data + readOffset);
readOffset += nameLength + 1;
Show* show;
if(medialibrary_getShow(&server->library, &show, showName, nameLength) == ERROR_ENTRY_NOT_FOUND){
util_uint64ToByteArray(response->data + response->dataLength, ERROR_ENTRY_NOT_FOUND);
response->dataLength += sizeof(uint64_t);
}else{
util_uint64ToByteArray(response->data + response->dataLength, ERROR_NO_ERROR);
response->dataLength += sizeof(uint64_t);
// Num_Seasons.
util_uint64ToByteArray(response->data + response->dataLength, show->seasons.length);
response->dataLength += sizeof(uint64_t);
if(show->seasons.length > 0){
Season** sortedSeasons = alloca(sizeof(Season*) * show->seasons.length);
mediaLibrary_sortSeasons(&sortedSeasons, &show->seasons);
uint_fast64_t j;
for(j = 0; j < show->seasons.length; j++){
Season* season = sortedSeasons[j];
// Season_Number.
util_uint16ToByteArray(response->data + response->dataLength, season->number);
response->dataLength += sizeof(uint16_t);
// Num_Episodes.
util_uint64ToByteArray(response->data + response->dataLength, season->episodes.length);
response->dataLength += sizeof(uint64_t);
Episode** sortedEpisodes = alloca(sizeof(Episode*) * season->episodes.length);
mediaLibrary_sortEpisodes(&sortedEpisodes, &season->episodes);
uint_fast64_t j;
for(j = 0; j < season->episodes.length; j++){
Episode* episode = sortedEpisodes[j];
// Episode_Number.
util_uint16ToByteArray(response->data + response->dataLength, episode->number);
response->dataLength += sizeof(uint16_t);
// Episode_NameLength.
util_uint64ToByteArray(response->data + response->dataLength, episode->nameLength);
response->dataLength += sizeof(uint64_t);
// Episode_Name.
memcpy(response->data + response->dataLength, episode->name, episode->nameLength + 1);
response->dataLength += episode->nameLength + 1;
// File_ExtensionLength.
util_uint16ToByteArray(response->data + response->dataLength, episode->fileExtensionLength);
response->dataLength += sizeof(uint16_t);
// File_Extension.
memcpy(response->data + response->dataLength, episode->fileExtension, episode->fileExtensionLength + 1);
response->dataLength += episode->fileExtensionLength + 1;
}
}
}
}
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
response->contentType = HTTP_CONTENT_TYPE_TEXT_HTML;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
return ERROR(ERROR_NO_ERROR);
}
local SERVER_CONTEXT_HANDLER(server_pageRenameEpisode){
if(request->type != REQUEST_TYPE_POST){
server_constructErrorPage(server, request, response, _405_METHOD_NOT_ALLOWED);
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE error;
uint_fast64_t readOffset = 0;
// Show_name.
const uint_fast64_t showNameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
const char* showName = (char*) (request->data + readOffset);
readOffset += showNameLength + 1;
Show* show;
if((error = medialibrary_getShow(&server->library, &show, showName, showNameLength)) != ERROR_NO_ERROR){
goto label_onError;
}
// Season_Number.
uint16_t seasonNumber = util_byteArrayTo_uint16(request->data + readOffset);
readOffset += sizeof(uint16_t);
Season* season;
if((error = medialibrary_getSeason(show, &season, seasonNumber)) != ERROR_NO_ERROR){
goto label_onError;
}
// Episode_Number.
uint16_t episodeNumber = util_byteArrayTo_uint16(request->data + readOffset);
readOffset += sizeof(uint16_t);
Episode* episode;
if((error = mediaLibrary_getEpisode(season, &episode, episodeNumber)) != ERROR_NO_ERROR){
goto label_onError;
}
// New Episode_Name.
const uint_fast64_t newEpisodeNameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
char* newEpisodeName = (char*) (request->data + readOffset);
readOffset += newEpisodeNameLength + 1;
if((error = mediaLibrary_renameEpisode(&server->library, show, season, episode, newEpisodeName, newEpisodeNameLength)) != ERROR_NO_ERROR){
goto label_onError;
}
label_onError:
util_uint64ToByteArray(response->data + response->dataLength, error);
response->dataLength += sizeof(uint64_t);
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
response->contentType = HTTP_CONTENT_TYPE_TEXT_HTML;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
return ERROR(ERROR_NO_ERROR);
}
local SERVER_CONTEXT_HANDLER(server_pageExtractShowInfo){
if(request->type != REQUEST_TYPE_POST){
server_constructErrorPage(server, request, response, _405_METHOD_NOT_ALLOWED);
return ERROR(ERROR_NO_ERROR);
}
ERROR_CODE error = ERROR_NO_ERROR;
uint_fast64_t readOffset = 0;
const uint_fast64_t fileNameLength = util_byteArrayTo_uint64(request->data + readOffset);
readOffset += sizeof(uint64_t);
char* fileName = (char*) (request->data + readOffset);
readOffset += fileNameLength;
EpisodeInfo info;
if((error = mediaLibrary_initEpisodeInfo(&info)) != ERROR_NO_ERROR){
goto label_onError;
}else{
error = mediaLibrary_extractEpisodeInfo(&info, &server->library.shows, fileName, fileNameLength);
if(error != ERROR_NO_ERROR && error != ERROR_INCOMPLETE){
mediaLibrary_freeEpisodeInfo(&info);
goto label_onError;
}else{
util_uint64ToByteArray(response->data + response->dataLength, error);
response->dataLength += sizeof(uint64_t);
util_uint64ToByteArray(response->data + response->dataLength, info.showNameLength);
response->dataLength += sizeof(uint64_t);
memcpy(response->data + response->dataLength, info.showName, info.showNameLength);
response->dataLength += info.showNameLength;
util_uint64ToByteArray(response->data + response->dataLength, info.nameLength);
response->dataLength += sizeof(uint64_t);
memcpy(response->data + response->dataLength, info.name, info.nameLength);
response->dataLength += info.nameLength;
util_uint16ToByteArray(response->data + response->dataLength, info.season);
response->dataLength += sizeof(uint16_t);
util_uint16ToByteArray(response->data + response->dataLength, info.episode);
response->dataLength += sizeof(uint16_t);
goto label_return;
}
}
label_onError:
util_uint64ToByteArray(response->data + response->dataLength, error);
response->dataLength += sizeof(uint64_t);
label_return:
mediaLibrary_freeEpisodeInfo(&info);
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = _200_OK;
response->contentType = HTTP_CONTENT_TYPE_TEXT_HTML;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
return ERROR(ERROR_NO_ERROR);
}
// TODO:(jan) Make custom entry point for the server build, so we won't have to use 'main'.
#ifndef TEST_BUILD
int main(const int argc, const char** argv){
#else
int server_totalyNotMain(const int argc, const char** argv){
#endif
ERROR_CODE error;
openlog(SERVER_DAEMON_NAME, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
ArgumentParser parser;
if((error = argumentParser_init(&parser)) != ERROR_NO_ERROR){
goto label_exit;
}
ARGUMENT_PARSER_ADD_ARGUMENT(Help, 3, "-?", "-h", "--help");
ARGUMENT_PARSER_ADD_ARGUMENT(SetServerRootDirectory, 1, "--setServerRootDirectory");
ARGUMENT_PARSER_ADD_ARGUMENT(SetServerExternalPort, 1, "--setServerExternalPort");
ARGUMENT_PARSER_ADD_ARGUMENT(ShowSettings, 1, "--showSettings");
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_NO_VALID_ARGUMENT);
if((error = argumentParser_parse(&parser, argc, argv)) != ERROR_NO_ERROR){
if(error == ERROR_DUPLICATE_ENTRY){
UTIL_LOG_CONSOLE(LOG_ERR, "Duplicate argument.");
goto label_exit;
}
}
const char* userHome = util_getHomeDirectory();
const uint_fast64_t userHomeLength = strlen(userHome);
const uint_fast64_t serverWorkingDirectoryLength = userHomeLength + 15/*/herder/daemon/*/;
char* serverWorkingDirectory = alloca(sizeof(*serverWorkingDirectory) * (serverWorkingDirectoryLength + 1));
strncpy(serverWorkingDirectory, userHome, userHomeLength);
strncpy(serverWorkingDirectory + userHomeLength, "/herder/daemon/", 16);
if(!util_fileExists(serverWorkingDirectory)){
UTIL_LOG_CONSOLE_(LOG_ERR, "WorkingDirectory '%s' %s.", serverWorkingDirectory, strerror(errno));
goto label_exit;
}
const uint_fast64_t proeprtyFileNameLength = strlen(PROPERTY_FILE_NAME);
const uint_fast64_t propertyFilePathLength = serverWorkingDirectoryLength + proeprtyFileNameLength;
char* propertyFilePath = alloca(sizeof(*propertyFilePath) * (propertyFilePathLength + 1));
strncpy(propertyFilePath, serverWorkingDirectory, serverWorkingDirectoryLength);
strncpy(propertyFilePath + serverWorkingDirectoryLength, PROPERTY_FILE_NAME, proeprtyFileNameLength + 1);
if(!util_fileExists(propertyFilePath)){
propertyFile_create(propertyFilePath, 8);
}
PropertyFile properties;
propertyFile_init(&properties, propertyFilePath);
Property* serverRootDirectory;
propertyFile_getProperty(&properties, &serverRootDirectory, SERVER_PROPERTY_SERVER_ROOT_DIRECTORY_NAME);
Property* serverExternalPort;
propertyFile_getProperty(&properties, &serverExternalPort, PROPERTY_SERVER_EXTERNAL_PORT_NAME);
if(argumentParser_contains(&parser, &argumentHelp)){
UTIL_LOG_CONSOLE(LOG_INFO, "Usage: herder --[command]/-[alias] <arguments>.\n");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t%s", SERVER_USAGE_ARGUMENT_SET_SERVER_ROOT_DIRECTORY, "Sets the 'server root directory' to the given path.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t%s", SERVER_USAGE_ARGUMENT_SET_SERVER_EXTERNAL_PORT, "Sets the external port to the given port.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", SERVER_USAGE_ARGUMENT_SHOW_SETTINGS, "Shows a quick overview of all the user settings.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t%s", SERVER_USAGE_ARGUMENT_HELP, "Displays this help.");
goto label_exit;
}
// --setServerRootDirectory
if(argumentParser_contains(&parser, &argumentSetServerRootDirectory)){
if(argumentSetServerRootDirectory.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " SERVER_USAGE_ARGUMENT_SET_SERVER_ROOT_DIRECTORY);
}else{
if((error = propertyFile_createAndSetDirectoryProperty(&properties, &serverRootDirectory, SERVER_PROPERTY_SERVER_ROOT_DIRECTORY_NAME, argumentSetServerRootDirectory.values[0], argumentSetServerRootDirectory.valueLengths[0])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully set '%s' to '%s'", SERVER_PROPERTY_SERVER_ROOT_DIRECTORY_NAME, (char*) serverRootDirectory->buffer);
}
goto label_free;
}
}
// --setServerExternalPort
if(argumentParser_contains(&parser, &argumentSetServerExternalPort)){
if(argumentSetServerExternalPort.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " PROPERTY_SERVER_EXTERNAL_PORT_NAME);
}else{
int64_t port;
ERROR_CODE error;
if((error = util_stringToInt(argumentSetServerExternalPort.values[0], &port)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Port value must be in range of 0-%" PRIu16 ". '%s'.", UINT16_MAX, util_toErrorString(ERROR_INVALID_VALUE));
goto label_free;
}else{
if(port <= 0 || port > UINT16_MAX){
UTIL_LOG_CONSOLE_(LOG_ERR, "Port value must be in range of 0-%" PRIu16 ". '%s'.", UINT16_MAX, util_toErrorString(ERROR_INVALID_VALUE));
goto label_free;
}
}
if((error = propertyFile_createAndSetUINT16Property(&properties, &serverExternalPort, PROPERTY_SERVER_EXTERNAL_PORT_NAME, port)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully set '%s' to '%s'", PROPERTY_SERVER_EXTERNAL_PORT_NAME, argumentSetServerExternalPort.values[0]);
}
goto label_free;
}
}
// --showSettings
if(argumentParser_contains(&parser, &argumentShowSettings)){
if(argumentShowSettings.numValues != 0){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage --showSettings.");
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "ServerRootDirectory: '%s'.", PROPERTY_IS_SET(serverRootDirectory) ? (char*) serverRootDirectory->buffer : "NULL");
UTIL_LOG_CONSOLE_(LOG_INFO, "ServerExternalPort: '%" PRIuFAST16 "'.", PROPERTY_IS_SET(serverExternalPort) ? util_byteArrayTo_uint16(serverExternalPort->buffer) : 0);
}
goto label_exit;
}
argumentParser_free(&parser);
if(PROPERTY_IS_NOT_SET(serverRootDirectory)){
UTIL_LOG_CONSOLE_(LOG_ERR, "Error: Failed to find server settings entry for '%s'.\n\tUse --setServerRootDirectory <path> to set the http server root directory.", SERVER_PROPERTY_SERVER_ROOT_DIRECTORY_NAME);
goto label_exit;
}
if(PROPERTY_IS_NOT_SET(serverExternalPort)){
UTIL_LOG_CONSOLE_(LOG_ERR, "Error: Failed to find server settings entry for '%s'.\n\tUse --setServerExternalPort <port> to set the external http server port.", PROPERTY_SERVER_EXTERNAL_PORT_NAME);
goto label_exit;
}
// server_daemonize(serverWorkingDirectory);
const uint_fast64_t serverDaemonNameLength = strlen(SERVER_DAEMON_NAME);
const uint_fast64_t serverDaemonLockFileNameLength = serverWorkingDirectoryLength + serverDaemonNameLength;
char* serverDaemonLockFileName = alloca(sizeof(*serverDaemonLockFileName) * (serverDaemonLockFileNameLength +5 /*'.lock'*/ + 1));
strncpy(serverDaemonLockFileName, serverWorkingDirectory, serverWorkingDirectoryLength);
strncpy(serverDaemonLockFileName + serverWorkingDirectoryLength, SERVER_DAEMON_NAME ".lock", serverDaemonNameLength + 5 + 1);
int lockFile;
lockFile = open(serverDaemonLockFileName, O_RDWR | O_CREAT, 0640);
if(lockFile == -1){
UTIL_LOG_ERROR_("Failed to open file: '%s'. %s.", serverDaemonLockFileName, strerror(errno));
goto label_exit;
}
if(lockf(lockFile, F_TLOCK, 0) == -1){
UTIL_LOG_INFO("Server already running.");
}else{
const uint_fast16_t port = util_byteArrayTo_uint16((int8_t*) serverExternalPort->buffer);
if((error = server_init(&server, (char*) serverRootDirectory->buffer, serverRootDirectory->entry->length - 1, port)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error));
goto label_free;
}
// HTML/Static pages
server_addContext(&server, "/", server_defaultContextHandler);
server_addContext(&server, "/img", server_defaultContextHandler);
server_addContext(&server, "/css", server_defaultContextHandler);
server_addContext(&server, "/js", server_defaultContextHandler);
// Herder media library rest api.
server_addContext(&server, "/add", server_pageAdd);
server_addContext(&server, "/addShow", server_pageAddShow);
server_addContext(&server, "/removeShow", server_pageRemoveShow);
server_addContext(&server, "/shows", server_pageShows);
server_addContext(&server, "/extractShowInfo", server_pageExtractShowInfo);
server_addContext(&server, "/showInfo", server_pageShowInfo);
server_addContext(&server, "/renameEpisode", server_pageRenameEpisode);
server_addContext(&server, "/removeEpisode", server_pageRemoveEpisode);
UTIL_LOG_INFO_("Starting server on port '%" PRIuFAST16 "'.", port);
if((error = server_start(&server)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "%s", util_toErrorString(error));
}
if(lockf(lockFile, F_ULOCK, 0) == -1){
UTIL_LOG_ERROR_("Failed to unlock lock file [%d] (%s)", errno, strerror(errno));
}
}
label_free:
close(lockFile);
server_free(&server);
util_deleteFile(serverDaemonLockFileName);
propertyFile_free(&properties);
if(PROPERTY_IS_SET(serverRootDirectory)){
propertyFile_freeProperty(serverRootDirectory);
free(serverRootDirectory);
}
if(PROPERTY_IS_SET(serverExternalPort)){
propertyFile_freeProperty(serverExternalPort);
free(serverExternalPort);
}
label_exit:
closelog();
return 0;
}
ERROR_CODE server_init(HerderServer* server, const char* rootDirectory, const uint_fast64_t rootDirectoryLength, const uint_fast16_t port){
memset(server, 0, sizeof(*server));
server->port = port;
ERROR_CODE error;
// TODO:(jan) Choose a sane number of threads here, or refactor threadPool to not need numWokers as an argument.
const int_fast32_t numAvailableCores = util_getNumAvailableProcessorCores();
const int_fast32_t numThreads = numAvailableCores * 12;
if((error = threadPool_init(&server->threadPool, numThreads + 1/* inotify watch thread for 'www' directory. */)) != ERROR_NO_ERROR){
return ERROR(error);
}
if((server->sockFD = socket(AF_INET, SOCK_STREAM, 0)) == -1){
return ERROR(ERROR_UNIX_DOMAIN_SOCKET_INITIALISATION_FAILED);
}
server->sockAddr.sin_family = AF_INET;
server->sockAddr.sin_addr.s_addr = INADDR_ANY;
server->sockAddr.sin_port = htons(port);
linkedList_init(&server->contexts);
if((error = mediaLibrary_init(&server->library, rootDirectory, rootDirectoryLength)) != ERROR_NO_ERROR){
return ERROR(error);
}
cache_init(&server->cache, numThreads, 32 * 1024 * 1024);
const uint_fast64_t serverWebDirectoryLength = strlen(SERVER_WEB_DIRECTORY);
server->rootDirectoryLength = rootDirectoryLength + serverWebDirectoryLength;
server->rootDirectory = malloc(sizeof(*server->rootDirectory) * (server->rootDirectoryLength + 1));
if(server->rootDirectory == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(server->rootDirectory, rootDirectory, rootDirectoryLength);
strncpy(server->rootDirectory + rootDirectoryLength, SERVER_WEB_DIRECTORY, serverWebDirectoryLength);
server->rootDirectory[server->rootDirectoryLength] = '\0';
if(!util_fileExists(server->rootDirectory)){
if((error = util_createDirectory(server->rootDirectory) != ERROR_NO_ERROR)){
return ERROR(error);
}
}
if(bind(server->sockFD, (struct sockaddr*) &server->sockAddr, sizeof(server->sockAddr)) == -1){
return ERROR(ERROR_FAILED_TO_BIND_SERVER_SOCKET);
}
server->alive = true;
// TODO:(jan) Decide on a socket backlog value, or implement epool for fun and giggles.
if(listen(server->sockFD, SOMAXCONN) == -1){
return ERROR(ERROR_FAILED_TO_LISTEN_ON_SERVER_SOCKET);
}
return ERROR(ERROR_NO_ERROR);
}
inline void server_initClient(Client* client, HerderServer* server){
memset(client, 0, sizeof(*client));
client->server = server;
}
inline ERROR_CODE server_getFile(HerderServer* server, CacheObject** cacheObject, char* symbolicFileLocation, const uint_fast64_t symbolicFileLocationLength){
*cacheObject = NULL;
ERROR_CODE error;
if((error = cache_get(&server->cache, cacheObject, symbolicFileLocation, symbolicFileLocationLength)) != ERROR_NO_ERROR){
return ERROR(error);
}
if(*cacheObject == NULL){
const uint_fast64_t fileLocationLength = server->rootDirectoryLength + symbolicFileLocationLength - 1;
char* fileLocation = malloc(sizeof(*fileLocation) * fileLocationLength + 1);
if(fileLocation == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
memcpy(fileLocation, server->rootDirectory, server->rootDirectoryLength);
memcpy(fileLocation + server->rootDirectoryLength, symbolicFileLocation + 1, symbolicFileLocationLength - 1);
fileLocation[fileLocationLength] = '\0';
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_FAILED_TO_RETRIEV_FILE_INFO);
error = cache_load(&server->cache, cacheObject, fileLocation, fileLocationLength, symbolicFileLocation, symbolicFileLocationLength);
}
return ERROR_(error, "File:'%s'", symbolicFileLocation);
}
inline ERROR_CODE server_initContext(Context* context, const char* location, const uint_fast64_t locationLength, ContextHandler* contextHandler){
context->locationLength = locationLength;
context->location = malloc(sizeof(*location) * (locationLength + 1));
if(context->location == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
strncpy(context->location, location, locationLength + 1);
context->contextHandler = contextHandler;
return ERROR(ERROR_NO_ERROR);
}
inline void server_freeContext(Context* context){
free(context->location);
}
ERROR_CODE server_start(HerderServer* server){
threadPool_run(&server->threadPool, (Runnable*) server_inotifyWatch, server);
while(server->alive){
Client* client = malloc(sizeof(*client));
if(client == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
server_initClient(client, server);
socklen_t clientSocketSize = sizeof(client->socket);
if((client->sockFD = accept(server->sockFD, (struct sockaddr*) &client->socket, &clientSocketSize)) == -1){
UTIL_LOG_INFO_("Failed to accept incoming connection. '%s'.", strerror(errno));
free(client);
continue;
}
// Note: We cast server_run to Runnable* here to be able to use the THREAD_POOL_RUNNABLE_ macro in the defenition of server_run, this allows us to have type information inside the function. (jan - 2019.03.07)
threadPool_run(&server->threadPool, (Runnable*) server_run, client);
}
return ERROR(ERROR_NO_ERROR);
}
inline void server_free(HerderServer* server){
close(server->sockFD);
threadPool_free(&server->threadPool);
LinkedListIterator it;
linkedList_initIterator(&it, &server->contexts);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Context* context = LINKED_LIST_ITERATOR_NEXT(&it);
server_freeContext(context);
free(context);
}
linkedList_free(&server->contexts);
free(server->rootDirectory);
cache_free(&server->cache);
mediaLibrary_free(&server->library);
}
inline ERROR_CODE server_stop(HerderServer* server){
server->alive = false;
shutdown(server->sockFD, SHUT_RDWR);
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE server_addContext(HerderServer* server, const char* location, ContextHandler* contextHandler){
Context* context = malloc(sizeof(*context));
if(context == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
server_initContext(context, location, strlen(location), contextHandler);
linkedList_add(&server->contexts, context);
return ERROR(ERROR_NO_ERROR);
}
inline ERROR_CODE server_getContext(HerderServer* server, ContextHandler** contextHandler, HTTP_Request* request){
char* baseDirectory;
uint_fast64_t baseDirectoryLength;
if(util_getBaseDirectory(&baseDirectory, &baseDirectoryLength, request->requestURL, request->urlLength) != ERROR_NO_ERROR){
*contextHandler = NULL;
return ERROR_(ERROR_INVALID_REQUEST_URL, "Failed to find baseDirectory URL:'%s'.", request->requestURL);
}
LinkedListIterator it;
linkedList_initIterator(&it, &server->contexts);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Context* context = LINKED_LIST_ITERATOR_NEXT(&it);
if(strncmp(baseDirectory, context->location, baseDirectoryLength) == 0){
if(context->location[baseDirectoryLength] == '\0'){
*contextHandler = context->contextHandler;
return ERROR(ERROR_NO_ERROR);
}
}
}
*contextHandler = NULL;
return ERROR(ERROR_ENTRY_NOT_FOUND);
}
ERROR_CODE server_constructErrorPage(HerderServer* server,HTTP_Request* request, HTTP_Response* response, HTTP_StatusCode statusCode){
http_setHTTP_Version(response, HTTP_VERSION_1_1);
response->statusCode = statusCode;
const char connection[] = "close";
HTTP_ADD_HEADER_FIELD((*response), Connection, connection);
const char errorPage[] = "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title>$errorCode</title> </head> <body> <h1>$errorCode</h1> <p>$errorMessage</p> <hr> <address>'Herder' HTTP-Web Server at <a href=\"http://$address\">$address</a> Port $port</address> </body></html>";
uint_fast64_t pageLength = strlen(errorPage);
memcpy(response->data, errorPage, pageLength + 1);
// ErrorCode.
const char errorCodeSearchString[] = "$errorCode";
const uint_fast64_t errorCodeSearchStringLength = strlen(errorCodeSearchString);
char errorString[UTIL_FORMATTED_NUMBER_LENGTH];
int_fast64_t formatedNumberLength = snprintf(errorString, UTIL_FORMATTED_NUMBER_LENGTH, "%" PRIdFAST16 "", http_getStatusCode(statusCode));
if(util_replace((char*) response->data, response->bufferSize, &pageLength, errorCodeSearchString, errorCodeSearchStringLength, errorString, formatedNumberLength) != ERROR_NO_ERROR){
UTIL_LOG_ERROR("Failed to replace '$erroCode'.");
}
// ErrorMessage.
const char errorMessageSearchString[] = "$errorMessage";
const char* errorMessage = http_getStatusMsg(statusCode);
if(util_replace((char*) response->data, response->bufferSize, &pageLength, errorMessageSearchString, strlen(errorMessageSearchString), errorMessage, strlen(errorMessage)) != ERROR_NO_ERROR){
UTIL_LOG_ERROR("Failed to replace '$errorMessage'.");
}
// Port.
const char portSeasrchString[] = "$port";
char port[UTIL_FORMATTED_NUMBER_LENGTH];
int_fast64_t portLength = snprintf(port, UTIL_FORMATTED_NUMBER_LENGTH, "%" PRIdFAST32 "", server->port);
if(util_replace((char*) response->data, response->bufferSize, &pageLength, portSeasrchString, strlen(portSeasrchString), port, portLength) != ERROR_NO_ERROR){
UTIL_LOG_ERROR("Failed to replace '$errorMessage'.");
}
// Url.
const char urlSeasrchString[] = "$url";
uint_fast64_t urlLength = request->urlLength;
char* url = alloca(sizeof(*url) * (urlLength + 1));
memcpy(url, request->requestURL, urlLength);
url[urlLength] = '\0';
if(util_replace((char*) response->data, response->bufferSize, &pageLength, urlSeasrchString, strlen(urlSeasrchString), url, request->urlLength) != ERROR_NO_ERROR){
UTIL_LOG_ERROR("Failed to replace '$errorMessage'.");
}
// Address.
const HTTP_HeaderField* headerFieldServer = http_getHeaderField(request, "Host");
if(headerFieldServer != NULL){
const char adddressSeatchString[] = "$address";
if(util_replace((char*) response->data, response->bufferSize, &pageLength, adddressSeatchString, strlen(adddressSeatchString), headerFieldServer->value, headerFieldServer->valueLength) != ERROR_NO_ERROR){
UTIL_LOG_ERROR("Failed to replace '$address'.");
}
}
response->dataLength = pageLength;
return ERROR(ERROR_NO_ERROR);
}
inline void server_daemonize(const char* workingDirectory){
// Ignore child signals, so we dont end up with a defunct zombie child process.
signal(SIGCHLD, SIG_IGN);
pid_t pid = fork();
if(pid < 0){
exit(EXIT_FAILURE);
}else if(pid > 0){
exit(EXIT_SUCCESS);
}
if(setsid() < 0){
exit(EXIT_FAILURE);
}
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
pid = fork();
if(pid < 0){
exit(EXIT_FAILURE);
}else if(pid > 0){
exit(EXIT_SUCCESS);
}
umask(S_IWGRP | S_IWOTH /*022*/);
if(chdir(workingDirectory) != 0){
UTIL_LOG_ERROR("Failed to change working directory.");
}
int_fast32_t fileDescriptor;
for (fileDescriptor = sysconf(_SC_OPEN_MAX); fileDescriptor >= 0; fileDescriptor--){
close(fileDescriptor);
}
openlog(SERVER_DAEMON_NAME, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
// Ignore TTY signals.
signal(SIGTSTP, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
struct sigaction action = {0};
// Block every signal while the handler runs.
sigfillset(&action.sa_mask);
action.sa_sigaction = &server_deamonSignalHandler;
action.sa_flags = SA_SIGINFO;
if(sigaction(SIGINT, &action, NULL) != 0) {
UTIL_LOG_WARNING("Failed to append signal handler. [SIGINT]");
}
if(sigaction(SIGPIPE, &action, NULL) != 0) {
UTIL_LOG_WARNING("Failed to append signal handler. [SIGPIPE]");
}
if(sigaction(SIGHUP, &action, NULL) != 0) {
UTIL_LOG_WARNING("Failed to append signal handler. [SIGHUP]");
}
if(sigaction(SIGTERM, &action, NULL) != 0) {
UTIL_LOG_WARNING("Failed to append signal handler. [SIGTERM]");
}
}
#undef SERVER_WEB_DIRECTORY
#endif
|
Ex05/herder
|
src/argumentParser.h
|
#ifndef ARGUMENT_PARSER_H
#define ARGUMENT_PARSER_H
#include "util.h"
#include "linkedList.h"
#if !defined __GNUC__ && !defined __GNUG__
TODO:(jan); Add preprocessor macros for other compiler.
#endif
#define ARGUMENT_PARSER_ADD_ARGUMENT(name, numArguments, ...) Argument argument ## name; \
argumentParser_addArgument(&parser, &argument ## name, numArguments, __VA_ARGS__)
typedef struct{
char** arguments;
uint_fast8_t numArguments;
const char** values;
uint_fast64_t* valueLengths;
uint_fast64_t numValues;
}Argument;
typedef struct{
LinkedList arguments;
}ArgumentParser;
ERROR_CODE argumentParser_init(ArgumentParser*);
ERROR_CODE argumentParser_addArgument(ArgumentParser*, Argument*, const uint_fast8_t, ...);
ERROR_CODE argumentParser_parse(ArgumentParser*, const int, const char**);
bool argumentParser_contains(ArgumentParser*, Argument*);
void argumentParser_free(ArgumentParser*);
#endif
|
Ex05/herder
|
src/linkedList.h
|
<gh_stars>0
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include "util.h"
#define LINKED_LIST_IS_EMPTY(list)((list)->length == 0)
#define LINKED_LIST_ITERATOR_HAS_NEXT(it) ((it)->node != NULL)
#define LINKED_LIST_ITERATOR_NEXT(it)(linkedList_iteratorNextNode(it)->data)
typedef struct node{
void* data;
struct node* next;
}Node;
typedef struct {
Node* tail;
uint_fast64_t length;
}LinkedList;
typedef struct {
Node* node;
}LinkedListIterator;
ERROR_CODE linkedList_init(LinkedList*);
ERROR_CODE linkedList_add(LinkedList*, void*);
void linkedList_initIterator(LinkedListIterator*, LinkedList*);
Node* linkedList_iteratorNextNode(LinkedListIterator*);
ERROR_CODE linkedList_remove(LinkedList*, void*);
void linkedList_free(LinkedList* list);
#endif
// Index: Watches: Directories:
// 0 1 /home
// 1 4 /home/ex05
// 2 8 /home/var
// 3 7 /home/ex05/projects
|
Ex05/herder
|
src/threadPool.c
|
#ifndef THREAD_POOL_C
#define THREAD_POOL_C
#include "threadPool.h"
local void* threadPool_threadFunc(void*);
// TODO:(jan) Cleanup error handling in 'threadpool_init' .
inline ERROR_CODE threadPool_init(ThreadPool* threadPool, const uint_fast16_t numWorkers){
threadPool->numWorkers = numWorkers;
threadPool->threads = malloc(sizeof(pthread_t) * numWorkers);
if(threadPool->threads == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
if(threadPool->threads == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
if(sem_init(&threadPool->numJobs, 0, 0)){
UTIL_LOG_ERROR("Failed to initialise 'semaphore'.");
free(threadPool->threads);
return ERROR(ERROR_PTHREAD_SEMAPHOR_INITIALISATION_FAILED);
}
if(pthread_mutex_init(&threadPool->lock, NULL)){
UTIL_LOG_ERROR("Failed to initialise 'pthread_mutex'.");
free(threadPool->threads);
return ERROR(ERROR_PTHREAD_MUTEX_INITIALISATION_FAILED);
}
ERROR_CODE error;
if((error = que_init(&threadPool->jobQue)) != ERROR_NO_ERROR){
return ERROR(error);
}
uint_fast16_t i;
for(i = 0; i < numWorkers; i++){
if(pthread_create(&threadPool->threads[i], NULL, threadPool_threadFunc, threadPool) != 0){
UTIL_LOG_ERROR("Failed to create thread.");
free(threadPool->threads);
return ERROR(ERROR_PTHREAD_THREAD_CREATION_FAILED);
}
}
if(sem_init(&threadPool->alive, 0, 0)){
UTIL_LOG_ERROR("Failed to initialise 'semaphore'.");
return ERROR(ERROR_PTHREAD_SEMAPHOR_INITIALISATION_FAILED);
}
return ERROR(ERROR_NO_ERROR);
}
inline void threadPool_free(ThreadPool* threadPool){
// Set threadPool status to 'Not alive'.
sem_post(&threadPool->alive);
// Free each worker from 'sem_wait(&threadPool->numJobs)'
uint_fast16_t i;
for(i = 0; i < threadPool->numWorkers; i++){
sem_post(&threadPool->numJobs);
}
for(i = 0; i < threadPool->numWorkers; i++){
// TODO:(jan) Collect exit status of each thread and report on it.
pthread_join(threadPool->threads[i], NULL);
}
sem_destroy(&threadPool->numJobs);
pthread_mutex_destroy(&threadPool->lock);
Job* job;
while((job = que_deque(&threadPool->jobQue)) != NULL){
free(job);
}
free(threadPool->threads);
}
ERROR_CODE threadPool_run(ThreadPool* threadPool, Runnable* runnable, void* data){
pthread_mutex_lock(&threadPool->lock);
Job* job = malloc(sizeof(*job));
if(job == NULL){
return ERROR(ERROR_OUT_OF_MEMORY);
}
job->runnable = runnable;
job->data = data;
que_enque(&threadPool->jobQue, job);
pthread_mutex_unlock(&threadPool->lock);
sem_post(&threadPool->numJobs);
return ERROR(ERROR_NO_ERROR);
}
void* threadPool_threadFunc(void* data){
ThreadPool* threadPool = (ThreadPool*) data;
void* httpProcessingBuffer;
if(util_blockAlloc(&httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE) != ERROR_NO_ERROR){
return NULL;
}
for(;;){
sem_wait(&threadPool->numJobs);
int alive;
if(sem_getvalue(&threadPool->alive, &alive) == -1){
UTIL_LOG_ERROR_("Invalid semaphore value '%d'.", alive);
}
if(alive != 0){
break;
}
pthread_mutex_lock(&threadPool->lock);
Job* job = que_deque(&threadPool->jobQue);
pthread_mutex_unlock(&threadPool->lock);
// NOTE: Until we can make sure we are not leaking memory, we just clear everything. (jan - 2019.03.06)
// TODO: Clear only the actually used memory after we send/received and handled our packets. (jan - 2019.03.06)
memset(httpProcessingBuffer, 0, HTTP_PROCESSING_BUFFER_SIZE);
job->buffer = httpProcessingBuffer;
job->runnable(job);
free(job);
}
util_unMap(httpProcessingBuffer, HTTP_PROCESSING_BUFFER_SIZE);
return NULL;
}
#endif
|
Ex05/herder
|
src/consoleClient.c
|
<filename>src/consoleClient.c<gh_stars>0
// POSIX Version ¢2008
#define _XOPEN_SOURCE 700
// For mmap flags that are not in the POSIX-Standard.
#define _GNU_SOURCE
#include <fcntl.h>
#include <signal.h>
#include <signal.h>
#include "util.c"
#include "linkedList.c"
#include "http.c"
#include "argumentParser.c"
#include "propertyFile.c"
#include "mediaLibrary.c"
#include "herder.c"
#include "pls.c"
#define CONSOLE_CLIENT_PROGRAM_NAME "herder"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_HELP "-?, -h, --help"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_ADD_SHOW "--addShow <name>."
#define CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE_SHOW "--removeShow <name>."
#define CONSOLE_CLIENT_USAGE_ARGUMENT_ADD_EPISODE "-a, --add, --addFile, --addEpisode <file>."
#define CONSOLE_CLIENT_USAGE_ARGUMENT_IMPORT "-i, --import optional:<path>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_BATCH_IMPORT "-b, --batch, --batchImport"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_RENAME "--rename"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_RENAME_EPISODE "--renameEpisode <old_name> <new_name>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE "--remove"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE_EPISODE "--removeEpisode <name>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_LIST_SHOWS "-l, --list --listShows"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_LIST_ALL_SHOWS "--listAll, --listAllShows"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_SHOW_INFO "--showInfo <name>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_SET_IMPORT_DIRECTORY "--setImportDirectory <path>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_SET_LIBRARY_DIRECTORY "--setLibraryDirectory <path>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_SET_REMOTE_HOST "--setRemoteHost <port>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_SET_REMOTE_PORT "--setRemotePort <port>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_SHOW_SETTINGS "--showSettings"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_PLAY "-p, --play <name>"
#define CONSOLE_CLIENT_USAGE_ARGUMENT_CONVERT "--mp3/convert :optional<all/showName>"
#define CONSOLE_CLIENT_PROPERTY_IMPORT_DIRECTORY_NAME "importDirectory"
#define CONSOLE_CLIENT_PROPERTY_REMOTE_HOST_NAME "remoteHost"
#define CONSOLE_CLIENT_PROPERTY_REMOTE_PORT_NAME "remotePort"
#define CONSOLE_CLIENT_PROPERTY_LIBRARY_DIRECTORY_NAME "libraryDirectory"
#define CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET() ((propertyFile_propertySet(remoteHost, CONSOLE_CLIENT_PROPERTY_REMOTE_HOST_NAME) == ERROR_NO_ERROR) && (propertyFile_propertySet(remotePort, CONSOLE_CLIENT_PROPERTY_REMOTE_PORT_NAME) == ERROR_NO_ERROR))
local void consoleClient_printHelp(void);
local ERROR_CODE consoleClient_listShows(Property*, Property*);
local ERROR_CODE consoleClient_import(Property*, Property*, Property*, const char*, const bool);
local ERROR_CODE consoleClient_listAllShows(Property*, Property*);
local ERROR_CODE consoleClient_printShowInfo(Property*, Property*, const char*, const uint_fast64_t);
local ERROR_CODE consoleClient_extractShowInfo(Property*, Property*, EpisodeInfo*, const bool);
local ERROR_CODE consoleClient_rename(Property*, Property*, Property*);
local ERROR_CODE consoleClient_renameEpisode(Property*, Property*, Property*, const char*, uint_fast64_t, const char*, const uint_fast64_t);
local ERROR_CODE consoleClient_remove(Property*, Property*, Property*);
local ERROR_CODE consoleClient_removeEpisode(Property*, Property*, Property*, const char*, uint_fast64_t);
local ERROR_CODE consoleClient_selectShow(Property*, Property*, Show**);
local ERROR_CODE consoleClient_selectSeason(Property*, Property*, Season**, Show*);
local ERROR_CODE consoleClient_selectEpisode(Episode**, Season*);
local ERROR_CODE consoleClient_selectYesNo(bool*);
local ERROR_CODE consoleClient_addEpisode(Property*, Property*, Property*, const char*, const uint_fast64_t);
local ERROR_CODE consoleClient_convert(Property*, Property*, Property*);
// TODO:(jan) Make custom entry point for the client build, so we won't have to use 'main'.
#ifndef TEST_BUILD
int main(const int argc, const char** argv){
#else
int consoleClient_totalyNotMain(const int argc, const char** argv){
#endif
ERROR_CODE error;
openlog(CONSOLE_CLIENT_PROGRAM_NAME, LOG_PID | LOG_NOWAIT | LOG_CONS, LOG_USER);
ArgumentParser parser;
if((error = argumentParser_init(&parser)) != ERROR_NO_ERROR){
goto label_free;
}
ARGUMENT_PARSER_ADD_ARGUMENT(Help, 3, "-?", "-h", "--help");
ARGUMENT_PARSER_ADD_ARGUMENT(AddShow, 1, "--addShow");
ARGUMENT_PARSER_ADD_ARGUMENT(RemoveShow, 1, "--removeShow");
ARGUMENT_PARSER_ADD_ARGUMENT(Add, 4, "-a", "--add", "--addFile", "--addEpisode");
ARGUMENT_PARSER_ADD_ARGUMENT(Import, 2, "-i", "--import");
ARGUMENT_PARSER_ADD_ARGUMENT(BatchImport, 3, "-b", "--batch", "--batchImport");
ARGUMENT_PARSER_ADD_ARGUMENT(Rename, 1, "--rename");
ARGUMENT_PARSER_ADD_ARGUMENT(RenameEpisode, 1, "--renameEpisode");
ARGUMENT_PARSER_ADD_ARGUMENT(Remove, 1, "--remove");
ARGUMENT_PARSER_ADD_ARGUMENT(RemoveEpisode, 1, "--removeEpisode");
ARGUMENT_PARSER_ADD_ARGUMENT(ListShows, 3, "-l", "--list", "--listShows");
ARGUMENT_PARSER_ADD_ARGUMENT(ListAll, 2, "--listAll", "--listAllShows");
ARGUMENT_PARSER_ADD_ARGUMENT(ShowInfo, 2, "--showInfo", "--info");
ARGUMENT_PARSER_ADD_ARGUMENT(SetImportDirectory, 1, "--setImportDirectory");
ARGUMENT_PARSER_ADD_ARGUMENT(SetLibraryDirectory, 1, "--setLibraryDirectory");
ARGUMENT_PARSER_ADD_ARGUMENT(SetRemoteHost, 1, "--setRemoteHost");
ARGUMENT_PARSER_ADD_ARGUMENT(SetRemoteHostPort, 1, "--setRemotePort");
ARGUMENT_PARSER_ADD_ARGUMENT(ShowSettings, 1, "--showSettings");
ARGUMENT_PARSER_ADD_ARGUMENT(Play, 1, "--play");
ARGUMENT_PARSER_ADD_ARGUMENT(Convert, 2, "--mp3", "--convert");
if((error = argumentParser_parse(&parser, argc, argv)) != ERROR_NO_ERROR){
if(error == ERROR_NO_VALID_ARGUMENT){
UTIL_LOG_CONSOLE(LOG_ERR, "No valid command line arguments.\nUse '" CONSOLE_CLIENT_USAGE_ARGUMENT_HELP "' to display a help message.");
goto label_free;
}else{
if(error == ERROR_DUPLICATE_ENTRY){
UTIL_LOG_CONSOLE(LOG_ERR, "Duplicate argument.");
}
}
goto label_free;
}
const char* userHome = util_getHomeDirectory();
const uint_fast64_t userHomeLength = strlen(userHome);
const uint_fast64_t propertyFilePathLength = userHomeLength + 16/*/herder/settings*/;
char* propertyFilePath = alloca(sizeof(*propertyFilePath) * (propertyFilePathLength + 1));
strncpy(propertyFilePath, userHome, userHomeLength);
strncpy(propertyFilePath + userHomeLength, "/herder/settings", 17);
if(!util_fileExists(propertyFilePath)){
if(propertyFile_create(propertyFilePath, 8) != ERROR_NO_ERROR){
goto label_free;
}
}
PropertyFile properties;
if(propertyFile_init(&properties, propertyFilePath) != ERROR_NO_ERROR){
goto label_freeProperties;
}
Property* importDirectory;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
propertyFile_getProperty(&properties, &importDirectory, CONSOLE_CLIENT_PROPERTY_IMPORT_DIRECTORY_NAME);
Property* remoteHost;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
propertyFile_getProperty(&properties, &remoteHost, CONSOLE_CLIENT_PROPERTY_REMOTE_HOST_NAME);
Property* remotePort;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
propertyFile_getProperty(&properties, &remotePort, CONSOLE_CLIENT_PROPERTY_REMOTE_PORT_NAME);
Property* libraryDirectory;
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_ENTRY_NOT_FOUND);
propertyFile_getProperty(&properties, &libraryDirectory, CONSOLE_CLIENT_PROPERTY_LIBRARY_DIRECTORY_NAME);
// --help.
if(argumentParser_contains(&parser, &argumentHelp)){
goto label_printHelp;
}
// --addShow.
if(argumentParser_contains(&parser, &argumentAddShow)){
if(argumentAddShow.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_ADD_SHOW);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
ERROR_CODE error;
if((error = herder_addShow(remoteHost, remotePort, argumentAddShow.values[0], argumentAddShow.valueLengths[0])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to add show '%s' to the library. '%s'", argumentAddShow.values[0], util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully added show '%s' to the library.", argumentAddShow.values[0]);
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --removeShow.
if(argumentParser_contains(&parser, &argumentRemoveShow)){
if(argumentRemoveShow.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE_SHOW);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
ERROR_CODE error;
if((error = herder_removeShow(remoteHost, remotePort, argumentRemoveShow.values[0], argumentRemoveShow.valueLengths[0])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to remove show. '%s'", util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully removed show '%s' from the library.", argumentRemoveShow.values[0]);
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --addEpisode.
if(argumentParser_contains(&parser, &argumentAdd)){
if(argumentAdd.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_ADD_EPISODE);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET() && (propertyFile_propertySet(libraryDirectory, CONSOLE_CLIENT_PROPERTY_LIBRARY_DIRECTORY_NAME) == ERROR_NO_ERROR)){
if(!util_fileExists(argumentAdd.values[0]) || util_isDirectory(argumentAdd.values[0])){
UTIL_LOG_CONSOLE_(LOG_INFO, "ERROR: '%s' is not a falid file.", argumentAdd.values[0]);
}else{
if((error = consoleClient_addEpisode(remoteHost, remotePort, libraryDirectory, argumentAdd.values[0], argumentAdd.valueLengths[0])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to add file'%s' to library. '%s'", argumentAdd.values[0], util_toErrorString(error));
}
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --import.
if(argumentParser_contains(&parser, &argumentImport)){
ERROR_CODE error;
if(argumentImport.numValues == 1){
// Import from path.
if((error = consoleClient_import(remoteHost, remotePort, libraryDirectory, argumentImport.values[0], false)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "ERROR: Failed to import from directory: '%s'. [%s]", argumentImport.values[0], util_toErrorString(error));
}
}else{
if(argumentImport.numValues == 0){
if(PROPERTY_IS_SET(importDirectory)){
// Import from importDirectory_setting.
if((error = consoleClient_import(remoteHost, remotePort, libraryDirectory, (char*) importDirectory->buffer, false)) != ERROR_NO_ERROR){
if(error != ERROR_DUPLICATE_ENTRY){
UTIL_LOG_CONSOLE_(LOG_ERR, "ERROR: Failed to import from directory: '%s'. [%s]", (char*) importDirectory->buffer, util_toErrorString(error));
}
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, "Import directory not set, Use '--setImportDirectory <path>' to set an import directory, or specify the directory to import from when running '-i, --import optional:<path>'.");
}
}else{
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_IMPORT);
}
}
goto label_freeProperties;
}
// --batch.
if(argumentParser_contains(&parser, &argumentBatchImport)){
ERROR_CODE error;
if(argumentBatchImport.numValues == 1){
// Import from path.
if((error = consoleClient_import(remoteHost, remotePort, libraryDirectory, argumentBatchImport.values[0], true)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "ERROR: Failed to import from directory: '%s'. [%s]", argumentBatchImport.values[0], util_toErrorString(error));
}
}else{
if(argumentBatchImport.numValues == 0){
if(PROPERTY_IS_SET(importDirectory)){
// Import from importDirectory_setting.
if((error = consoleClient_import(remoteHost, remotePort, libraryDirectory, (char*) importDirectory->buffer, true)) != ERROR_NO_ERROR){
if(error != ERROR_DUPLICATE_ENTRY){
UTIL_LOG_CONSOLE_(LOG_ERR, "ERROR: Failed to import from directory: '%s'. [%s]", (char*) importDirectory->buffer, util_toErrorString(error));
}
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, "Import directory not set, Use '--setImportDirectory <path>' to set an import directory, or specify the directory to import from when running '-i, --import optional:<path>'.");
}
}else{
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_BATCH_IMPORT);
}
}
goto label_freeProperties;
}
// --rename.
if(argumentParser_contains(&parser, &argumentRename)){
if(argumentRename.numValues != 0){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_RENAME);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
ERROR_CODE error;
if((error = consoleClient_rename(remoteHost, remotePort, libraryDirectory)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to rename Episode. '%s'", util_toErrorString(error));
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --renameEpisode.
if(argumentParser_contains(&parser, &argumentRenameEpisode)){
if(argumentRenameEpisode.numValues != 2){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_RENAME_EPISODE);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
ERROR_CODE error;
if((error = consoleClient_renameEpisode(remoteHost, remotePort, libraryDirectory, argumentRenameEpisode.values[0], argumentRenameEpisode.valueLengths[0], argumentRenameEpisode.values[1], argumentRenameEpisode.valueLengths[1])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to rename Episode. '%s'", util_toErrorString(error));
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --remove.
if(argumentParser_contains(&parser, &argumentRemove)){
if(argumentRename.numValues != 0){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
ERROR_CODE error;
if((error = consoleClient_remove(remoteHost, remotePort, libraryDirectory)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to remove Episode. '%s'", util_toErrorString(error));
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --removeEpisode.
if(argumentParser_contains(&parser, &argumentRemoveEpisode)){
if(argumentRenameEpisode.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE_EPISODE);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
ERROR_CODE error;
if((error = consoleClient_removeEpisode(remoteHost, remotePort, libraryDirectory, argumentRemoveEpisode.values[0], argumentRemoveEpisode.valueLengths[0])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to remove Episode. '%s'", util_toErrorString(error));
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --listShows.
if(argumentParser_contains(&parser, &argumentListShows)){
if(argumentListShows.numValues != 0){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_LIST_SHOWS);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
ERROR_CODE error;
if((error = consoleClient_listShows(remoteHost, remotePort)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to list shows. '%s'", util_toErrorString(error));
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --listAll.
if(argumentParser_contains(&parser, &argumentListAll)){
if(argumentListAll.numValues != 0){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_LIST_ALL_SHOWS);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
ERROR_CODE error;
if((error = consoleClient_listAllShows(remoteHost, remotePort)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to list all shows. '%s'", util_toErrorString(error));
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --showInfo.
if(argumentParser_contains(&parser, &argumentShowInfo)){
if(argumentShowInfo.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_SHOW_INFO);
}else{
if(CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET()){
if((error = consoleClient_printShowInfo(remoteHost, remotePort, argumentShowInfo.values[0], argumentShowInfo.valueLengths[0]))){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to print show info for '%s': '%s'.", argumentShowInfo.values[0], util_toErrorString(error));
goto label_freeProperties;
}
}else{
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(ERROR_PROPERTY_NOT_SET));
}
}
goto label_freeProperties;
}
// --setImportDirectory.
if(argumentParser_contains(&parser, &argumentSetImportDirectory)){
if(argumentSetImportDirectory.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_SET_IMPORT_DIRECTORY);
}else{
if((error = propertyFile_createAndSetDirectoryProperty(&properties, &importDirectory, CONSOLE_CLIENT_PROPERTY_IMPORT_DIRECTORY_NAME, argumentSetImportDirectory.values[0], argumentSetImportDirectory.valueLengths[0])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully set '%s' to '%s'", CONSOLE_CLIENT_PROPERTY_IMPORT_DIRECTORY_NAME, (char*) importDirectory->buffer);
}
}
goto label_freeProperties;
}
// --setLibraryDirectory.
if(argumentParser_contains(&parser, &argumentSetLibraryDirectory)){
if(argumentSetLibraryDirectory.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_SET_LIBRARY_DIRECTORY);
}else{
if((error = propertyFile_createAndSetDirectoryProperty(&properties, &libraryDirectory, CONSOLE_CLIENT_PROPERTY_LIBRARY_DIRECTORY_NAME, argumentSetLibraryDirectory.values[0], argumentSetLibraryDirectory.valueLengths[0])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully set '%s' to '%s'", CONSOLE_CLIENT_PROPERTY_LIBRARY_DIRECTORY_NAME, argumentSetLibraryDirectory.values[0]);
}
}
goto label_freeProperties;
}
// --setRemoteHost.
if(argumentParser_contains(&parser, &argumentSetRemoteHost)){
if(argumentSetRemoteHost.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_SET_REMOTE_HOST);
}else{
if((error = propertyFile_createAndSetStringProperty(&properties, &libraryDirectory, CONSOLE_CLIENT_PROPERTY_REMOTE_HOST_NAME, argumentSetRemoteHost.values[0], argumentSetRemoteHost.valueLengths[0])) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully set '%s' to '%s'", CONSOLE_CLIENT_PROPERTY_REMOTE_HOST_NAME, argumentSetRemoteHost.values[0]);
}
}
goto label_freeProperties;
}
// --setRemotePort.
if(argumentParser_contains(&parser, &argumentSetRemoteHostPort)){
if(argumentSetRemoteHostPort.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_SET_REMOTE_HOST);
}else{
int64_t port;
ERROR_CODE error;
if((error = util_stringToInt(argumentSetRemoteHostPort.values[0], &port)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Port value must be in range of 0-%" PRIu16 ". '%s'.", UINT16_MAX, util_toErrorString(ERROR_INVALID_VALUE));
goto label_freeProperties;
}else{
if(port <= 0 || port > UINT16_MAX){
UTIL_LOG_CONSOLE_(LOG_ERR, "Port value must be in range of 0-%" PRIu16 ". '%s'.", UINT16_MAX, util_toErrorString(ERROR_INVALID_VALUE));
goto label_freeProperties;
}
}
if((error = propertyFile_createAndSetUINT16Property(&properties, &libraryDirectory, CONSOLE_CLIENT_PROPERTY_REMOTE_PORT_NAME, port)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully set '%s' to '%s'", CONSOLE_CLIENT_PROPERTY_REMOTE_PORT_NAME, argumentSetRemoteHostPort.values[0]);
}
}
goto label_freeProperties;
}
// --play.
if(argumentParser_contains(&parser, &argumentPlay)){
if(argumentPlay.numValues != 1){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_PLAY);
}else{
Show show;
if((error = medialibrary_initShow(&show, argumentPlay.values[0], argumentPlay.valueLengths[0])) != ERROR_NO_ERROR){
goto label_freeProperties;
}
if((error = herder_pullShowInfo(remoteHost, remotePort, &show)) != ERROR_NO_ERROR){
goto label_freeProperties;
}
#define PLAYLIST_FILE_NAME "/tmp/herder_playList.pls"
if((error = pls_savePlayList(libraryDirectory, PLAYLIST_FILE_NAME, &show)) != ERROR_NO_ERROR){
mediaLibrary_freeShow(&show);
goto label_freeProperties;
}
mediaLibrary_freeShow(&show);
system("vlc \"" PLAYLIST_FILE_NAME "\" --play-and-exit");
#undef PLAYLIST_FILE_NAME
}
goto label_freeProperties;
}
// --convert.
if(argumentParser_contains(&parser, &argumentConvert)){
if(argumentConvert.numValues == 0){
consoleClient_convert(remoteHost, remotePort, libraryDirectory);
}else{
if(argumentConvert.numValues == 1){
LinkedList shows;
if((error = herder_pullShowList(&shows, remoteHost, remotePort)) != ERROR_NO_ERROR){
goto label_freeProperties;
}
#define CONSOLE_CLIENT_STRING_CONSTANT_ALL "all"
if(strncmp(CONSOLE_CLIENT_STRING_CONSTANT_ALL, argumentConvert.values[0], strlen(CONSOLE_CLIENT_STRING_CONSTANT_ALL) + 1) == 0){
LinkedListIterator it;
linkedList_initIterator(&it, &shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
if(strncmp(argumentConvert.values[0], show->name, argumentConvert.valueLengths[0] + 1) == 0){
if((error = herder_convertToMP3(remoteHost, remotePort, libraryDirectory, show->name, show->nameLength)) != ERROR_NO_ERROR){
goto label_freeShowList;
}
}
}
}else{
LinkedListIterator it;
linkedList_initIterator(&it, &shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
if(strncmp(argumentConvert.values[0], show->name, argumentConvert.valueLengths[0] + 1) == 0){
if((error = herder_convertToMP3(remoteHost, remotePort, libraryDirectory, show->name, show->nameLength)) != ERROR_NO_ERROR){
goto label_freeShowList;
}
}
}
}
#undef CONSOLE_CLIENT_STRING_CONSTANT_ALL
LinkedListIterator it;
label_freeShowList:
linkedList_initIterator(&it, &shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
mediaLibrary_freeShow(show);
free(show);
}
linkedList_free(&shows);
}else{
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_CONVERT);
}
}
goto label_freeProperties;
}
// --showSettings.
if(argumentParser_contains(&parser, &argumentShowSettings)){
if(argumentShowSettings.numValues != 0){
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid command. Usage: " CONSOLE_CLIENT_USAGE_ARGUMENT_SHOW_SETTINGS);
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "ImportDirectory: %s.", PROPERTY_IS_SET(importDirectory) ? (char*) importDirectory->buffer : "NULL");
UTIL_LOG_CONSOLE_(LOG_INFO, "RemoteHost: %s.", PROPERTY_IS_SET(remoteHost) ? (char*) remoteHost->buffer : "NULL");
UTIL_LOG_CONSOLE_(LOG_INFO, "RemotePorrt: %" PRIuFAST64 ".", PROPERTY_IS_SET(remotePort) ? util_byteArrayTo_uint64(remotePort->buffer) : 0);
UTIL_LOG_CONSOLE_(LOG_INFO, "LibraryDirectory: %s.", PROPERTY_IS_SET(libraryDirectory) ? (char*) libraryDirectory->buffer : "NULL");
}
goto label_freeProperties;
}
label_printHelp:
consoleClient_printHelp();
label_freeProperties:
if(PROPERTY_IS_SET(libraryDirectory)){
propertyFile_freeProperty(libraryDirectory);
free(libraryDirectory);
}
if(PROPERTY_IS_SET(remotePort)){
propertyFile_freeProperty(remotePort);
free(remotePort);
}
if(PROPERTY_IS_SET(remoteHost)){
propertyFile_freeProperty(remoteHost);
free(remoteHost);
}
if(PROPERTY_IS_SET(importDirectory)){
propertyFile_freeProperty(importDirectory);
free(importDirectory);
}
propertyFile_free(&properties);
label_free:
argumentParser_free(&parser);
closelog();
return EXIT_SUCCESS;
}
inline void consoleClient_printHelp(void){
UTIL_LOG_CONSOLE(LOG_INFO, "Usage: herder --[command]/-[alias] <arguments>.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_ADD_SHOW, "Adds a new empty show with the given name to the library.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE_SHOW, "Removes the show with the given name from the library.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_ADD_EPISODE, "Adds the given file to the library.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_IMPORT, "Imports all files from the given directory, if no directory is specified the import directory set via '--setImportDirectory' will be used.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_BATCH_IMPORT, "Like '--import' but only imports episodes which don't require any user input to be add to the library.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_RENAME, "Interactivly renames an episode.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_RENAME_EPISODE, "Renames episode <old_name> to <new_name>.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE, "Interactivly remove an episode from the library.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_REMOVE_EPISODE, "Remove episode <name> from the library.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_LIST_SHOWS, "Lists all shows currently in the library.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_LIST_ALL_SHOWS, "Lists all episodes of all shows currently in the library.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_SHOW_INFO, "Lists all episodes of the show <name>.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_SET_IMPORT_DIRECTORY, "Sets the 'import directory' to the given path.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_SET_LIBRARY_DIRECTORY, "Sets the 'library directory' to the given path.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_SET_REMOTE_HOST, "Sets the 'remote host' address to the given URL.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_SET_REMOTE_PORT, "Sets the 'remote host' port to the given port.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_SHOW_SETTINGS, "Shows a quick overview of all the user settings.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_PLAY, "Shows a quick overview of all the user settings.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%s\t\t\t%s", CONSOLE_CLIENT_USAGE_ARGUMENT_CONVERT, "Convert episodes to audio only versions. No Arguments opens an interactive episode selection, 'all' to convert all episodes in the library which have not been converted and 'showName' to convert all episodes of a show.");
}
inline ERROR_CODE consoleClient_listShows(Property* remoteHost, Property* remotePort){
ERROR_CODE error = ERROR_NO_ERROR;
LinkedList shows;
if((error = herder_pullShowList(&shows, remoteHost, remotePort)) != ERROR_NO_ERROR){
if(error != ERROR_FAILED_TO_CONNECT){
goto label_freeShowList;
}else{
goto label_return;
}
}
if(shows.length == 0){
UTIL_LOG_CONSOLE(LOG_INFO, "Library is empty.");
goto label_freeShowList;
}
LinkedListIterator it;
linkedList_initIterator(&it, &shows);
uint_fast64_t i = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
UTIL_LOG_CONSOLE_(LOG_INFO, "%02" PRIuFAST64 ":'%s'.", i, show->name);
i++;
mediaLibrary_freeShow(show);
free(show);
}
label_freeShowList:
linkedList_free(&shows);
label_return:
return ERROR(error);
}
ERROR_CODE consoleClient_import(Property* remoteHost, Property* remotePort, Property* libraryDirectory, const char* directory, const bool batchImport){
ERROR_CODE error;
if(!CONSOLE_CLIENT_REMOTE_HOST_PROPERTIES_SET() || PROPERTY_IS_NOT_SET(libraryDirectory)){
return ERROR(ERROR_PROPERTY_NOT_SET);
}
LinkedList infos;
if((error = linkedList_init(&infos)) != ERROR_NO_ERROR){
goto label_return;
}
if((error = util_walkDirectory(&infos, directory, UTIL_FILES_ONLY)) != ERROR_NO_ERROR){
goto label_return;
}
if(LINKED_LIST_IS_EMPTY(&infos)){
UTIL_LOG_CONSOLE_(LOG_INFO, "No files recorgnised for import in '%s'.", directory);
goto label_freeFiles;
}
LinkedList fileInfos;
if((error = linkedList_init(&fileInfos)) != ERROR_NO_ERROR){
goto label_freeFiles;
}
LinkedListIterator fileIterator;
linkedList_initIterator(&fileIterator, &infos);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&fileIterator)){
char* path = LINKED_LIST_ITERATOR_NEXT(&fileIterator);
const uint_fast64_t pathLength = strlen(path);
EpisodeInfo* info = alloca(sizeof(*info));
mediaLibrary_initEpisodeInfo(info);
info->path = path;
info->pathLength = pathLength;
info->fileName = util_getFileName(info->path, info->pathLength);
info->fileNameLength = strlen(info->fileName);
UTIL_LOG_CONSOLE_(LOG_INFO, "\"%s\"", info->fileName);
if((error = consoleClient_extractShowInfo(remoteHost, remotePort, info, batchImport)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to extract show info from file: '%s'. [%s]", info->fileName, util_toErrorString(error));
goto label_freeFiles;
}
linkedList_add(&fileInfos, info);
}
UTIL_LOG_CONSOLE(LOG_INFO, "Importing:...");
const uint_fast64_t entries = infos.length;
uint_fast64_t i = 0;
LinkedListIterator episodeInfoIterator;
linkedList_initIterator(&episodeInfoIterator, &fileInfos);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&episodeInfoIterator)){
EpisodeInfo* info = LINKED_LIST_ITERATOR_NEXT(&episodeInfoIterator);
if((error = herder_addEpisode(remoteHost, remotePort, libraryDirectory, info)) != ERROR_NO_ERROR){
if(error != ERROR_DUPLICATE_ENTRY){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to add Episode: '%s'. [%s]", info->fileName, util_toErrorString(error));
}
goto label_freeFiles;
}else{
i++;
UTIL_LOG_CONSOLE_(LOG_INFO, " %" PRIdFAST64 "/%" PRIdFAST64 " Successfully added '%s'. to library.", i, entries, info->fileName);
}
mediaLibrary_freeEpisodeInfo(info);
}
__UTIL_SUPPRESS_NEXT_ERROR_OF_TYPE__(ERROR_FAILED_TO_DELETE_DIRECTORY);
if((error = util_deleteDirectory(directory, true, true)) != ERROR_NO_ERROR){
goto label_freeFiles;
}
linkedList_free(&fileInfos);
label_freeFiles:
linkedList_free(&infos);
label_return:
return ERROR(error);
}
inline ERROR_CODE consoleClient_listAllShows(Property* remoteHost, Property* remotePort){
ERROR_CODE error = ERROR_NO_ERROR;
LinkedList shows = {0};
if((error = herder_pullShowList(&shows, remoteHost, remotePort)) != ERROR_NO_ERROR){
goto label_freeShowList;
}
if(shows.length == 0){
UTIL_LOG_CONSOLE(LOG_INFO,"Library is empty.");
goto label_freeShowList;
}
LinkedListIterator it;
linkedList_initIterator(&it, &shows);
uint_fast64_t i = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
if((error = consoleClient_printShowInfo(remoteHost, remotePort, show->name, show->nameLength)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE(LOG_ERR, util_toErrorString(error));
}
i++;
mediaLibrary_freeShow(show);
free(show);
}
label_freeShowList:
linkedList_free(&shows);
return ERROR(error);
}
inline ERROR_CODE consoleClient_printShowInfo(Property* remoteHost, Property* remotePort, const char* showName, const uint_fast64_t showNameLength){
ERROR_CODE error;
Show show;
if((error = medialibrary_initShow(&show, showName, showNameLength)) != ERROR_NO_ERROR){
goto label_return;
}
if((error = herder_pullShowInfo(remoteHost, remotePort, &show)) != ERROR_NO_ERROR){
goto label_freeShow;
}
UTIL_LOG_CONSOLE_(LOG_INFO, "%s:", show.name);
Season** seasons = alloca(sizeof(*seasons) * show.seasons.length);
if((error = mediaLibrary_sortSeasons(&seasons, &show.seasons)) != ERROR_NO_ERROR){
goto label_freeShow;
}
if(show.seasons.length == 0){
UTIL_LOG_CONSOLE(LOG_INFO, "\tEmpty.");
}
register uint_fast64_t i;
for(i = 0; i < show.seasons.length; i++){
Season* season = seasons[i];
Episode** episodes = alloca(sizeof(*episodes) * season->episodes.length);
if((error = mediaLibrary_sortEpisodes(&episodes, &season->episodes)) != ERROR_NO_ERROR){
goto label_freeShow;
}
UTIL_LOG_CONSOLE_(LOG_INFO, "\tSeason: %02" PRIuFAST16 ".", season->number);
register uint_fast64_t j;
for(j = 0; j < season->episodes.length; j++){
Episode* episode = episodes[j];
UTIL_LOG_CONSOLE_(LOG_INFO, "\t\t -> %02" PRIuFAST16 ": '%s'.", episode->number, episode->name);
}
}
label_freeShow:
mediaLibrary_freeShow(&show);
label_return:
return ERROR(error);
}
ERROR_CODE consoleClient_extractShowInfo(Property* remoteHost, Property* remotePort, EpisodeInfo* episodeInfo, const bool batchImport){
ERROR_CODE error;
label_extractShowInfo:
if((error = herder_extractShowInfo(remoteHost, remotePort, episodeInfo)) != ERROR_NO_ERROR){
if(error != ERROR_INCOMPLETE){
goto label_return;
}
}
int_fast64_t userInputLength;
char* userInput;
if(episodeInfo->showName == NULL){
UTIL_LOG_CONSOLE(LOG_INFO, "Failed to extract the show name based on library entries.\nPlease enter the show name.");
if((error = util_readUserInput(&userInput, &userInputLength)) != ERROR_NO_ERROR){
goto label_freeUserInput;
}
if((error = herder_addShow(remoteHost, remotePort, userInput, userInputLength)) != ERROR_NO_ERROR){
goto label_freeUserInput;
}
free(episodeInfo->name);
free(userInput);
goto label_extractShowInfo;
}
if(batchImport){
goto label_return;
}
UTIL_LOG_CONSOLE(LOG_INFO, "Are these values correct? Yes/No.");
UTIL_LOG_CONSOLE_(LOG_INFO, "\tShow:'%s'.", episodeInfo->showName);
UTIL_LOG_CONSOLE_(LOG_INFO, "\tSeason:'%" PRIdFAST16 "'.", episodeInfo->season);
UTIL_LOG_CONSOLE_(LOG_INFO, "\tEpisode:'%" PRIdFAST16 "'.", episodeInfo->episode);
UTIL_LOG_CONSOLE_(LOG_INFO, "\t\t'%s'.", episodeInfo->name);
label_readUserInput:
if((error = util_readUserInput(&userInput, &userInputLength)) != ERROR_NO_ERROR){
goto label_freeUserInput;
}
util_toLowerChase(userInput);
if(userInputLength != 0 && strncmp("no", userInput, userInputLength) == 0){
// Show name.
UTIL_LOG_CONSOLE_(LOG_INFO, "Show name:'%s'. Press <Enter> to accept.", episodeInfo->showName);
char* showName;
if((error = util_readUserInput(&showName, &userInputLength)) != ERROR_NO_ERROR){
goto label_freeUserInput;
}
if(userInputLength != 0){
free(episodeInfo->showName);
episodeInfo->showName = showName;
episodeInfo->showNameLength = userInputLength;
}else{
free(showName);
}
label_seasonNumber:
// Season number.
UTIL_LOG_CONSOLE_(LOG_INFO, "Season:'%" PRIiFAST16 "'. Press <Enter> to accept.", episodeInfo->season);
char* season;
if((error = util_readUserInput(&season, &userInputLength)) != ERROR_NO_ERROR){
goto label_freeUserInput;
}
if(userInputLength != 0){
if((error = util_stringToInt(season, (int64_t*) &episodeInfo->season)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "%s.", util_toErrorString(error));
free(season);
goto label_seasonNumber;
}
}
free(season);
label_episodeNumber:
// Episode number.
UTIL_LOG_CONSOLE_(LOG_INFO, "Episode:'%" PRIiFAST16 "'. Press <Enter> to accept.", episodeInfo->episode);
char* episode;
if((error = util_readUserInput(&episode, &userInputLength)) != ERROR_NO_ERROR){
goto label_freeUserInput;
}
if(userInputLength != 0){
if((error = util_stringToInt(episode, (int64_t*) &episodeInfo->episode)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "%s.", util_toErrorString(error));
free(episode);
goto label_episodeNumber;
}
}
free(episode);
// Episode name.
UTIL_LOG_CONSOLE_(LOG_INFO, "Episode name:'%s'. Press <Enter> to accept.", episodeInfo->name);
char* episodeName;
if((error = util_readUserInput(&episodeName, &userInputLength)) != ERROR_NO_ERROR){
goto label_freeUserInput;
}
if(userInputLength != 0){
free(episodeInfo->name);
episodeInfo->name = episodeName;
episodeInfo->nameLength = userInputLength;
}
}else{
if(userInputLength != 0 || strncmp("yes", userInput, userInputLength) != 0){
UTIL_LOG_CONSOLE_(LOG_INFO, "'%s' is not a valid answer, please type Yes/No.", userInput);
free(userInput);
goto label_readUserInput;
}
}
label_freeUserInput:
free(userInput);
label_return:
return ERROR(error);
}
ERROR_CODE consoleClient_rename(Property* remoteHost, Property* remotePort, Property* libraryDirectory){
ERROR_CODE error = ERROR_NO_ERROR;
Show* selectedShow = NULL;
if((error = consoleClient_selectShow(remoteHost, remotePort, &selectedShow))){
goto label_return;
}
UTIL_LOG_CONSOLE_(LOG_DEBUG, "Selected show:'%s'.", selectedShow->name);
Season* selectedSeason = NULL;
if((error = consoleClient_selectSeason(remoteHost, remotePort, &selectedSeason, selectedShow))){
goto label_return;
}
UTIL_LOG_CONSOLE_(LOG_DEBUG, "Selected season:'%" PRIdFAST16 "'.", selectedSeason->number);
Episode* selectedEpisode = NULL;
if((error = consoleClient_selectEpisode(&selectedEpisode, selectedSeason) != ERROR_NO_ERROR)){
goto label_return;
}
UTIL_LOG_CONSOLE_(LOG_DEBUG, "Selected:[Episode:%" PRIdFAST16 " '%s'].", selectedEpisode->number, selectedEpisode->name);
UTIL_LOG_CONSOLE(LOG_INFO, "Please enter a new episode name.");
char* newEpisodeName;
int_fast64_t newEpisodeNameLength;
if((error = util_readUserInput(&newEpisodeName, &newEpisodeNameLength)) != ERROR_NO_ERROR){
goto label_freeNewName;
}
label_yesNo:
UTIL_LOG_CONSOLE_(LOG_INFO, "Rename '%s', s%02" PRIdFAST16 "e%02" PRIdFAST16 " - '%s' to '%s'? Yes/No.", selectedShow->name, selectedSeason->number, selectedEpisode->number, selectedEpisode->name, newEpisodeName);
bool renameEpisode;
if((error = consoleClient_selectYesNo(&renameEpisode) != ERROR_NO_ERROR)){
goto label_yesNo;
}
if(!renameEpisode){
goto label_freeNewName;
}
EpisodeInfo info;
if((error = mediaLibrary_initEpisodeInfo(&info)) != ERROR_NO_ERROR){
goto label_freeNewName;
}
mediaLibrary_fillEpisodeInfo(&info ,selectedShow, selectedSeason, selectedEpisode);
if((error = herder_renameEpisode(remoteHost, remotePort, libraryDirectory, &info, newEpisodeName, newEpisodeNameLength)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Server side error, failed to rename episode. [%s]", util_toErrorString(error));
goto label_freeNewName;
}
label_freeNewName:
free(newEpisodeName);
mediaLibrary_freeShow(selectedShow);
free(selectedShow);
label_return:
return ERROR(error);
}
local ERROR_CODE consoleClient_renameEpisode(Property* remoteHost, Property* remotePort, Property* libraryDirectory, const char* oldName, const uint_fast64_t oldNameLength, const char* newName, const uint_fast64_t newNameLength){
ERROR_CODE error;
LinkedList shows;
if((error = linkedList_init(&shows)) != ERROR_NO_ERROR){
goto label_return;
}
if((error = herder_pullShowList(&shows, remoteHost, remotePort)) != ERROR_NO_ERROR){
goto label_freeShows;
}
EpisodeInfo info;
if((error = mediaLibrary_initEpisodeInfo(&info)) != ERROR_NO_ERROR){
goto label_freeShows;
}
char* fileName = alloca(sizeof(*fileName) * (oldNameLength + 1));
memcpy(fileName, oldName, oldNameLength + 1);
if((error = mediaLibrary_extractEpisodeInfo(&info, &shows, fileName, oldNameLength)) != ERROR_NO_ERROR){
goto label_freeShows;
}
if((error = herder_renameEpisode(remoteHost, remotePort, libraryDirectory, &info, newName, newNameLength)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Server side error, failed to rename episode. [%s]", util_toErrorString(error));
goto label_freeShows;
}
LinkedListIterator it;
label_freeShows:
linkedList_initIterator(&it, &shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
mediaLibrary_freeShow(show);
free(show);
}
linkedList_free(&shows);
free(info.showName);
free(info.name);
label_return:
return ERROR(error);
}
ERROR_CODE consoleClient_remove(Property* remoteHost, Property* remotePort, Property* libraryDirectory){
ERROR_CODE error = ERROR_NO_ERROR;
Show* selectedShow = NULL;
if((error = consoleClient_selectShow(remoteHost, remotePort, &selectedShow))){
goto label_return;
}
UTIL_LOG_CONSOLE_(LOG_DEBUG, "Selected show:'%s'.", selectedShow->name);
Season* selectedSeason = NULL;
if((error = consoleClient_selectSeason(remoteHost, remotePort, &selectedSeason, selectedShow))){
goto label_return;
}
UTIL_LOG_CONSOLE_(LOG_DEBUG, "Selected season:'%" PRIdFAST16 "'.", selectedSeason->number);
Episode* selectedEpisode = NULL;
if((error = consoleClient_selectEpisode(&selectedEpisode, selectedSeason) != ERROR_NO_ERROR)){
goto label_return;
}
UTIL_LOG_CONSOLE_(LOG_DEBUG, "Selected:[Episode:%" PRIdFAST16 " '%s'].", selectedEpisode->number, selectedEpisode->name);
label_yesNo:
UTIL_LOG_CONSOLE_(LOG_INFO, "Remove '%s', s%02" PRIdFAST16 "e%02" PRIdFAST16 " - '%s' from the library? Yes/No.", selectedShow->name, selectedSeason->number, selectedEpisode->number, selectedEpisode->name);
bool renameEpisode;
if((error = consoleClient_selectYesNo(&renameEpisode) != ERROR_NO_ERROR)){
goto label_yesNo;
}
if(!renameEpisode){
goto label_freeNewName;
}
EpisodeInfo info;
mediaLibrary_initEpisodeInfo(&info);
mediaLibrary_fillEpisodeInfo(&info, selectedShow, selectedSeason, selectedEpisode);
// Send remove packet.
if((error = herder_removeEpisode(remoteHost, remotePort, libraryDirectory, &info)) != ERROR_NO_ERROR){
goto label_freeNewName;
}
label_freeNewName:
mediaLibrary_freeShow(selectedShow);
free(selectedShow);
label_return:
return ERROR(error);
}
local ERROR_CODE consoleClient_removeEpisode(Property* remoteHost, Property* remotePort, Property* libraryDirectory, const char* episodeName, const uint_fast64_t episodeNameLength){
ERROR_CODE error;
LinkedList shows;
if((error = linkedList_init(&shows)) != ERROR_NO_ERROR){
goto label_return;
}
if((error = herder_pullShowList(&shows, remoteHost, remotePort)) != ERROR_NO_ERROR){
goto label_freeShows;
}
EpisodeInfo info;
if((error = mediaLibrary_initEpisodeInfo(&info)) != ERROR_NO_ERROR){
goto label_freeShows;
}
char* fileName = alloca(sizeof(*fileName) * (episodeNameLength + 1));
memcpy(fileName, episodeName, episodeNameLength + 1);
if((error = mediaLibrary_extractEpisodeInfo(&info, &shows, fileName, episodeNameLength)) != ERROR_NO_ERROR){
goto label_freeShows;
}
// Send remove packet.
if((error = herder_removeEpisode(remoteHost, remotePort, libraryDirectory, &info)) != ERROR_NO_ERROR){
goto label_freeShows;
}
LinkedListIterator it;
label_freeShows:
linkedList_initIterator(&it, &shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
mediaLibrary_freeShow(show);
free(show);
}
linkedList_free(&shows);
free(info.showName);
free(info.name);
label_return:
return ERROR(error);
}
local ERROR_CODE consoleClient_selectShow(Property* remoteHost, Property* remotePort, Show** selection){
ERROR_CODE error;
// Pull show list.
LinkedList shows;
if((error = herder_pullShowList(&shows, remoteHost, remotePort)) != ERROR_NO_ERROR){
if(error != ERROR_FAILED_TO_CONNECT){
goto label_freeShowList;
}else{
goto label_return;
}
}
if(shows.length == 0){
UTIL_LOG_CONSOLE(LOG_INFO, "Library is empty.");
error = ERROR_EMPTY_RESPONSE;
goto label_freeShowList;
}
// Print shows.
LinkedListIterator it;
linkedList_initIterator(&it, &shows);
int_fast64_t i = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
UTIL_LOG_CONSOLE_(LOG_INFO, "%02" PRIuFAST64 ":'%s'.", i, show->name);
i++;
}
// Select show.
char* userInput;
int_fast64_t userInputLength;
label_readUserInput:
UTIL_LOG_CONSOLE(LOG_INFO, "\nPlease select a show.");
if((error = util_readUserInput(&userInput, &userInputLength)) != ERROR_NO_ERROR){
goto label_freeShowList;
}
char* showSelection = NULL;
// Differentiate between selection via show name or via position in list.
// TODO: Add a check to see if there are shows with names like '1', '2', etc. (jan - 2020.02.08)
int_fast64_t numberSelection;
if(util_stringToInt(userInput, &numberSelection) != ERROR_NO_ERROR){
showSelection = userInput;
}
if(numberSelection + 1 > (int_fast64_t) shows.length || numberSelection < 0){
UTIL_LOG_CONSOLE(LOG_ERR, "Invalid selection.");
free(userInput);
goto label_readUserInput;
}else{
linkedList_initIterator(&it, &shows);
i = 0;
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
if(numberSelection == i++ && showSelection == NULL){
*selection = show;
break;
}
if(strncmp(userInput, show->name, userInputLength + 1) == 0){
*selection = show;
break;
}
}
}
if(*selection == NULL){
free(userInput);
UTIL_LOG_CONSOLE(LOG_ERR, "Invalid selection.");
goto label_readUserInput;
}
LinkedListIterator showIterator;
label_freeShowList:
linkedList_initIterator(&showIterator, &shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&showIterator)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&showIterator);
if(show != *selection){
mediaLibrary_freeShow(show);
free(show);
}
}
linkedList_free(&shows);
free(userInput);
label_return:
return ERROR(error);
}
local ERROR_CODE consoleClient_selectSeason(Property* remoteHost, Property* remotePort, Season** season, Show* show){
ERROR_CODE error;
if((error = herder_pullShowInfo(remoteHost, remotePort, show)) != ERROR_NO_ERROR){
goto label_return;
}
UTIL_LOG_CONSOLE(LOG_INFO, "Seasons:");
Season** seasons = alloca(sizeof(*seasons) * show->seasons.length);
mediaLibrary_sortSeasons(&seasons, &show->seasons);
uint_fast64_t j;
for(j = 0; j < show->seasons.length; j++){
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%" PRIuFAST16 ".", seasons[j]->number);
}
UTIL_LOG_CONSOLE(LOG_INFO, "Please select a season.");
char* userInput;
int_fast64_t userInputLength;
int_fast64_t selection;
label_selectSeason:
if((error = util_readUserInput(&userInput, &userInputLength)) != ERROR_NO_ERROR){
goto label_return;
}
if(util_stringToInt(userInput, &selection) != ERROR_NO_ERROR){
free(userInput);
goto label_selectSeason;
}
if(selection <= 0 || (uint_fast16_t) selection > UINT_FAST16_MAX){
goto label_invalidUserInput;
}
uint_fast64_t i;
for(i = 0; i < show->seasons.length; i++){
if(seasons[i]->number == (uint_fast16_t) selection){
*season = seasons[i];
goto label_return;
}
}
label_invalidUserInput:
free(userInput);
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid selection.");
goto label_selectSeason;
label_return:
free(userInput);
return ERROR(error);
}
local ERROR_CODE consoleClient_selectEpisode(Episode** episode, Season* season){
ERROR_CODE error;
UTIL_LOG_CONSOLE(LOG_INFO, "Episodes:");
Episode** episodes = alloca(sizeof(*episodes) * season->episodes.length);
mediaLibrary_sortEpisodes(&episodes, &season->episodes);
uint_fast64_t j;
for(j = 0; j < season->episodes.length; j++){
UTIL_LOG_CONSOLE_(LOG_INFO, "\t%" PRIuFAST16 ":'%s'", episodes[j]->number, episodes[j]->name);
}
UTIL_LOG_CONSOLE(LOG_INFO, "Please select an episode.");
char* userInput;
int_fast64_t userInputLength;
int_fast64_t selection;
label_selectSeason:
if((error = util_readUserInput(&userInput, &userInputLength)) != ERROR_NO_ERROR){
goto label_return;
}
if(util_stringToInt(userInput, &selection) != ERROR_NO_ERROR){
free(userInput);
goto label_selectSeason;
}
if(selection <= 0 || (uint_fast16_t) selection > UINT_FAST16_MAX){
goto label_invalidUserInput;
}
uint_fast64_t i;
for(i = 0; i < season->episodes.length; i++){
if(episodes[i]->number == (uint_fast16_t) selection){
*episode = episodes[i];
goto label_return;
}
}
label_invalidUserInput:
free(userInput);
UTIL_LOG_CONSOLE(LOG_INFO, "Invalid selection.");
goto label_selectSeason;
label_return:
free(userInput);
return ERROR(error);
}
local ERROR_CODE consoleClient_selectYesNo(bool* selection){
ERROR_CODE error;
char* userInput;
int_fast64_t userInputLength;
if((error = util_readUserInput(&userInput, &userInputLength)) != ERROR_NO_ERROR){
goto label_freeUserInput;
}
util_toLowerChase(userInput);
if(strncmp(userInput, "no", 3) == 0 || strncmp(userInput, "n", 2) == 0){
*selection = false;
}else{
if(userInputLength != 0 && strncmp(userInput, "yes", 4) != 0 && strncmp(userInput, "y", 2) != 0){
UTIL_LOG_CONSOLE(LOG_DEBUG, "Invalid selection, enter Yes/No to continue.");
error = ERROR_INVALID_VALUE;
}else{
*selection = true;
}
}
label_freeUserInput:
free(userInput);
return ERROR(error);
}
ERROR_CODE consoleClient_addEpisode(Property* remoteHost, Property* remotePort, Property* libraryDirectory, const char* path, const uint_fast64_t pathLength){
ERROR_CODE error;
EpisodeInfo info;
if((error = mediaLibrary_initEpisodeInfo(&info)) != ERROR_NO_ERROR){
goto label_freeInfo;
}
LinkedList shows;
if((error = linkedList_init(&shows)) != ERROR_NO_ERROR){
goto label_freeInfo;
}
if((error = herder_pullShowList(&shows, remoteHost, remotePort)) != ERROR_NO_ERROR){
goto label_freeShowList;
}
info.path = alloca(sizeof(*info.path) * (pathLength + 1));
memcpy(info.path, path, pathLength + 1);
info.pathLength = pathLength;
char* fileName = util_getFileName(info.path, info.pathLength);
const uint_fast64_t fileNameLength = strlen(fileName);
if((error = util_getFileExtension(&info.fileExtension, (uint_fast64_t*) &info.fileExtensionLength, fileName, fileNameLength)) != ERROR_NO_ERROR){
goto label_freeShowList;
}
if((error = consoleClient_extractShowInfo(remoteHost, remotePort, &info, false)) != ERROR_NO_ERROR){
goto label_freeShowList;
}
UTIL_LOG_CONSOLE(LOG_INFO, "Importing:...");
if((error = herder_addEpisode(remoteHost, remotePort, libraryDirectory, &info)) != ERROR_NO_ERROR){
UTIL_LOG_CONSOLE_(LOG_ERR, "Failed to add '%s' to library. [%s]", path, util_toErrorString(error));
}else{
UTIL_LOG_CONSOLE_(LOG_INFO, "Successfully added '%s' to the library.", path);
}
// Free show list.
LinkedListIterator it;
label_freeShowList:
linkedList_initIterator(&it, &shows);
while(LINKED_LIST_ITERATOR_HAS_NEXT(&it)){
Show* show = LINKED_LIST_ITERATOR_NEXT(&it);
mediaLibrary_freeShow(show);
free(show);
}
linkedList_free(&shows);
label_freeInfo:
free(info.showName);
free(info.name);
return ERROR(error);
}
ERROR_CODE consoleClient_convert(Property* remoteHost, Property* remotePort, Property* libraryDirectory){
ERROR_CODE error = ERROR_NO_ERROR;
Show* selectedShow = NULL;
if((error = consoleClient_selectShow(remoteHost, remotePort, &selectedShow))){
goto label_return;
}
UTIL_LOG_CONSOLE_(LOG_DEBUG, "Selected show:'%s'.", selectedShow->name);
label_yesNo:
UTIL_LOG_CONSOLE_(LOG_INFO, "Convert '%s' to audio/mp3? Yes/No.", selectedShow->name);
bool renameEpisode;
if((error = consoleClient_selectYesNo(&renameEpisode) != ERROR_NO_ERROR)){
goto label_yesNo;
}
if(!renameEpisode){
goto label_freeNewName;
}
if((error = herder_convertToMP3(remoteHost, remotePort, libraryDirectory, selectedShow->name, selectedShow->nameLength)) != ERROR_NO_ERROR){
goto label_freeNewName;
}
label_freeNewName:
mediaLibrary_freeShow(selectedShow);
free(selectedShow);
label_return:
return ERROR(error);
}
|
ionelmc/virtualenv
|
tests/functional/testcext/test_cext.c
|
<reponame>ionelmc/virtualenv
#include "Python.h"
static PyObject *hello_world(PyObject *self, PyObject *args) {
return Py_BuildValue("s", "hello, world!");
}
static PyMethodDef module_functions[]={
{"hello_world", hello_world, METH_VARARGS, "Say hello."},
{NULL}
};
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC inittest_cext(void) {
Py_InitModule3("test_cext", module_functions, "Minimal test module.");
}
#else
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"test_cext", /* m_name */
"Minimal test module.", /* m_doc */
-1, /* m_size */
module_functions, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC PyInit_test_cext(void) {
return PyModule_Create(&moduledef);
}
#endif
|
totorigolo/yap
|
examples/calc-with-vars/NamedVariableSymbol.h
|
<filename>examples/calc-with-vars/NamedVariableSymbol.h<gh_stars>0
/*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <YAP/YAP.h>
#include <map>
template<typename Type, YAP::Symbol::Id ValueId, char DebugName = '\0'>
class NamedVariableSymbol : public YAP::Symbol {
public:
static Ptr Create(std::string const& name) {
return Ptr(new NamedVariableSymbol(name));
}
Type GetValue() const {
static std::map<std::string, Type> values;
// Ask for the variable value, once
auto found = values.find(mName);
if (found == values.end()) {
std::cout << "Enter the value of <" << mName << ">: ";
Type value{};
std::cin >> value;
values[mName] = value;
}
return values[mName];
}
protected:
explicit NamedVariableSymbol(std::string name) : Symbol(ValueId), mName{std::move(name)} {}
void print(std::ostream &os) const override {
os << DebugName << "(name=" << mName << ")";
}
private:
std::string mName;
};
|
totorigolo/yap
|
include/YAP/Singleton.h
|
/*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <type_traits>
namespace YAP {
template<typename T>
class Singleton {
protected:
Singleton() noexcept = default;
virtual ~Singleton() = default;
public:
// Forbid move and copy
Singleton(Singleton &&) = delete;
Singleton &operator=(Singleton &&) = delete;
Singleton(const Singleton &) = delete;
Singleton &operator=(const Singleton &) = delete;
public:
inline static T &Instance() noexcept(std::is_nothrow_constructible<T>::value) {
static T instance;
return instance;
}
inline static T *InstancePtr() noexcept(std::is_nothrow_constructible<T>::value) {
return &T::Instance();
}
};
} // namespace YAP
|
totorigolo/yap
|
include/YAP/Lexer.h
|
<filename>include/YAP/Lexer.h
/*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <YAP/Symbol.h>
#include <YAP/TokenRule.h>
#include <regex>
#include <map>
namespace YAP {
class Lexer {
public:
explicit Lexer(std::string &&input);
virtual ~Lexer() = default;
Symbol::Ptr GetNext();
void MoveNext();
template<typename FromStringFunc>
void RegisterToken(char token, FromStringFunc fromStringFunc);
template<typename FromStringFunc>
void RegisterToken(std::regex &®ex, FromStringFunc fromStringFunc);
private:
std::string mInput;
size_t mCursor;
std::vector<TokenRule*> mTokenRules;
size_t mCurrentSymbolSize;
bool mHasNextSymbol;
};
template<typename FromStringFunc>
void Lexer::RegisterToken(char token, FromStringFunc fromStringFunc) {
mTokenRules.push_back(new SimpleTokenRule{
token,
std::move(fromStringFunc)
});
}
template<typename FromStringFunc>
void Lexer::RegisterToken(std::regex &®ex, FromStringFunc fromStringFunc) {
mTokenRules.push_back(new RegexTokenRule{
std::forward<std::regex>(regex),
std::move(fromStringFunc)
});
}
} // namespace YAP
|
totorigolo/yap
|
include/YAP/Transition.h
|
/*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <YAP/Common.h>
#include <YAP/Symbol.h>
#include <YAP/Automaton.h>
#include <YAP/Singleton.h>
#include <functional>
namespace YAP {
class Automaton;
class Transition {
public:
virtual bool operator()(Automaton &automaton, Symbol::Ptr const &symbol) const = 0;
inline bool execute(Automaton &automaton, Symbol::Ptr const &symbol) const {
return operator()(automaton, symbol);
}
};
template<State StateId>
class Shift final : public Transition, public Singleton<Shift<StateId>> {
public:
bool operator()(Automaton &automaton, Symbol::Ptr const &symbol) const override {
automaton.Shift(symbol, StateId);
return true;
}
private:
friend class Singleton<Shift<StateId>>;
Shift() = default;
};
class AcceptTransition final : public Transition, public Singleton<AcceptTransition> {
public:
bool operator()(yap_unused Automaton &automaton, yap_unused Symbol::Ptr const &symbol) const override {
return false;
}
private:
friend class Singleton<AcceptTransition>;
AcceptTransition() = default;
};
class SkipTransition final : public Transition, public Singleton<SkipTransition> {
public:
bool operator()(Automaton &automaton, yap_unused Symbol::Ptr const &symbol) const override {
automaton.MoveNext();
return true;
}
private:
friend class Singleton<SkipTransition>;
SkipTransition() = default;
};
class SkipUnexpectedTransition final : public Transition, public Singleton<SkipUnexpectedTransition> {
public:
bool operator()(Automaton &automaton, Symbol::Ptr const &symbol) const override {
using namespace Colors;
std::cout << bold << yellow << "[Warn] " << reset
<< yellow << "Skipped unexpected token: " << reset << yellow << symbol
<< reset << std::endl;
automaton.MoveNext();
return true;
}
private:
friend class Singleton<SkipUnexpectedTransition>;
SkipUnexpectedTransition() = default;
};
using Reduction = Transition;
#define NEW_REDUCTION(name, action) \
class name : public YAP::Reduction, public YAP::Singleton<name> { /* NOLINT */ \
public: \
bool operator()(YAP::Automaton &automaton, YAP::Symbol::Ptr const &symbol) const override { \
action \
} \
private: \
friend class YAP::Singleton<name>; \
name() = default; \
};
} // namespace YAP
|
totorigolo/yap
|
include/YAP/Symbol.h
|
<reponame>totorigolo/yap<gh_stars>0
/*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <YAP/HasPtr.h>
namespace YAP {
class Symbol : public HasPtr<Symbol> {
public:
using Id = size_t;
/// Symbol ids over 2^16 are reserved
static constexpr Id Eof = 1U + (1U << 15U);
public:
virtual ~Symbol() = default;
Id GetId() const;
friend std::ostream &operator<<(std::ostream &os, const Symbol &symbol);
friend std::ostream &operator<<(std::ostream &os, const Symbol::Ptr &symbolPtr);
protected:
explicit Symbol(Id id);
virtual void print(std::ostream &os) const;
private:
Id mID;
};
} // namespace YAP
|
totorigolo/yap
|
include/YAP/Automaton.h
|
<reponame>totorigolo/yap
/*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <type_traits>
#include <iostream>
#include <cassert>
#include <vector>
#include <array>
#include <tuple>
#include <map>
#include <YAP/Lexer.h>
#include <YAP/State.h>
#include <YAP/State.h>
#include <YAP/Common.h>
namespace YAP {
class Symbol;
class Transition;
class Automaton;
class TransitionAdder {
public:
template<typename Transition>
inline TransitionAdder &Add(State state, Symbol::Id symbol);
inline TransitionAdder &Add(State fromState, Symbol::Id fromSymbol, State toState);
private:
friend class Automaton;
explicit TransitionAdder(Automaton &automaton) : mAutomaton{automaton} {}
private:
Automaton &mAutomaton;
};
class Automaton {
public:
explicit Automaton(Lexer lexer, bool debug = false);
virtual ~Automaton() = default;
Symbol::Ptr Read(State rootState = State(0));
template<typename Transition>
void AddTransition(State state, Symbol::Id symbol);
TransitionAdder AddTransitions();
void AddGoToTransition(State fromState, Symbol::Id fromSymbol, State toState);
void Shift(Symbol::Ptr symbol, State state);
void Reduce(int n, Symbol::Ptr symbol);
void MoveNext();
void PopSymbol();
template<typename SymbolType, bool Assert = true>
auto PopSymbolAs();
void DebugStacks() const;
private:
bool executeTransition(Symbol::Ptr symbol);
private:
std::vector<Symbol::Ptr> mSymbolsStack;
std::vector<State> mStatesStack;
Lexer mLexer;
bool mDebug;
using StateTransitions = std::map<Symbol::Id, Transition const *>;
using TransitionTable = std::map<State, StateTransitions>;
TransitionTable transitions;
using SymbolTransitions = std::map<Symbol::Id, State>;
using GotoTransitions = std::map<State, SymbolTransitions>;
GotoTransitions goToTransitions;
};
template<class TransitionClass>
void Automaton::AddTransition(State state, Symbol::Id symbol) {
static_assert(
std::is_base_of<Transition, TransitionClass>::value,
"TransitionClass must be a child of Transition."
);
transitions[state][symbol] = TransitionClass::InstancePtr();
}
template<typename SymbolType, bool Assert = true>
auto Automaton::PopSymbolAs() {
static_assert(
std::is_base_of<Symbol, SymbolType>::value,
"SymbolType must be a child of Symbol!"
);
// TODO: Use a Result class
assert(!mSymbolsStack.empty() && "Can't pop as the stack is empty.");
Symbol::Ptr s = mSymbolsStack.back();
mSymbolsStack.pop_back();
auto r = std::dynamic_pointer_cast<SymbolType>(s);
if constexpr (Assert) {
assert(r && "The popped symbol is of wrong type!");
}
return r;
}
template<typename Transition>
TransitionAdder &TransitionAdder::Add(State state, Symbol::Id symbol) {
mAutomaton.AddTransition<Transition>(state, symbol);
return *this;
}
TransitionAdder &TransitionAdder::Add(State fromState, Symbol::Id fromSymbol, State toState) {
mAutomaton.AddGoToTransition(fromState, fromSymbol, toState);
return *this;
}
} // namespace YAP
|
totorigolo/yap
|
examples/simple/Transitions.h
|
/*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include "Symbols.h"
#include <YAP/YAP.h>
#include <iostream>
namespace Shifts {
using YAP::Shift;
using YAP::State;
using d2 = Shift<State(2)>;
using d3 = Shift<State(3)>;
using d4 = Shift<State(4)>;
using d5 = Shift<State(5)>;
using d9 = Shift<State(9)>;
}
namespace Reductions {
// E -> E + E
NEW_REDUCTION(r2, {
YAP_UNUSED(symbol);
auto const e1 = automaton.PopSymbolAs<Expr>();
automaton.PopSymbol();
auto const e3 = automaton.PopSymbolAs<Expr>();
auto result = Expr::Create(e1->GetValue() + e3->GetValue());
automaton.Reduce(3, result);
return true;
})
// E -> E * E
NEW_REDUCTION(r3, {
YAP_UNUSED(symbol);
auto const e1 = automaton.PopSymbolAs<Expr>();
automaton.PopSymbol();
auto const e3 = automaton.PopSymbolAs<Expr>();
auto result = Expr::Create(e1->GetValue() * e3->GetValue());
automaton.Reduce(3, result);
return true;
})
// E -> ( E )
NEW_REDUCTION(r4, {
YAP_UNUSED(symbol);
automaton.PopSymbol();
auto const e2 = automaton.PopSymbolAs<Expr>();
automaton.PopSymbol();
automaton.Reduce(3, Expr::Create(e2->GetValue()));
return true;
})
// E -> val
NEW_REDUCTION(r5, {
YAP_UNUSED(symbol);
auto const v = automaton.PopSymbolAs<Val>();
automaton.Reduce(1, Expr::Create(v->GetValue()));
return true;
})
}
|
totorigolo/yap
|
include/YAP/TokenRule.h
|
/*
* MIT License
*
* Copyright (c) 2018 insa.4if.hexanome_kalate
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <YAP/Symbol.h>
#include <regex>
#include <utility>
namespace YAP {
class TokenRule {
public:
TokenRule() = default;
virtual ~TokenRule() = default;
virtual bool Match(char currentChar) const = 0;
virtual Symbol::Ptr GetSymbol(const std::string& str) const = 0;
virtual bool IsSingleChar() const = 0;
};
template<typename FromStringFunc>
class SimpleTokenRule : public TokenRule {
public:
explicit SimpleTokenRule(char character, FromStringFunc fromStringFunc)
: mChar{character},
mFromStringFunc{fromStringFunc} {
static_assert(
std::is_invocable<FromStringFunc, std::string const&>::value
|| std::is_invocable<FromStringFunc>::value,
"FromStringFunc must be a function that either turns a string into a symbol or takes no argument."
);
}
bool Match(char currentChar) const override {
return currentChar == mChar;
}
Symbol::Ptr GetSymbol(const std::string& str) const override {
if constexpr (std::is_invocable<FromStringFunc, std::string const&>::value) {
return mFromStringFunc(str);
} else {
return mFromStringFunc();
}
}
bool IsSingleChar() const override {
return true;
}
private:
char mChar;
FromStringFunc mFromStringFunc;
};
template<typename FromStringFunc>
class RegexTokenRule : public TokenRule {
public:
explicit RegexTokenRule(std::regex &®ex, FromStringFunc fromStringFunc)
: mRegex{std::move(regex)},
mFromStringFunc{fromStringFunc} {
static_assert(
std::is_invocable<FromStringFunc, std::string const&>::value
|| std::is_invocable<FromStringFunc>::value,
"FromStringFunc must be a function that either turns a string into a symbol or takes no argument."
);
}
bool Match(char currentChar) const override {
return std::regex_match(std::string(1, currentChar), mRegex) != 0;
}
Symbol::Ptr GetSymbol(const std::string& str) const override {
if constexpr (std::is_invocable<FromStringFunc, std::string const&>::value) {
return mFromStringFunc(str);
} else {
return mFromStringFunc();
}
}
bool IsSingleChar() const override {
return false;
}
private:
std::regex mRegex;
FromStringFunc mFromStringFunc;
};
} // namespace YAP
|
StateFromJakeFarm/ascii3d
|
frame.h
|
/**
* @file frame.h
* @author <NAME>
*
* Header for Frame class to render player's view within terminal emulator using
* ASCII characters.
*/
#ifndef FRAME_H
#define FRAME_H
#include <vector>
#include <string>
#include <utility>
#include <omp.h>
#include "game_map.h"
#include "player.h"
using std::vector;
using std::pair;
class Frame {
private:
GameMap *game_map_ptr;
Player *player_ptr;
bool is_corner(const double, const double);
public:
int screen_rows, screen_cols, render_dist;
double corner_resolution;
vector<wchar_t*> picture;
Frame(GameMap*, Player*, int, int, int, double);
~Frame();
void render();
};
#endif
|
StateFromJakeFarm/ascii3d
|
player.h
|
/**
* @file player.h
* @author <NAME>
*
* Header for Player class to record player's orientation and movement
* information.
*/
#ifndef PLAYER_H
#define PLAYER_H
#include <cmath>
#include "game_map.h"
class Player {
private:
GameMap *game_map_ptr;
double x, y, view_angle;
double fov, walk_speed, turn_speed;
public:
// Player movement
Player(GameMap*, double, double, double, double, double, double);
void turn_right();
void turn_left();
void walk_forward();
void walk_backward();
void strafe_right();
void strafe_left();
// Getters
double get_x() {return x;}
double get_y() {return y;}
double get_view() {return view_angle;}
double get_fov() {return fov;}
};
#endif
|
StateFromJakeFarm/ascii3d
|
game_map.h
|
<reponame>StateFromJakeFarm/ascii3d
/**
* @file game_map.h
* @author <NAME>
*
* Header for GameMap class to maintain positions of obstacles in the
* environment.
*/
#ifndef GAME_MAP_H
#define GAME_MAP_H
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
using std::string;
using std::ifstream;
using std::getline;
using std::vector;
using std::cerr;
using std::endl;
class GameMap {
private:
vector<string> map;
int height;
int width;
public:
GameMap(string);
// Getters
int get_height() {return height;}
int get_width() {return width;}
char at(const int, const int);
};
#endif
|
manageryzy/ac_types_plus
|
include/ac_channel.h
|
<gh_stars>0
/**************************************************************************
* *
* Algorithmic C (tm) Datatypes *
* *
* Software Version: 3.7 *
* *
* Release Date : Tue May 30 14:25:58 PDT 2017 *
* Release Type : Production Release *
* Release Build : 3.7.2 *
* *
* Copyright 2004-2014, Mentor Graphics Corporation, *
* *
* All Rights Reserved. *
*
**************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
**************************************************************************
* *
* The most recent version of this package is available at github. *
* *
*************************************************************************/
/*
// Source: ac_channel.h
// Description: templatized channel communication class
// Author: <NAME>, Ph.D.
*/
#ifndef __AC_CHANNEL_H
#define __AC_CHANNEL_H
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#ifndef __SYNTHESIS__
#include <deque>
#include <string>
#include <algorithm>
#endif
// Macro Definitions (obsolete - provided here for backward compatibility)
#define AC_CHAN_CTOR(varname) varname
#define AC_CHAN_CTOR_INIT(varname,init) varname(init)
#define AC_CHAN_CTOR_VAL(varname,init,val) varname(init,val)
///////////////////////////////////////////
// Class: ac_channel
//////////////////////////////////////////
template <class T>
class ac_channel:public ac_base_type
{
public:
struct is_ac_basic_type : std::conditional_t<is_ac_type<T>::value, typename T::is_ac_basic_type, std::false_type> {};
T read();
void read(T& t) ;
void write(const T& t);
// constructors
ac_channel();
ac_channel(int init);
ac_channel(int init, T val);
bool available(unsigned int k); // Return true if channel has at least k entries
unsigned int size();
bool empty() {return size() == 0;}
unsigned int debug_size() {
#ifndef __SYNTHESIS__
return chan.size();
#endif
}
T operator[](unsigned int pos) const {
#ifndef __SYNTHESIS__
return chan[pos];
#endif
}
#ifndef __SYNTHESIS__
// These functions are useful for writing the testbench and the
// scverify flow but are not supported for synthesis.
bool operator==(const ac_channel &rhs) const { return this->chan == rhs.chan; }
bool operator!=(const ac_channel &rhs) const { return !operator==(rhs); }
void reset() {chan.clear(); for (int i=0; i<(int)rSz; i++) write(rVal);}
bool nb_read(T& t) {
if (size() != 0) {
read(t);
return true;
} else return false;
}
int get_size_call_count() { int tmp=size_call_count; size_call_count=0; return tmp; }
// data - The verifcation flow needs it to be public
std::deque<T> chan;
#else
// for synthesis
bool nb_read(T& t);
private:
// Prevent the compiler from autogenerating these. (This enforces that channels are always passed by
// reference.)
ac_channel(const ac_channel< T >&);
ac_channel& operator=(const ac_channel< T >&);
#endif
private:
// data
#ifndef __SYNTHESIS__
unsigned int rSz; // reset size
T rVal; // resetValue
int size_call_count;
#else
T chan;
#endif
};
// constructors with no name ID
template <class T>
ac_channel<T>::ac_channel()
#ifndef __SYNTHESIS__
: rSz(0)
, size_call_count(0)
#endif
{}
// Default for types we don't know about
template <class T>
ac_channel<T>::ac_channel(int init)
#ifndef __SYNTHESIS__
: rSz(init)
, size_call_count(0)
#endif
{
for (int i=init; i> 0; i--) {
T dc;
write(dc);
}
}
template <class T>
ac_channel<T>::ac_channel(int init, T val)
#ifndef __SYNTHESIS__
: rSz(init)
, rVal(val)
, size_call_count(0)
#endif
{
for (int i=init; i> 0; i--)
write(val);
}
//The actual hardware looks very much like the SYNTHESIS model.
// The 2 and 3 argument CTORs store the size arg
// in an integer variable similar to rSz. The allows us to use a FIFO length which is
// independent of the startup time of the design.
template <class T>
T ac_channel<T>::read()
{
#ifndef __SYNTHESIS__
if (chan.empty()) {
std::cout << "Read from empty channel" << std::endl;
abort();
}
T t= chan.front();
chan.pop_front();
return t;
#else
// this is non-sense (doesn't get used, right?)
T dc;
unsigned int chan_rSz = 0;
if (chan_rSz == 0) {
return chan;
} else {
chan_rSz--;
return dc;
}
#endif
}
template <class T>
void ac_channel<T>::read(T& t)
{
t = read();
}
template <class T>
void ac_channel<T>::write(const T& t)
{
#ifndef __SYNTHESIS__
chan.push_back(t);
#endif
}
template <class T>
unsigned int ac_channel<T>::size()
{
#ifndef __SYNTHESIS__
size_call_count++;
return (int)chan.size();
#endif
}
template <class T>
bool ac_channel<T>::available(unsigned int k)
{
#ifndef __SYNTHESIS__
return chan.size() >= k;
#endif
}
template<class T>
inline std::ostream& operator<< (std::ostream& os, ac_channel<T> &a)
{
#ifndef __SYNTHESIS__
for (unsigned int i=0; i<a.size(); i++) {
if (i > 0) os << " ";
os << a[i];
}
#endif
return os;
}
#endif
|
manageryzy/ac_types_plus
|
include/ac_float.h
|
/**************************************************************************
* *
* Algorithmic C (tm) Datatypes *
* *
* Software Version: 3.7 *
* *
* Release Date : Tue May 30 14:25:58 PDT 2017 *
* Release Type : Production Release *
* Release Build : 3.7.2 *
* *
* Copyright 2013-2016, Mentor Graphics Corporation, *
* *
* All Rights Reserved. *
*
**************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
**************************************************************************
* *
* The most recent version of this package is available at github. *
* *
*************************************************************************/
// Source: ac_float.h
// Description: class for floating point operation handling in C++
// Author: <NAME>, Ph.D.
#ifndef __AC_FLOAT_H
#define __AC_FLOAT_H
#include <ac_fixed.h>
#ifndef __SYNTHESIS__
#include <cmath>
#endif
#if (defined(__GNUC__) && __GNUC__ < 3 && !defined(__EDG__))
#error GCC version 3 or greater is required to include this header file
#endif
#if (defined(_MSC_VER) && _MSC_VER < 1400 && !defined(__EDG__))
#error Microsoft Visual Studio 8 or newer is required to include this header file
#endif
#if (defined(_MSC_VER) && !defined(__EDG__))
#pragma warning( push )
#pragma warning( disable: 4003 4127 4308 4365 4514 4800 )
#endif
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wparentheses"
#pragma clang diagnostic ignored "-Wlogical-op-parentheses"
#pragma clang diagnostic ignored "-Wbitwise-op-parentheses"
#endif
// for safety
#if (defined(E) || defined(WF) || defined(IF) || defined(SF))
#error One or more of the following is defined: E, WF, IF, SF. Definition conflicts with their usage as template parameters.
#error DO NOT use defines before including third party header files.
#endif
#define AC_FL(v) ac_float<W##v,I##v,E##v,Q##v>
#define AC_FL0(v) ac_float<W##v,I##v,E##v>
#define AC_FL_T(v) int W##v, int I##v, int E##v, ac_q_mode Q##v
#define AC_FL_TV(v) W##v, I##v, E##v, Q##v
#define AC_FL_T0(v) int W##v, int I##v, int E##v
#define AC_FL_TV0(v) W##v, I##v, E##v
#ifdef __AC_NAMESPACE
namespace __AC_NAMESPACE {
#endif
template<int W, int I, int E, ac_q_mode Q=AC_TRN> class ac_float;
namespace ac_private {
typedef ac_float<54,2,11> ac_float_cdouble_t;
typedef ac_float<25,2,8> ac_float_cfloat_t;
template<typename T>
struct rt_ac_float_T {
template< AC_FL_T0() >
struct op1 {
typedef AC_FL0() fl_t;
typedef typename T::template rt_T<fl_t>::mult mult;
typedef typename T::template rt_T<fl_t>::plus plus;
typedef typename T::template rt_T<fl_t>::minus2 minus;
typedef typename T::template rt_T<fl_t>::minus minus2;
typedef typename T::template rt_T<fl_t>::logic logic;
typedef typename T::template rt_T<fl_t>::div2 div;
typedef typename T::template rt_T<fl_t>::div div2;
};
};
// specializations after definition of ac_float
inline ac_float_cdouble_t double_to_ac_float(double d);
inline ac_float_cfloat_t float_to_ac_float(float f);
}
//////////////////////////////////////////////////////////////////////////////
// ac_float
//////////////////////////////////////////////////////////////////////////////
template< AC_FL_T() >
class ac_float:public ac_base_type {
enum { NO_UN = true, S = true, S2 = true, SR = true };
public:
typedef ac_fixed<W,I,S> mant_t;
typedef ac_int<E,true> exp_t;
mant_t m;
exp_t e;
void set_mantissa(const ac_fixed<W,I,S> &man) { m = man; }
void set_exp(const ac_int<E,true> &exp) { if(E) e = exp; }
private:
inline bool is_neg() const { return m < 0; } // is_neg would be more efficient
enum {NZ_E = !!E, MIN_EXP = (unsigned int)(-NZ_E) << (E-NZ_E), MAX_EXP = (1 << (E-NZ_E))-1};
public:
static const int width = W;
static const int i_width = I;
static const int e_width = E;
static const bool sign = S;
static const ac_q_mode q_mode = Q;
static const ac_o_mode o_mode = AC_SAT;
struct is_ac_basic_type : std::false_type {};
template< AC_FL_T0(2) >
struct rt {
enum {
// need to validate
F=W-I,
F2=W2-I2,
mult_w = W+W2,
mult_i = I+I2,
mult_e = AC_MAX(E,E2)+1,
mult_s = S||S2,
plus_w = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+1+AC_MAX(F,F2),
plus_i = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+1,
plus_e = AC_MAX(E,E2),
plus_s = S||S2,
minus_w = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+1+AC_MAX(F,F2),
minus_i = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+1,
minus_e = AC_MAX(E,E2),
minus_s = true,
div_w = W+AC_MAX(W2-I2,0)+S2,
div_i = I+(W2-I2)+S2,
div_e = AC_MAX(E,E2)+1,
div_s = S||S2,
logic_w = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+AC_MAX(F,F2),
logic_i = AC_MAX(I+(S2&&!S),I2+(S&&!S2)),
logic_s = S||S2,
logic_e = AC_MAX(E,E2)
};
typedef ac_float<mult_w, mult_i, mult_e> mult;
typedef ac_float<plus_w, plus_i, plus_e> plus;
typedef ac_float<minus_w, minus_i, minus_e> minus;
typedef ac_float<logic_w, logic_i, logic_e> logic;
typedef ac_float<div_w, div_i, div_e> div;
typedef ac_float arg1;
};
template<int WI, bool SI>
struct rt_i {
enum {
lshift_w = W,
lshift_i = I,
lshift_s = S,
lshift_e_0 = exp_t::template rt<WI,SI>::plus::width,
lshift_e = AC_MIN(lshift_e_0, 24),
rshift_w = W,
rshift_i = I,
rshift_s = S,
rshift_e_0 = exp_t::template rt<WI,SI>::minus::width,
rshift_e = AC_MIN(rshift_e_0, 24)
};
typedef ac_float<lshift_w, lshift_i, lshift_e> lshift;
typedef ac_float<rshift_w, rshift_i, rshift_e> rshift;
};
template<typename T>
struct rt_T {
typedef typename ac_private::map<T>::t map_T;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::mult mult;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::plus plus;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::minus minus;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::minus2 minus2;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::logic logic;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::div div;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::div2 div2;
typedef ac_float arg1;
};
template<typename T>
struct rt_T2 {
typedef typename ac_private::map<T>::t map_T;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::mult mult;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::plus plus;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::minus2 minus;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::minus minus2;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::logic logic;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::div2 div;
typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::div div2;
typedef ac_float arg1;
};
struct rt_unary {
enum {
neg_w = W+1,
neg_i = I+1,
neg_e = E,
neg_s = true,
mag_sqr_w = 2*W-S + NO_UN,
mag_sqr_i = 2*I-S + NO_UN,
mag_sqr_e = E,
mag_sqr_s = false | NO_UN,
mag_w = W+S + NO_UN,
mag_i = I+S + NO_UN,
mag_e = E,
mag_s = false | NO_UN,
to_fx_i = I + MAX_EXP,
to_fx_w = W + MAX_EXP - MIN_EXP,
to_fx_s = S,
to_i_w = AC_MAX(to_fx_i,1),
to_i_s = S
};
typedef ac_float<neg_w, neg_i, neg_e> neg;
typedef ac_float<mag_sqr_w, mag_sqr_i, mag_sqr_e> mag_sqr;
typedef ac_float<mag_w, mag_i, mag_e> mag;
template<unsigned N>
struct set {
enum { sum_w = W + ac::log2_ceil<N>::val, sum_i = (sum_w-W) + I, sum_e = E, sum_s = S};
typedef ac_float<sum_w, sum_i, sum_e> sum;
};
typedef ac_fixed<to_fx_w, to_fx_i, to_fx_s> to_ac_fixed_t;
typedef ac_int<to_i_w, to_i_s> to_ac_int_t;
};
template<AC_FL_T(2)> friend class ac_float;
ac_float() {
#if defined(AC_DEFAULT_IN_RANGE)
#endif
}
ac_float(const ac_float &op) {
m = op.m;
e = op.e;
}
template<AC_FL_T(2)>
ac_float(const AC_FL(2) &op, bool assert_on_overflow=false, bool assert_on_rounding=false) {
typedef AC_FL(2) fl2_t;
enum {
ST2 = S|S2, WT2 = W2+(!S2&S), IT2 = I2+(!S2&S),
RND = Q!=AC_TRN & Q!=AC_TRN_ZERO & WT2 > W,
MAX_EXP2 = fl2_t::MAX_EXP, MIN_EXP2 = fl2_t::MIN_EXP,
I_DIFF = IT2-I,
MAX_EXP_T = MAX_EXP2 + I_DIFF + RND, MIN_EXP_T = MIN_EXP2 + I_DIFF,
MAX_EXP_T_P = MAX_EXP_T < 0 ? ~ MAX_EXP_T : MAX_EXP_T,
MIN_EXP_T_P = MIN_EXP_T < 0 ? ~ MIN_EXP_T : MIN_EXP_T,
WC_EXP_T = AC_MAX(MAX_EXP_T_P, MIN_EXP_T_P),
ET = ac::template nbits<WC_EXP_T>::val + 1 };
typedef ac_fixed<WT2,IT2,ST2> fx2_t;
typedef ac_fixed<WT2,I,S> fx_t;
fx2_t m2 = op.m;
fx_t t;
t.set_slc(0, m2.template slc<fx_t::width>(0));
ac_fixed<W+RND,I+RND,S,Q> m_1 = t;
bool rnd_ovfl = false;
if(RND) {
rnd_ovfl = !m_1[W] & m_1[W-1];
m_1[W-1] = m_1[W-1] & !rnd_ovfl;
m_1[W-2] = m_1[W-2] | rnd_ovfl;
}
m.set_slc(0, m_1.template slc<W>(0));
if(fx_t::width > W && assert_on_rounding)
AC_ASSERT(m == t, "Loss of precision due to Rounding in ac_float constructor");
ac_int<ET,true> exp = !m ? ac_int<ET,true> (0) :
ac_int<ET,true> (op.e + I_DIFF + (RND & rnd_ovfl));
adjust(exp, false, assert_on_overflow);
}
ac_float(const ac_fixed<W,I,S> &m2, const ac_int<E,true> &e2, bool normalize=true) {
m = m2;
if(E) {
if(!m)
e = 0;
else {
e = e2;
if(normalize)
m.normalize(e);
}
}
}
template<int WFX, int IFX, bool SFX, int E2>
ac_float(const ac_fixed<WFX,IFX,SFX> &m2, const ac_int<E2,true> &e2, bool normalize=true) {
enum { WF2 = WFX+!SFX, IF2 = IFX+!SFX };
ac_float<WF2,IF2,E2> f(ac_fixed<WF2,IF2,true>(m2), e2, normalize);
*this = f;
}
template<int WFX, int IFX, bool SFX, ac_q_mode QFX, ac_o_mode OFX>
ac_float(const ac_fixed<WFX,IFX,SFX,QFX,OFX> &op, bool normalize=true) {
enum {
U2S = !SFX,
WT2 = WFX+U2S, IT2 = IFX+U2S,
RND = QFX!=AC_TRN & QFX!=AC_TRN_ZERO & WT2 > W,
I_DIFF = IT2-I,
MAX_EXP_T = -(I_DIFF + RND), MIN_EXP_T = AC_MAX(MIN_EXP - I_DIFF, -WT2+1),
MAX_EXP_T_P = MAX_EXP_T < 0 ? ~ MAX_EXP_T : MAX_EXP_T,
MIN_EXP_T_P = MIN_EXP_T < 0 ? ~ MIN_EXP_T : MIN_EXP_T,
WC_EXP_T = AC_MAX(MAX_EXP_T_P, MIN_EXP_T_P),
ET = ac::template nbits<WC_EXP_T>::val + 1
};
ac_float<WT2,IT2,ET> f(op, ac_int<ET,true>(0), normalize);
*this = f;
}
template<int WI, bool SI>
ac_float(const ac_int<WI,SI> &op) {
*this = ac_fixed<WI,WI,SI>(op);
}
inline ac_float( bool b ) { *this = (ac_int<1,false>) b; }
inline ac_float( char b ) { *this = (ac_int<8,true>) b; }
inline ac_float( signed char b ) { *this = (ac_int<8,true>) b; }
inline ac_float( unsigned char b ) { *this = (ac_int<8,false>) b; }
inline ac_float( signed short b ) { *this = (ac_int<16,true>) b; }
inline ac_float( unsigned short b ) { *this = (ac_int<16,false>) b; }
inline ac_float( signed int b ) { *this = (ac_int<32,true>) b; }
inline ac_float( unsigned int b ) { *this = (ac_int<32,false>) b; }
inline ac_float( signed long b ) { *this = (ac_int<ac_private::long_w,true>) b; }
inline ac_float( unsigned long b ) { *this = (ac_int<ac_private::long_w,false>) b; }
inline ac_float( Slong b ) { *this = (ac_int<64,true>) b; }
inline ac_float( Ulong b ) { *this = (ac_int<64,false>) b; }
// Explicit conversion functions to ac_int and ac_fixed
inline typename rt_unary::to_ac_fixed_t to_ac_fixed() const {
typename rt_unary::to_ac_fixed_t r = m;
r <<= e;
return r;
}
inline typename rt_unary::to_ac_int_t to_ac_int() const {
return to_ac_fixed().to_ac_int();
}
// Explicit conversion functions to C built-in types -------------
inline int to_int() const { return to_ac_int().to_int(); }
inline unsigned to_uint() const { return to_ac_int().to_uint(); }
inline long to_long() const { return (signed long) to_ac_int().to_int64(); }
inline unsigned long to_ulong() const { return (unsigned long) to_ac_int().to_uint64(); }
inline Slong to_int64() const { return to_ac_int().to_int64(); }
inline Ulong to_uint64() const { return to_ac_int().to_uint64(); }
inline float to_float() const { return ldexpf(m.to_double(), exp()); }
inline double to_double() const { return ldexp(m.to_double(), exp()); }
const ac_fixed<W,I,S> mantissa() const { return m; }
const ac_int<E,true> exp() const { return e; }
bool normalize() {
bool normalized = operator !() || !S && m[W-1] || S && (m[W-1] ^ m[W-2]);
if(E && !normalized)
normalized = m.normalize(e);
return normalized;
}
template <int ET>
void adjust(ac_int<ET,true> new_e, bool normalize, bool assert_on_overflow) {
if(E >= ET) {
e = new_e;
if(E && normalize)
m.normalize(e);
} else {
ac_int<E,false> offset = 0;
offset[E-1] = 1;
ac_int<ET+1,true> e_s = new_e + offset;
if(e_s < 0) {
m >>= (MIN_EXP - new_e); // can a full barrel-shifter be avoided ???
e = MIN_EXP;
} else {
// break down: bits( (1<<E) -1 + W-1 ) + 1 is max bit for normalization
// other bits can be tested separetely
ac_int<ET,false> e_u = e_s;
if(ET && normalize)
m.normalize(e_u);
e_u -= offset;
if(e_u[ET-1] | !(e_u >> (E-1))) // what about E == 0 or ET == 0 ???
e = e_u;
else {
e = MAX_EXP;
m = m < 0 ? value<AC_VAL_MIN>(m) : value<AC_VAL_MAX>(m);
if(assert_on_overflow)
AC_ASSERT(0, "OVERFLOW ON ASSIGNMENT TO AC_FLOAT");
}
}
}
}
ac_float( double d, bool assert_on_overflow=false, bool assert_on_rounding=false ) {
enum { I_EXT = AC_MAX(I,1), W_EXT = ac_private::ac_float_cdouble_t::width + I_EXT - 1, };
ac_private::ac_float_cdouble_t t = ac_private::double_to_ac_float(d);
ac_float r(t, assert_on_overflow, assert_on_rounding);
*this = r;
}
ac_float( float f, bool assert_on_overflow=false, bool assert_on_rounding=false ) {
enum { I_EXT = AC_MAX(I,1), W_EXT = ac_private::ac_float_cfloat_t::width + I_EXT - 1, };
ac_private::ac_float_cfloat_t t = ac_private::float_to_ac_float(f);
ac_float r(t, assert_on_overflow, assert_on_rounding);
*this = r;
}
template<AC_FL_T(2)>
typename rt< AC_FL_TV0(2) >::mult operator *(const AC_FL(2) &op2) const {
typename rt< AC_FL_TV0(2) >::mult r(m*op2.m, exp()+op2.exp(), false);
return r;
}
template<AC_FL_T(2)>
bool compare(const AC_FL(2) &op2, bool *gt) const {
typedef ac_fixed<W2,I,S2> fx2_t;
typedef typename ac_fixed<W,I,S>::template rt_T< fx2_t >::logic fx_t;
typedef ac_fixed<fx_t::width,fx_t::i_width,false> fxu_t;
fx2_t op2_m_0;
op2_m_0.set_slc(0, op2.m.template slc<W2>(0));
fx_t op1_m = m;
fx_t op2_m = op2_m_0;
int e_dif = exp() - op2.exp() + I - I2;
bool op2_m_neg = op2_m[fx_t::width-1];
fx_t out_bits = op2_m ^ ((op2_m_neg & e_dif < 0) ? ~fx_t(0) : fx_t(0));
out_bits &= ~(fxu_t(~fxu_t(0)) << e_dif);
op2_m >>= e_dif;
bool overflow = e_dif < 0 & !!out_bits | op2_m_neg ^ op2_m[fx_t::width-1];
*gt = overflow & op2_m_neg | !overflow & op1_m > op2_m;
bool eq = op1_m == op2_m & !overflow & !out_bits;
return eq;
}
template<AC_FL_T(2), AC_FL_T(R)>
void plus_minus(const AC_FL(2) &op2, AC_FL(R) &r, bool sub=false) const {
typedef AC_FL(R) r_type;
enum { IT = AC_MAX(I,I2) };
typedef ac_fixed<W, IT, S> fx1_t;
typedef ac_fixed<W2, IT, S2> fx2_t;
typedef typename fx1_t::template rt_T< ac_fixed<WR,IT,SR> >::logic fx1t_t;
typedef typename fx2_t::template rt_T< ac_fixed<WR,IT,SR> >::logic fx2t_t;
typedef typename fx1t_t::template rt_T<fx2t_t>::plus mt_t;
typedef ac_fixed<mt_t::width+1,mt_t::i_width,SR> t1_t;
typedef ac_fixed<mt_t::width+2,mt_t::i_width,SR> t2_t;
typedef ac_fixed<t2_t::width,IR,SR> r1_t;
enum { MAX_EXP2 = AC_FL(2)::MAX_EXP, MIN_EXP2 = AC_FL(2)::MIN_EXP,
I_DIFF = mt_t::i_width - IR,
MAX_EXP_T = AC_MAX(MAX_EXP, MAX_EXP2) + I_DIFF,
MIN_EXP_T = AC_MIN(MIN_EXP, MIN_EXP2) + I_DIFF,
MAX_EXP_T_P = MAX_EXP_T < 0 ? ~ MAX_EXP_T : MAX_EXP_T,
MIN_EXP_T_P = MIN_EXP_T < 0 ? ~ MIN_EXP_T : MIN_EXP_T,
WC_EXP_T = AC_MAX(MAX_EXP_T_P, MIN_EXP_T_P),
ET = ac::template nbits<WC_EXP_T>::val + 1 };
ac_fixed<mt_t::width, I+1, mt_t::sign> op1_m_0 = m;
mt_t op1_m = 0;
op1_m.set_slc(0, op1_m_0.template slc<mt_t::width>(0));
int op1_e = exp() + I-IT + (SR&!S);
ac_fixed<mt_t::width, I2+1, mt_t::sign> op2_m_0 = op2.m;
mt_t op2_m = 0;
op2_m.set_slc(0, op2_m_0.template slc<mt_t::width>(0));
if(sub)
op2_m = -op2_m;
int op2_e = op2.exp() + I2-IT + (SR&!S2);
bool op1_zero = operator !();
bool op2_zero = !op2;
int e_dif = op1_e - op2_e;
bool e1_lt_e2 = e_dif < 0;
e_dif = (op1_zero | op2_zero) ? 0 : e1_lt_e2 ? -e_dif : e_dif;
mt_t op_sl = e1_lt_e2 ? op1_m : op2_m;
// Sticky bits are bits shifted out, leaving out the MSB
mt_t sticky_bits = op_sl;
sticky_bits &= ~((~t1_t(0)) << e_dif);
bool sticky_bit = !!sticky_bits;
bool msb_shifted_out = (bool) t1_t(op_sl).template slc<1>(e_dif);
op_sl >>= e_dif;
op1_m = e1_lt_e2 ? op_sl : op1_m;
op2_m = e1_lt_e2 ? op2_m : op_sl;
t1_t t1 = op1_m;
t1 += op2_m;
t1[0] = msb_shifted_out;
bool shift_r_1 = false; //t1[t1_t::width-1] != t1[t1_t::width-2];
sticky_bit |= shift_r_1 & t1[0];
t1 >>= shift_r_1;
t2_t t2 = t1;
t2[0] = sticky_bit;
r1_t r1;
r1.set_slc(0, t2.template slc<t2_t::width>(0));
r_type r_t;
r_t.m = (ac_fixed<WR,IR,SR,QR>) r1; // t2; This could overflow if !SR&ST
ac_int<ET,true> r_e = op1_zero ? op2_e : (op2_zero ? op1_e : AC_MAX(op1_e, op2_e));
r_e = ac_int<1,true>(!op1_zero | !op2_zero) & (r_e + shift_r_1 + I_DIFF);
r_t.adjust(r_e, true, false);
r.m = r_t.m;
r.e = r_t.e;
}
template<AC_FL_T(1), AC_FL_T(2)>
ac_float add(const AC_FL(1) &op1, const AC_FL(2) &op2) {
op1.plus_minus(op2, *this);
return *this;
}
template<AC_FL_T(1), AC_FL_T(2)>
ac_float sub(const AC_FL(1) &op1, const AC_FL(2) &op2) {
op1.plus_minus(op2, *this, true);
return *this;
}
typename rt_unary::neg abs() const {
typedef typename rt_unary::neg r_t;
r_t r;
r.m = is_neg() ? -m : r_t::mant_t(m);
r.e = e;
return r;
}
#ifdef __AC_FLOAT_ENABLE_ALPHA
// These will be changed!!! For now only enable to explore integration with ac_complex
template<AC_FL_T(2)>
typename rt< AC_FL_TV0(2) >::plus operator +(const AC_FL(2) &op2) const {
typename rt< AC_FL_TV0(2) >::plus r;
plus_minus(op2, r);
return r;
}
template<AC_FL_T(2)>
typename rt< AC_FL_TV0(2) >::minus operator -(const AC_FL(2) &op2) const {
typename rt< AC_FL_TV0(2) >::minus r;
plus_minus(op2, r, true);
return r;
}
#endif
template<AC_FL_T(2)>
typename rt< AC_FL_TV0(2) >::div operator /(const AC_FL(2) &op2) const {
typename rt< AC_FL_TV0(2) >::div r(m/op2.m, exp()-op2.exp());
return r;
}
template<AC_FL_T(2)>
ac_float operator +=(const AC_FL(2) &op2) {
ac_float r;
plus_minus(op2, r);
*this = r;
}
template<AC_FL_T(2)>
ac_float operator -=(const AC_FL(2) &op2) {
ac_float r;
plus_minus(op2, r, true);
*this = r;
}
template<AC_FL_T(2)>
ac_float operator *=(const AC_FL(2) &op2) {
*this = *this * op2;
}
template<AC_FL_T(2)>
ac_float operator /=(const AC_FL(2) &op2) {
*this = *this / op2;
}
ac_float operator + () const {
return *this;
}
typename rt_unary::neg operator - () const {
typename rt_unary::neg r;
r.m = -m;
r.e = e;
return r;
}
bool operator ! () const {
return !m;
}
// Shift --------------------------------------------------------------------
template<int WI, bool SI>
typename rt_i<WI,SI>::lshift operator << ( const ac_int<WI,SI> &op2 ) const {
typename rt_i<WI,SI>::lshift r;
r.m = m;
r.e = e + op2;
return r;
}
template<int WI, bool SI>
typename rt_i<WI,SI>::rshift operator >> ( const ac_int<WI,SI> &op2 ) const {
typename rt_i<WI,SI>::rshift r;
r.m = m;
r.e = e - op2;
return r;
}
// Shift assign -------------------------------------------------------------
template<int WI, bool SI>
ac_float &operator <<= ( const ac_int<WI,SI> &op2 ) {
*this = operator << (op2);
return *this;
}
template<int WI, bool SI>
ac_float &operator >>= ( const ac_int<WI,SI> &op2 ) {
*this = operator >> (op2);
return *this;
}
template<AC_FL_T(2)>
bool operator == (const AC_FL(2) &f) const {
bool gt;
return compare(f, >);
}
template<AC_FL_T(2)>
bool operator != (const AC_FL(2) &f) const {
return !operator == (f);
}
template<AC_FL_T(2)>
bool operator < (const AC_FL(2) &f) const {
bool gt;
bool eq = compare(f, >);
return !(eq | gt);
}
template<AC_FL_T(2)>
bool operator >= (const AC_FL(2) &f) const {
return !operator < (f);
}
template<AC_FL_T(2)>
bool operator > (const AC_FL(2) &f) const {
bool gt;
compare(f, >);
return gt;
}
template<AC_FL_T(2)>
bool operator <= (const AC_FL(2) &f) const {
return !operator > (f);
}
inline std::string to_string(ac_base_mode base_rep, bool sign_mag = false, bool hw=true) const {
// TODO: printing decimal with exponent
if(!hw) {
ac_fixed<W,0,S> mantissa;
mantissa.set_slc(0, m.template slc<W>(0));
std::string r = mantissa.to_string(base_rep, sign_mag);
r += "e2";
r += (e + I).to_string(base_rep, sign_mag | base_rep == AC_DEC);
return r;
} else {
std::string r = m.to_string(base_rep, sign_mag);
if(base_rep != AC_DEC)
r += "_";
r += "e2";
if(base_rep != AC_DEC)
r += "_";
if(E)
r += e.to_string(base_rep, sign_mag | base_rep == AC_DEC);
else
r += "0";
return r;
}
}
inline static std::string type_name() {
const char *tf[] = {"false", "true" };
const char *q[] = {"AC_TRN", "AC_RND", "AC_TRN_ZERO", "AC_RND_ZERO", "AC_RND_INF", "AC_RND_MIN_INF", "AC_RND_CONV" };
std::string r = "ac_float<";
r += ac_int<32,true>(W).to_string(AC_DEC) + ',';
r += ac_int<32,true>(I).to_string(AC_DEC) + ',';
r += ac_int<32,true>(E).to_string(AC_DEC) + ',';
r += tf[S];
r += ',';
r += q[Q];
r += '>';
return r;
}
template<ac_special_val V>
inline ac_float &set_val() {
m.template set_val<V>();
if(V == AC_VAL_MIN)
e.template set_val<AC_VAL_MAX>();
else if(V == AC_VAL_QUANTUM)
e.template set_val<AC_VAL_MIN>();
else
e.template set_val<V>();
return *this;
}
};
namespace ac_private {
template<typename T>
bool ac_fpclassify(T x, bool &inf) {
bool nan = !(x==x);
if(!nan) {
T d = x - x;
inf = !(d==d);
}
return nan;
}
inline ac_float_cdouble_t double_to_ac_float(double d) {
typedef ac_float_cdouble_t r_t;
#ifndef __SYNTHESIS__
bool inf;
bool nan = ac_fpclassify(d, inf);
if(nan)
AC_ASSERT(0, "In conversion from double to ac_float: double is NaN");
else if(inf)
AC_ASSERT(0, "In conversion from double to ac_float: double is Infinite");
#endif
r_t::exp_t exp;
r_t::mant_t mant = ac::frexp_d(d, exp);
return r_t(mant, exp, false);
}
inline ac_float_cfloat_t float_to_ac_float(float f) {
typedef ac_float_cfloat_t r_t;
#ifndef __SYNTHESIS__
bool inf;
bool nan = ac_fpclassify(f, inf);
if(nan)
AC_ASSERT(0, "In conversion from float to ac_float: float is NaN");
else if(inf)
AC_ASSERT(0, "In conversion from float to ac_float: float is Infinite");
#endif
r_t::exp_t exp;
r_t::mant_t mant = ac::frexp_f(f, exp);
return r_t(mant, exp, false);
}
};
namespace ac {
template<typename T>
struct ac_float_represent {
typedef typename ac_fixed_represent<T>::type fx_t;
typedef ac_float<fx_t::width+!fx_t::sign,fx_t::i_width+!fx_t::sign,1,fx_t::q_mode> type;
};
template<> struct ac_float_represent<float> {
typedef ac_private::ac_float_cfloat_t type;
};
template<> struct ac_float_represent<double> {
typedef ac_private::ac_float_cdouble_t type;
};
}
namespace ac_private {
// with T == ac_float
template< AC_FL_T0(2) >
struct rt_ac_float_T< AC_FL0(2) > {
typedef AC_FL0(2) fl2_t;
template< AC_FL_T0() >
struct op1 {
typedef AC_FL0() fl_t;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::mult mult;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::plus plus;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::minus minus;
typedef typename fl2_t::template rt< AC_FL_TV0() >::minus minus2;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::logic logic;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::div div;
typedef typename fl2_t::template rt< AC_FL_TV0() >::div div2;
};
};
// with T == ac_fixed
template<int WFX, int IFX, bool SFX>
struct rt_ac_float_T< ac_fixed<WFX,IFX,SFX> > {
// For now E2 > 0
enum { E2 = 1, S2 = true, W2 = WFX + !SFX, I2 = IFX + !SFX };
typedef AC_FL0(2) fl2_t;
template< AC_FL_T0() >
struct op1 {
typedef AC_FL0() fl_t;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::mult mult;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::plus plus;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::minus minus;
typedef typename fl2_t::template rt< AC_FL_TV0() >::minus minus2;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::logic logic;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::div div;
typedef typename fl2_t::template rt< AC_FL_TV0() >::div div2;
};
};
// with T == ac_int
template<int WI, bool SI>
struct rt_ac_float_T< ac_int<WI,SI> > {
// For now E2 > 0
enum { E2 = 1, S2 = true, I2 = WI + !SI, W2 = I2 };
typedef AC_FL0(2) fl2_t;
template< AC_FL_T0() >
struct op1 {
typedef AC_FL0() fl_t;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::mult mult;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::plus plus;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::minus minus;
typedef typename fl2_t::template rt< AC_FL_TV0() >::minus minus2;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::logic logic;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::div div;
typedef typename fl2_t::template rt< AC_FL_TV0() >::div div2;
};
};
// Multiplication is optimizable, general operator +/- is not yet supported
template<typename T>
struct rt_ac_float_T< c_type<T> > {
// For now E2 > 0
enum { SCT = c_type_params<T>::S, S2 = true, W2 = c_type_params<T>::W + !SCT, I2 = c_type_params<T>::I + !SCT, E2 = AC_MAX(1, c_type_params<T>::E) };
typedef AC_FL0(2) fl2_t;
template< AC_FL_T0() >
struct op1 {
typedef AC_FL0() fl_t;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::mult mult;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::plus plus;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::minus minus;
typedef typename fl2_t::template rt< AC_FL_TV0() >::minus minus2;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::logic logic;
typedef typename fl_t::template rt< AC_FL_TV0(2) >::div div;
typedef typename fl2_t::template rt< AC_FL_TV0() >::div div2;
};
};
}
// Stream --------------------------------------------------------------------
#ifndef __SYNTHESIS__
template<AC_FL_T()>
inline std::ostream& operator << (std::ostream &os, const AC_FL() &x) {
os << x.to_string(AC_DEC);
return os;
}
#endif
#define FL_BIN_OP_WITH_CTYPE(BIN_OP, C_TYPE, RTYPE) \
template< AC_FL_T() > \
inline typename AC_FL()::template rt_T2<C_TYPE>::RTYPE operator BIN_OP ( C_TYPE c_op, const AC_FL() &op) { \
typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \
return fl2_t(c_op).operator BIN_OP (op); \
} \
template< AC_FL_T() > \
inline typename AC_FL()::template rt_T<C_TYPE>::RTYPE operator BIN_OP ( const AC_FL() &op, C_TYPE c_op) { \
typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \
return op.operator BIN_OP (fl2_t(c_op)); \
}
#define FL_REL_OP_WITH_CTYPE(REL_OP, C_TYPE) \
template< AC_FL_T() > \
inline bool operator REL_OP ( const AC_FL() &op, C_TYPE op2) { \
typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \
return op.operator REL_OP (fl2_t(op2)); \
} \
template< AC_FL_T() > \
inline bool operator REL_OP ( C_TYPE op2, const AC_FL() &op) { \
typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \
return fl2_t(op2).operator REL_OP (op); \
}
#define FL_ASSIGN_OP_WITH_CTYPE_2(ASSIGN_OP, C_TYPE) \
template< AC_FL_T() > \
inline AC_FL() &operator ASSIGN_OP ( AC_FL() &op, C_TYPE op2) { \
typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \
return op.operator ASSIGN_OP (fl2_t(op2)); \
}
#define FL_OPS_WITH_CTYPE(C_TYPE) \
FL_BIN_OP_WITH_CTYPE(*, C_TYPE, mult) \
FL_BIN_OP_WITH_CTYPE(+, C_TYPE, plus) \
FL_BIN_OP_WITH_CTYPE(-, C_TYPE, minus) \
FL_BIN_OP_WITH_CTYPE(/, C_TYPE, div) \
\
FL_REL_OP_WITH_CTYPE(==, C_TYPE) \
FL_REL_OP_WITH_CTYPE(!=, C_TYPE) \
FL_REL_OP_WITH_CTYPE(>, C_TYPE) \
FL_REL_OP_WITH_CTYPE(>=, C_TYPE) \
FL_REL_OP_WITH_CTYPE(<, C_TYPE) \
FL_REL_OP_WITH_CTYPE(<=, C_TYPE) \
\
FL_ASSIGN_OP_WITH_CTYPE_2(+=, C_TYPE) \
FL_ASSIGN_OP_WITH_CTYPE_2(-=, C_TYPE) \
FL_ASSIGN_OP_WITH_CTYPE_2(*=, C_TYPE) \
FL_ASSIGN_OP_WITH_CTYPE_2(/=, C_TYPE)
#define FL_SHIFT_OP_WITH_INT_CTYPE(BIN_OP, C_TYPE, RTYPE) \
template< AC_FL_T() > \
inline typename AC_FL()::template rt_i< ac_private::c_type_params<C_TYPE>::W, ac_private::c_type_params<C_TYPE>::S >::RTYPE operator BIN_OP ( const AC_FL() &op, C_TYPE i_op) { \
typedef typename ac::template ac_int_represent<C_TYPE>::type i_t; \
return op.operator BIN_OP (i_t(i_op)); \
}
#define FL_SHIFT_ASSIGN_OP_WITH_INT_CTYPE(ASSIGN_OP, C_TYPE) \
template< AC_FL_T() > \
inline AC_FL() &operator ASSIGN_OP ( AC_FL() &op, C_TYPE i_op) { \
typedef typename ac::template ac_int_represent<C_TYPE>::type i_t; \
return op.operator ASSIGN_OP (i_t(i_op)); \
}
#define FL_SHIFT_OPS_WITH_INT_CTYPE(C_TYPE) \
FL_SHIFT_OP_WITH_INT_CTYPE(>>, C_TYPE, rshift) \
FL_SHIFT_OP_WITH_INT_CTYPE(<<, C_TYPE, lshift) \
FL_SHIFT_ASSIGN_OP_WITH_INT_CTYPE(>>=, C_TYPE) \
FL_SHIFT_ASSIGN_OP_WITH_INT_CTYPE(<<=, C_TYPE)
#define FL_OPS_WITH_INT_CTYPE(C_TYPE) \
FL_OPS_WITH_CTYPE(C_TYPE) \
FL_SHIFT_OPS_WITH_INT_CTYPE(C_TYPE)
// --------------------------------------- End of Macros for Binary Operators with C Floats
// Binary Operators with C Floats --------------------------------------------
FL_OPS_WITH_CTYPE(float)
FL_OPS_WITH_CTYPE(double)
FL_OPS_WITH_INT_CTYPE(bool)
FL_OPS_WITH_INT_CTYPE(char)
FL_OPS_WITH_INT_CTYPE(signed char)
FL_OPS_WITH_INT_CTYPE(unsigned char)
FL_OPS_WITH_INT_CTYPE(short)
FL_OPS_WITH_INT_CTYPE(unsigned short)
FL_OPS_WITH_INT_CTYPE(int)
FL_OPS_WITH_INT_CTYPE(unsigned int)
FL_OPS_WITH_INT_CTYPE(long)
FL_OPS_WITH_INT_CTYPE(unsigned long)
FL_OPS_WITH_INT_CTYPE(Slong)
FL_OPS_WITH_INT_CTYPE(Ulong)
// -------------------------------------- End of Binary Operators with C Floats
// Macros for Binary Operators with ac_int --------------------------------------------
#define FL_BIN_OP_WITH_AC_INT_1(BIN_OP, RTYPE) \
template< AC_FL_T(), int WI, bool SI> \
inline typename AC_FL()::template rt_T2< ac_int<WI,SI> >::RTYPE operator BIN_OP ( const ac_int<WI,SI> &i_op, const AC_FL() &op) { \
typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \
return fl2_t(i_op).operator BIN_OP (op); \
}
#define FL_BIN_OP_WITH_AC_INT_2(BIN_OP, RTYPE) \
template< AC_FL_T(), int WI, bool SI> \
inline typename AC_FL()::template rt_T2< ac_int<WI,SI> >::RTYPE operator BIN_OP ( const AC_FL() &op, const ac_int<WI,SI> &i_op) { \
typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \
return op.operator BIN_OP (fl2_t(i_op)); \
}
#define FL_BIN_OP_WITH_AC_INT(BIN_OP, RTYPE) \
FL_BIN_OP_WITH_AC_INT_1(BIN_OP, RTYPE) \
FL_BIN_OP_WITH_AC_INT_2(BIN_OP, RTYPE)
#define FL_REL_OP_WITH_AC_INT(REL_OP) \
template< AC_FL_T(), int WI, bool SI> \
inline bool operator REL_OP ( const AC_FL() &op, const ac_int<WI,SI> &op2) { \
typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \
return op.operator REL_OP (fl2_t(op2)); \
} \
template< AC_FL_T(), int WI, bool SI> \
inline bool operator REL_OP ( ac_int<WI,SI> &op2, const AC_FL() &op) { \
typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \
return fl2_t(op2).operator REL_OP (op); \
}
#define FL_ASSIGN_OP_WITH_AC_INT(ASSIGN_OP) \
template< AC_FL_T(), int WI, bool SI> \
inline AC_FL() &operator ASSIGN_OP ( AC_FL() &op, const ac_int<WI,SI> &op2) { \
typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \
return op.operator ASSIGN_OP (fl2_t(op2)); \
}
// -------------------------------------------- End of Macros for Binary Operators with ac_int
// Binary Operators with ac_int --------------------------------------------
FL_BIN_OP_WITH_AC_INT(*, mult)
FL_BIN_OP_WITH_AC_INT(+, plus)
FL_BIN_OP_WITH_AC_INT(-, minus)
FL_BIN_OP_WITH_AC_INT(/, div)
FL_REL_OP_WITH_AC_INT(==)
FL_REL_OP_WITH_AC_INT(!=)
FL_REL_OP_WITH_AC_INT(>)
FL_REL_OP_WITH_AC_INT(>=)
FL_REL_OP_WITH_AC_INT(<)
FL_REL_OP_WITH_AC_INT(<=)
FL_ASSIGN_OP_WITH_AC_INT(+=)
FL_ASSIGN_OP_WITH_AC_INT(-=)
FL_ASSIGN_OP_WITH_AC_INT(*=)
FL_ASSIGN_OP_WITH_AC_INT(/=)
FL_ASSIGN_OP_WITH_AC_INT(%=)
// -------------------------------------- End of Binary Operators with ac_int
// Macros for Binary Operators with ac_fixed --------------------------------------------
#define FL_BIN_OP_WITH_AC_FIXED_1(BIN_OP, RTYPE) \
template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \
inline typename AC_FL()::template rt_T2< ac_fixed<WF,IF,SF> >::RTYPE operator BIN_OP ( const ac_fixed<WF,IF,SF,QF,OF> &f_op, const AC_FL() &op) { \
typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \
return fl2_t(f_op).operator BIN_OP (op); \
}
#define FL_BIN_OP_WITH_AC_FIXED_2(BIN_OP, RTYPE) \
template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \
inline typename AC_FL()::template rt_T2< ac_fixed<WF,IF,SF> >::RTYPE operator BIN_OP ( const AC_FL() &op, const ac_fixed<WF,IF,SF,QF,OF> &f_op) { \
typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \
return op.operator BIN_OP (fl2_t(f_op)); \
}
#define FL_BIN_OP_WITH_AC_FIXED(BIN_OP, RTYPE) \
FL_BIN_OP_WITH_AC_FIXED_1(BIN_OP, RTYPE) \
FL_BIN_OP_WITH_AC_FIXED_2(BIN_OP, RTYPE)
#define FL_REL_OP_WITH_AC_FIXED(REL_OP) \
template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \
inline bool operator REL_OP ( const AC_FL() &op, const ac_fixed<WF,IF,SF,QF,OF> &op2) { \
typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \
return op.operator REL_OP (fl2_t(op2)); \
} \
template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \
inline bool operator REL_OP ( ac_fixed<WF,IF,SF,QF,OF> &op2, const AC_FL() &op) { \
typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \
return fl2_t(op2).operator REL_OP (op); \
}
#define FL_ASSIGN_OP_WITH_AC_FIXED(ASSIGN_OP) \
template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \
inline AC_FL() &operator ASSIGN_OP ( AC_FL() &op, const ac_fixed<WF,IF,SF,QF,OF> &op2) { \
typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \
return op.operator ASSIGN_OP (fl2_t(op2)); \
}
// -------------------------------------------- End of Macros for Binary Operators with ac_fixed
// Binary Operators with ac_fixed --------------------------------------------
FL_BIN_OP_WITH_AC_FIXED(*, mult)
FL_BIN_OP_WITH_AC_FIXED(+, plus)
FL_BIN_OP_WITH_AC_FIXED(-, minus)
FL_BIN_OP_WITH_AC_FIXED(/, div)
FL_REL_OP_WITH_AC_FIXED(==)
FL_REL_OP_WITH_AC_FIXED(!=)
FL_REL_OP_WITH_AC_FIXED(>)
FL_REL_OP_WITH_AC_FIXED(>=)
FL_REL_OP_WITH_AC_FIXED(<)
FL_REL_OP_WITH_AC_FIXED(<=)
FL_ASSIGN_OP_WITH_AC_FIXED(+=)
FL_ASSIGN_OP_WITH_AC_FIXED(-=)
FL_ASSIGN_OP_WITH_AC_FIXED(*=)
FL_ASSIGN_OP_WITH_AC_FIXED(/=)
// -------------------------------------- End of Binary Operators with ac_fixed
// Global templatized functions for easy initialization to special values
template<ac_special_val V, AC_FL_T()>
inline AC_FL() value( AC_FL() ) {
AC_FL() r;
return r.template set_val<V>();
}
namespace ac {
// function to initialize (or uninitialize) arrays
template<ac_special_val V, AC_FL_T() >
inline bool init_array( AC_FL() *a, int n) {
AC_FL0() t = value<V>(*a);
for(int i=0; i < n; i++)
a[i] = t;
return true;
}
}
///////////////////////////////////////////////////////////////////////////////
#if (defined(_MSC_VER) && !defined(__EDG__))
#pragma warning( pop )
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#ifdef __AC_NAMESPACE
}
#endif
#endif // __AC_FLOAT_H
|
manageryzy/ac_types_plus
|
include/ac_int.h
|
<filename>include/ac_int.h
/**************************************************************************
* *
* Algorithmic C (tm) Datatypes *
* *
* Software Version: 3.7 *
* *
* Release Date : Tue May 30 14:25:58 PDT 2017 *
* Release Type : Production Release *
* Release Build : 3.7.2 *
* *
* Copyright 2004-2017, Mentor Graphics Corporation, *
* *
* All Rights Reserved. *
*
**************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
**************************************************************************
* *
* The most recent version of this package is available at github. *
* *
*************************************************************************/
/*
// Source: ac_int.h
// Description: fast arbitrary-length bit-accurate integer types:
// - unsigned integer of length W: ac_int<W,false>
// - signed integer of length W: ac_int<W,true>
// Author: <NAME>, Ph.D.
// Notes:
// - C++ Runtime: important to use optimization flag (for example -O3)
//
// - Compiler support: recent GNU compilers are required for correct
// template compilation
//
// - Most frequent migration issues:
// - need to cast to common type when using question mark operator:
// (a < 0) ? -a : a; // a is ac_int<W,true>
// change to:
// (a < 0) ? -a : (ac_int<W+1,true>) a;
// or
// (a < 0) ? (ac_int<W+1,false>) -a : (ac_int<W+1,false>) a;
//
// - left shift is not arithmetic ("a<<n" has same bitwidth as "a")
// ac_int<W+1,false> b = a << 1; // a is ac_int<W,false>
// is not equivalent to b=2*a. In order to get 2*a behavior change to:
// ac_int<W+1,false> b = (ac_int<W+1,false>)a << 1;
//
// - only static length read/write slices are supported:
// - read: x.slc<4>(k) => returns ac_int for 4-bit slice x(4+k-1 DOWNTO k)
// - write: x.set_slc(k,y) = writes bits of y to x starting at index k
*/
#ifndef __AC_INT_H
#define __AC_INT_H
#define AC_VERSION 3
#define AC_VERSION_MINOR 7
#ifndef __cplusplus
#error C++ is required to include this header file
#endif
#if (defined(__GNUC__) && __GNUC__ < 3 && !defined(__EDG__))
#error GCC version 3 or greater is required to include this header file
#endif
#if (defined(_MSC_VER) && _MSC_VER < 1400 && !defined(__EDG__))
#error Microsoft Visual Studio 8 or newer is required to include this header file
#endif
#if (defined(_MSC_VER) && !defined(__EDG__))
#pragma warning( push )
#pragma warning( disable: 4127 4100 4244 4307 4310 4365 4514 4554 4706 4800 )
#endif
// for safety
#if (defined(N) || defined(N2))
#error One or more of the following is defined: N, N2. Definition conflicts with their usage as template parameters.
#error DO NOT use defines before including third party header files.
#endif
// for safety
#if (defined(W) || defined(I) || defined(S) || defined(W2) || defined(I2) || defined(S2))
#error One or more of the following is defined: W, I, S, W2, I2, S2. Definition conflicts with their usage as template parameters.
#error DO NOT use defines before including third party header files.
#endif
#ifndef __ASSERT_H__
#define __ASSERT_H__
#include <assert.h>
#endif
#include <limits>
#ifndef AC_USER_DEFINED_ASSERT
#include <iostream>
#else
#include <ostream>
#endif
#include <math.h>
#include <string>
#ifndef __SYNTHESIS__
#ifndef __AC_INT_UTILITY_BASE
#define __AC_INT_UTILITY_BASE
#endif
#endif
#ifdef __AC_NAMESPACE
namespace __AC_NAMESPACE {
#endif
#define AC_MAX(a,b) ((a) > (b) ? (a) : (b))
#define AC_MIN(a,b) ((a) < (b) ? (a) : (b))
#define AC_ABS(a) ((a) < 0 ? (-a) : (a))
#if defined(_MSC_VER)
typedef unsigned __int64 Ulong;
typedef signed __int64 Slong;
#else
typedef unsigned long long Ulong;
typedef signed long long Slong;
#endif
enum ac_base_mode { AC_BIN=2, AC_OCT=8, AC_DEC=10, AC_HEX=16 };
enum ac_special_val {AC_VAL_DC, AC_VAL_0, AC_VAL_MIN, AC_VAL_MAX, AC_VAL_QUANTUM};
template <int W, bool S> class ac_int;
namespace ac_private {
#if defined(__SYNTHESIS__) && !defined(AC_IGNORE_BUILTINS)
#pragma builtin
#endif
enum {long_w = std::numeric_limits<unsigned long>::digits};
const unsigned int all_ones = (unsigned) ~0;
// PRIVATE FUNCTIONS in namespace: for implementing ac_int/ac_fixed
#ifndef __SYNTHESIS__
inline double mgc_floor(double d) { return floor(d); }
#else
inline double mgc_floor(double d) { return 0.0; }
#endif
#define AC_ASSERT(cond, msg) ac_private::ac_assert(cond, __FILE__, __LINE__, msg)
inline void ac_assert(bool condition, const char *file=0, int line=0, const char *msg=0) {
#ifndef __SYNTHESIS__
#ifndef AC_USER_DEFINED_ASSERT
if(!condition) {
std::cerr << "Assert";
if(file)
std::cerr << " in file " << file << ":" << line;
if(msg)
std::cerr << " " << msg;
std::cerr << std::endl;
assert(0);
}
#else
AC_USER_DEFINED_ASSERT(condition, file, line, msg);
#endif
#endif
}
// helper structs for statically computing log2 like functions (nbits, log2_floor, log2_ceil)
// using recursive templates
template<unsigned char N>
struct s_N {
template<unsigned X>
struct s_X {
enum {
X2 = X >> N,
N_div_2 = N >> 1,
nbits = X ? (X2 ? N + (int) s_N<N_div_2>::template s_X<X2>::nbits : (int) s_N<N_div_2>::template s_X<X>::nbits) : 0
};
};
};
template<> struct s_N<0> {
template<unsigned X>
struct s_X {
enum {nbits = !!X };
};
};
template<int N>
inline double ldexpr32(double d) {
double d2 = d;
if(N < 0)
for(int i=0; i < -N; i++)
d2 /= (Ulong) 1 << 32;
else
for(int i=0; i < N; i++)
d2 *= (Ulong) 1 << 32;
return d2;
}
template<> inline double ldexpr32<0>(double d) { return d; }
template<> inline double ldexpr32<1>(double d) { return d * ((Ulong) 1 << 32); }
template<> inline double ldexpr32<-1>(double d) { return d / ((Ulong) 1 << 32); }
template<> inline double ldexpr32<2>(double d) { return (d * ((Ulong) 1 << 32)) * ((Ulong) 1 << 32); }
template<> inline double ldexpr32<-2>(double d) { return (d / ((Ulong) 1 << 32)) / ((Ulong) 1 << 32); }
template<int N>
inline double ldexpr(double d) {
return ldexpr32<N/32>( N < 0 ? d/( (unsigned) 1 << (-N & 31)) : d * ( (unsigned) 1 << (N & 31)));
}
template<int N>
inline void iv_copy(const int *op, int *r) {
for(int i=0; i < N; i++)
r[i] = op[i];
}
template<> inline void iv_copy<1>(const int *op, int *r) {
r[0] = op[0];
}
template<> inline void iv_copy<2>(const int *op, int *r) {
r[0] = op[0];
r[1] = op[1];
}
template<int N>
inline bool iv_equal_zero(const int *op){
for(int i=0; i < N; i++)
if(op[i])
return false;
return true;
}
template<> inline bool iv_equal_zero<0>(const int * /*op*/) { return true; }
template<> inline bool iv_equal_zero<1>(const int *op) {
return !op[0];
}
template<> inline bool iv_equal_zero<2>(const int *op) {
return !(op[0] || op[1]);
}
template<int N>
inline bool iv_equal_ones(const int *op){
for(int i=0; i < N; i++)
if(~op[i])
return false;
return true;
}
template<> inline bool iv_equal_ones<0>(const int * /*op*/) { return true; }
template<> inline bool iv_equal_ones<1>(const int *op) {
return !~op[0];
}
template<> inline bool iv_equal_ones<2>(const int *op) {
return !(~op[0] || ~op[1]);
}
template<int N1, int N2>
inline bool iv_equal(const int *op1, const int *op2){
const int M1 = AC_MAX(N1,N2);
const int M2 = AC_MIN(N1,N2);
const int *OP1 = N1 >= N2 ? op1 : op2;
const int *OP2 = N1 >= N2 ? op2 : op1;
for(int i=0; i < M2; i++)
if(OP1[i] != OP2[i])
return false;
int ext = OP2[M2-1] < 0 ? ~0 : 0;
for(int i=M2; i < M1; i++)
if(OP1[i] != ext)
return false;
return true;
}
template<> inline bool iv_equal<1,1>(const int *op1, const int *op2) {
return op1[0] == op2[0];
}
template<int B, int N>
inline bool iv_equal_ones_from(const int *op){
if((B >= 32*N && op[N-1] >= 0) || (B&31 && ~(op[B/32] >> (B&31))))
return false;
return iv_equal_ones<N-(B+31)/32>(&op[(B+31)/32]);
}
template<> inline bool iv_equal_ones_from<0,1>(const int *op){
return iv_equal_ones<1>(op);
}
template<> inline bool iv_equal_ones_from<0,2>(const int *op){
return iv_equal_ones<2>(op);
}
template<int B, int N>
inline bool iv_equal_zeros_from(const int *op){
if((B >= 32*N && op[N-1] < 0) || (B&31 && (op[B/32] >> (B&31))))
return false;
return iv_equal_zero<N-(B+31)/32>(&op[(B+31)/32]);
}
template<> inline bool iv_equal_zeros_from<0,1>(const int *op){
return iv_equal_zero<1>(op);
}
template<> inline bool iv_equal_zeros_from<0,2>(const int *op){
return iv_equal_zero<2>(op);
}
template<int B, int N>
inline bool iv_equal_ones_to(const int *op){
if((B >= 32*N && op[N-1] >= 0) || (B&31 && ~(op[B/32] | (all_ones << (B&31)))))
return false;
return iv_equal_ones<B/32>(op);
}
template<> inline bool iv_equal_ones_to<0,1>(const int *op){
return iv_equal_ones<1>(op);
}
template<> inline bool iv_equal_ones_to<0,2>(const int *op){
return iv_equal_ones<2>(op);
}
template<int B, int N>
inline bool iv_equal_zeros_to(const int *op){
if((B >= 32*N && op[N-1] < 0) || (B&31 && (op[B/32] & ~(all_ones << (B&31)))))
return false;
return iv_equal_zero<B/32>(op);
}
template<> inline bool iv_equal_zeros_to<0,1>(const int *op){
return iv_equal_zero<1>(op);
}
template<> inline bool iv_equal_zeros_to<0,2>(const int *op){
return iv_equal_zero<2>(op);
}
template<int N1, int N2, bool greater>
inline bool iv_compare(const int *op1, const int *op2){
const int M1 = AC_MAX(N1,N2);
const int M2 = AC_MIN(N1,N2);
const int *OP1 = N1 >= N2 ? op1 : op2;
const int *OP2 = N1 >= N2 ? op2 : op1;
const bool b = (N1 >= N2) == greater;
int ext = OP2[M2-1] < 0 ? ~0 : 0;
int i2 = M1 > M2 ? ext : OP2[M1-1];
if(OP1[M1-1] != i2)
return b ^ (OP1[M1-1] < i2);
for(int i=M1-2; i >= M2; i--) {
if((unsigned) OP1[i] != (unsigned) ext)
return b ^ ((unsigned) OP1[i] < (unsigned) ext);
}
for(int i=M2-1; i >= 0; i--) {
if((unsigned) OP1[i] != (unsigned) OP2[i])
return b ^ ((unsigned) OP1[i] < (unsigned) OP2[i]);
}
return false;
}
template<> inline bool iv_compare<1,1,true>(const int *op1, const int *op2) {
return op1[0] > op2[0];
}
template<> inline bool iv_compare<1,1,false>(const int *op1, const int *op2) {
return op1[0] < op2[0];
}
template<int N>
inline void iv_extend(int *r, int ext) {
for(int i=0; i < N; i++)
r[i] = ext;
}
template<> inline void iv_extend<-2>(int * /*r*/, int /*ext*/) { }
template<> inline void iv_extend<-1>(int * /*r*/, int /*ext*/) { }
template<> inline void iv_extend<0>(int * /*r*/, int /*ext*/) { }
template<> inline void iv_extend<1>(int *r, int ext) {
r[0] = ext;
}
template<> inline void iv_extend<2>(int *r, int ext) {
r[0] = ext;
r[1] = ext;
}
template<int Nr>
inline void iv_assign_int64(int *r, Slong l) {
r[0] = (int) l;
if(Nr > 1) {
r[1] = (int) (l >> 32);
iv_extend<Nr-2>(r+2, (r[1] < 0) ? ~0 : 0);
}
}
template<> inline void iv_assign_int64<1>(int *r, Slong l) {
r[0] = (int) l;
}
template<> inline void iv_assign_int64<2>(int *r, Slong l) {
r[0] = (int) l;
r[1] = (int) (l >> 32);
}
template<int Nr>
inline void iv_assign_uint64(int *r, Ulong l) {
r[0] = (int) l;
if(Nr > 1) {
r[1] = (int) (l >> 32);
iv_extend<Nr-2>(r+2, 0);
}
}
template<> inline void iv_assign_uint64<1>(int *r, Ulong l) {
r[0] = (int) l;
}
template<> inline void iv_assign_uint64<2>(int *r, Ulong l) {
r[0] = (int) l;
r[1] = (int) (l >> 32);
}
inline Ulong mult_u_u(int a, int b) {
return (Ulong) (unsigned) a * (Ulong) (unsigned) b;
}
inline Slong mult_u_s(int a, int b) {
return (Ulong) (unsigned) a * (Slong) (signed) b;
}
inline Slong mult_s_u(int a, int b) {
return (Slong) (signed) a * (Ulong) (unsigned) b;
}
inline Slong mult_s_s(int a, int b) {
return (Slong) (signed) a * (Slong) (signed) b;
}
inline void accumulate(Ulong a, Ulong &l1, Slong &l2) {
l1 += (Ulong) (unsigned) a;
l2 += a >> 32;
}
inline void accumulate(Slong a, Ulong &l1, Slong &l2) {
l1 += (Ulong) (unsigned) a;
l2 += a >> 32;
}
template<int N1, int N2, int Nr>
inline void iv_mult(const int *op1, const int *op2, int *r) {
if(Nr==1)
r[0] = op1[0] * op2[0];
else if(N1==1 && N2==1)
iv_assign_int64<Nr>(r, ((Slong) op1[0]) * ((Slong) op2[0]));
else {
const int M1 = AC_MAX(N1,N2);
const int M2 = AC_MIN(N1,N2);
const int *OP1 = N1 >= N2 ? op1 : op2;
const int *OP2 = N1 >= N2 ? op2 : op1;
const int T1 = AC_MIN(M2-1,Nr);
const int T2 = AC_MIN(M1-1,Nr);
const int T3 = AC_MIN(M1+M2-2,Nr);
Ulong l1 = 0;
Slong l2 = 0;
for(int k=0; k < T1; k++) {
for(int i=0; i < k+1; i++)
accumulate(mult_u_u(OP1[k-i], OP2[i]), l1, l2);
l2 += (Ulong) (unsigned) (l1 >> 32);
r[k] = (int) l1;
l1 = (unsigned) l2;
l2 >>= 32;
}
for(int k=T1; k < T2; k++) {
accumulate(mult_u_s(OP1[k-M2+1], OP2[M2-1]), l1, l2);
for(int i=0; i < M2-1; i++)
accumulate(mult_u_u(OP1[k-i], OP2[i]), l1, l2);
l2 += (Ulong) (unsigned) (l1 >> 32);
r[k] = (int) l1;
l1 = (unsigned) l2;
l2 >>= 32;
}
for(int k=T2; k < T3; k++) {
accumulate(mult_u_s(OP1[k-M2+1], OP2[M2-1]), l1, l2);
for(int i=k-T2+1; i < M2-1; i++)
accumulate(mult_u_u(OP1[k-i], OP2[i]), l1, l2);
accumulate(mult_s_u(OP1[M1-1], OP2[k-M1+1]), l1, l2);
l2 += (Ulong) (unsigned) (l1 >> 32);
r[k] = (int) l1;
l1 = (unsigned) l2;
l2 >>= 32;
}
if(Nr >= M1+M2-1) {
accumulate(mult_s_s(OP1[M1-1], OP2[M2-1]), l1, l2);
r[M1+M2-2] = (int) l1;
if(Nr >= M1+M2) {
l2 += (Ulong) (unsigned) (l1 >> 32);
r[M1+M2-1] = (int) l2;
iv_extend<Nr-(M1+M2)>(r+M1+M2, (r[M1+M2-1] < 0) ? ~0 : 0);
}
}
}
}
template<> inline void iv_mult<1,1,1>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] * op2[0];
}
template<> inline void iv_mult<1,1,2>(const int *op1, const int *op2, int *r) {
iv_assign_int64<2>(r, ((Slong) op1[0]) * ((Slong) op2[0]));
}
template<int N>
inline bool iv_uadd_carry(const int *op1, bool carry, int *r) {
Slong l = carry;
for(int i=0; i < N; i++) {
l += (Ulong) (unsigned) op1[i];
r[i] = (int) l;
l >>= 32;
}
return l != 0;
}
template<> inline bool iv_uadd_carry<0>(const int * /*op1*/, bool carry, int * /*r*/) { return carry; }
template<> inline bool iv_uadd_carry<1>(const int *op1, bool carry, int *r) {
Ulong l = carry + (Ulong) (unsigned) op1[0];
r[0] = (int) l;
return (l >> 32) & 1;
}
template<int N>
inline bool iv_add_int_carry(const int *op1, int op2, bool carry, int *r) {
if(N==0)
return carry;
if(N==1) {
Ulong l = carry + (Slong) op1[0] + (Slong) op2;
r[0] = (int) l;
return (l >> 32) & 1;
}
Slong l = carry + (Ulong) (unsigned) op1[0] + (Slong) op2;
r[0] = (int) l;
l >>= 32;
for(int i=1; i < N-1; i++) {
l += (Ulong) (unsigned) op1[i];
r[i] = (int) l;
l >>= 32;
}
l += (Slong) op1[N-1];
r[N-1] = (int) l;
return (l >> 32) & 1;
}
template<> inline bool iv_add_int_carry<0>(const int * /*op1*/, int /*op2*/, bool carry, int * /*r*/) { return carry; }
template<> inline bool iv_add_int_carry<1>(const int *op1, int op2, bool carry, int *r) {
Ulong l = carry + (Slong) op1[0] + (Slong) op2;
r[0] = (int) l;
return (l >> 32) & 1;
}
template<int N>
inline bool iv_uadd_n(const int *op1, const int *op2, int *r) {
Ulong l = 0;
for(int i=0; i < N; i++) {
l += (Ulong)(unsigned) op1[i] + (Ulong)(unsigned) op2[i];
r[i] = (int) l;
l >>= 32;
}
return l & 1;
}
template<> inline bool iv_uadd_n<0>(const int * /*op1*/, const int * /*op2*/, int * /*r*/) { return false; }
template<> inline bool iv_uadd_n<1>(const int *op1, const int *op2, int *r) {
Ulong l = (Ulong) (unsigned) op1[0] + (Ulong) (unsigned) op2[0];
r[0] = (int) l;
return (l >> 32) & 1;
}
template<> inline bool iv_uadd_n<2>(const int *op1, const int *op2, int *r) {
Ulong l = (Ulong) (unsigned) op1[0] + (Ulong) (unsigned) op2[0];
r[0] = (int) l;
l >>= 32;
l += (Ulong) (unsigned) op1[1] + (Ulong) (unsigned) op2[1];
r[1] = (int) l;
return (l >> 32) & 1;
}
template<int N1, int N2, int Nr>
inline void iv_add(const int *op1, const int *op2, int *r) {
if(Nr==1)
r[0] = op1[0] + op2[0];
else {
const int M1 = AC_MAX(N1,N2);
const int M2 = AC_MIN(N1,N2);
const int *OP1 = N1 >= N2 ? op1 : op2;
const int *OP2 = N1 >= N2 ? op2 : op1;
const int T1 = AC_MIN(M2-1,Nr);
const int T2 = AC_MIN(M1,Nr);
bool carry = iv_uadd_n<T1>(OP1, OP2, r);
carry = iv_add_int_carry<T2-T1>(OP1+T1, OP2[T1], carry, r+T1);
iv_extend<Nr-T2>(r+T2, carry ? ~0 : 0);
}
}
template<> inline void iv_add<1,1,1>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] + op2[0];
}
template<> inline void iv_add<1,1,2>(const int *op1, const int *op2, int *r) {
iv_assign_int64<2>(r, (Slong) op1[0] + (Slong) op2[0]);
}
template<int N>
inline bool iv_sub_int_borrow(const int *op1, int op2, bool borrow, int *r) {
if(N==1) {
Ulong l = (Slong) op1[0] - (Slong) op2 - borrow;
r[0] = (int) l;
return (l >> 32) & 1;
}
Slong l = (Ulong) (unsigned) op1[0] - (Slong) op2 - borrow;
r[0] = (int) l;
l >>= 32;
for(int i=1; i < N-1; i++) {
l += (Ulong) (unsigned) op1[i];
r[i] = (int) l;
l >>= 32;
}
l += (Slong) op1[N-1];
r[N-1] = (int) l;
return (l >> 32) & 1;
}
template<> inline bool iv_sub_int_borrow<0>(const int * /*op1*/, int /*op2*/, bool borrow, int * /*r*/) { return borrow; }
template<> inline bool iv_sub_int_borrow<1>(const int *op1, int op2, bool borrow, int *r) {
Ulong l = (Slong) op1[0] - (Slong) op2 - borrow;
r[0] = (int) l;
return (l >> 32) & 1;
}
template<int N>
inline bool iv_sub_int_borrow(int op1, const int *op2, bool borrow, int *r) {
if(N==1) {
Ulong l = (Slong) op1 - (Slong) op2[0] - borrow;
r[0] = (int) l;
return (l >> 32) & 1;
}
Slong l = (Slong) op1 - (Ulong) (unsigned) op2[0] - borrow;
r[0] = (int) l;
l >>= 32;
for(int i=1; i < N-1; i++) {
l -= (Ulong) (unsigned) op2[i];
r[i] = (int) l;
l >>= 32;
}
l -= (Slong) op2[N-1];
r[N-1] = (int) l;
return (l >> 32) & 1;
}
template<> inline bool iv_sub_int_borrow<0>(int /*op1*/, const int * /*op2*/, bool borrow, int * /*r*/) { return borrow; }
template<> inline bool iv_sub_int_borrow<1>(int op1, const int *op2, bool borrow, int *r) {
Ulong l = (Slong) op1 - (Slong) op2[0] - borrow;
r[0] = (int) l;
return (l >> 32) & 1;
}
template<int N>
inline bool iv_usub_n(const int *op1, const int *op2, int *r) {
Slong l = 0;
for(int i=0; i < N; i++) {
l += (Ulong)(unsigned) op1[i] - (Ulong)(unsigned) op2[i];
r[i] = (int) l;
l >>= 32;
}
return l & 1;
}
template<> inline bool iv_usub_n<1>(const int *op1, const int *op2, int *r) {
Ulong l = (Ulong) (unsigned) op1[0] - (Ulong) (unsigned) op2[0];
r[0] = (int) l;
return (l >> 32) & 1;
}
template<> inline bool iv_usub_n<2>(const int *op1, const int *op2, int *r) {
Slong l = (Ulong) (unsigned) op1[0] - (Ulong) (unsigned) op2[0];
r[0] = (int) l;
l >>= 32;
l += (Ulong) (unsigned) op1[1] - (Ulong) (unsigned) op2[1];
r[1] = (int) l;
return (l >> 32) & 1;
}
template<int N1, int N2, int Nr>
inline void iv_sub(const int *op1, const int *op2, int *r) {
if(Nr==1)
r[0] = op1[0] - op2[0];
else {
const int M1 = AC_MAX(N1,N2);
const int M2 = AC_MIN(N1,N2);
const int T1 = AC_MIN(M2-1,Nr);
const int T2 = AC_MIN(M1,Nr);
bool borrow = iv_usub_n<T1>(op1, op2, r);
if(N1 > N2)
borrow = iv_sub_int_borrow<T2-T1>(op1+T1, op2[T1], borrow, r+T1);
else
borrow = iv_sub_int_borrow<T2-T1>(op1[T1], op2+T1, borrow, r+T1);
iv_extend<Nr-T2>(r+T2, borrow ? ~0 : 0);
}
}
template<> inline void iv_sub<1,1,1>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] - op2[0];
}
template<> inline void iv_sub<1,1,2>(const int *op1, const int *op2, int *r) {
iv_assign_int64<2>(r, (Slong) op1[0] - (Slong) op2[0]);
}
template<int N>
inline bool iv_all_bits_same(const int *op, bool bit) {
int t = bit ? ~0 : 0;
for(int i=0; i < N; i++)
if(op[i] != t)
return false;
return true;
}
template<> inline bool iv_all_bits_same<0>(const int * /*op*/, bool /*bit*/) { return true; }
template<> inline bool iv_all_bits_same<1>(const int *op, bool bit) {
return op[0] == (bit ? ~0 : 0);
}
template <int N, int Nr>
void iv_neg(const int *op1, int *r) {
Slong l = 0;
for(int k = 0; k < AC_MIN(N,Nr); k++) {
l -= (Ulong) (unsigned) op1[k];
r[k] = (unsigned) l;
l >>= 32;
}
if(Nr > N) {
r[N] = (unsigned) (l - (op1[N-1] < 0 ? ~0 : 0));
iv_extend<Nr-N-1>(r+N+1, r[N] < 0 ? ~0 : 0);
}
}
template <int N, bool S, int Nr>
void iv_abs(const int *op1, int *r) {
if( S && op1[N-1] < 0) {
iv_neg<N,Nr>(op1, r);
} else {
iv_copy<AC_MIN(N,Nr)>(op1, r);
iv_extend<Nr-N>(r+N, 0);
}
}
template<int N, int D, int Q, int R, typename sw2, typename uw2, typename sw4, typename uw4, int w1_length>
void iv_udiv(const sw2 *n, const sw2 *d, sw2 *q, sw2 *r) {
const int w2_length = 2*w1_length;
int d_msi; // most significant int for d
for(d_msi = D-1; d_msi > 0 && !d[d_msi]; d_msi--) {}
uw4 d1 = 0;
if(!d_msi && !d[0]) {
d1 = n[0]/d[0]; // d is zero => divide by zero
return;
}
int n_msi; // most significant int for n
for(n_msi = N-1; n_msi > 0 && !n[n_msi]; n_msi--) {}
for(int i=0; i < Q; i++)
q[i] = 0;
for(int i=0; i < R; i++)
r[i] = n[i];
// write most significant "words" into d1
bool d_mss_odd = (bool) (d[d_msi] >> w1_length);
int d_mss= 2*d_msi + d_mss_odd; // index to most significant short (16-bit)
d1 = (uw4) (uw2) d[d_msi] << (w1_length << (int) !d_mss_odd);
if(d_msi)
d1 |= (uw2) d[d_msi-1] >> (d_mss_odd ? w1_length : 0);
bool n_mss_odd = (bool) (n[n_msi] >> w1_length);
int n_mss = 2*n_msi + n_mss_odd;
if(n_mss < d_mss) {
// q already initialized to 0
// r already initialized to n
} else {
uw2 r1[N+1];
r1[n_msi+1] = 0;
for(int k = n_msi; k >= 0; k--)
r1[k] = n[k];
for(int k = n_mss; k >=d_mss; k--) {
int k_msi = k >> 1;
bool odd = k & 1;
uw2 r1m1 = k_msi > 0 ? r1[k_msi-1] : (uw2) 0;
uw4 n1 = odd ?
(uw4) ((r1[k_msi+1] << w1_length) | (r1[k_msi] >> w1_length)) << w2_length | ((r1[k_msi] << w1_length) | (r1m1 >> w1_length)) :
(uw4) r1[k_msi] << w2_length | r1m1;
uw2 q1 = n1/d1;
if(q1 >> w1_length)
q1--;
AC_ASSERT(!(q1 >> w1_length), "Problem detected in long division algorithm, Please report");
unsigned k2 = k - d_mss;
unsigned k2_i = k2 >> 1;
bool odd_2 = k2 & 1;
uw2 q2 = q1 << (odd_2 ? w1_length : 0);
sw4 l = 0;
for(int j = 0; j <= d_msi; j++) {
l += r1[k2_i + j];
bool l_sign = l < 0;
sw4 prod = (uw4) (uw2) d[j] * (uw4) q2;
l -= prod;
bool ov1 = (l >= 0) & ((prod < 0) | l_sign);
bool ov2 = (l < 0) & (prod < 0) & l_sign;
r1[k2_i + j] = (uw2) l;
l >>= w2_length;
if(ov1)
l |= ((uw4) -1 << w2_length);
if(ov2)
l ^= ((sw4) 1 << w2_length);
}
if(odd_2 | d_mss_odd) {
l += r1[k2_i + d_msi + 1];
r1[k2_i + d_msi + 1] = (uw2) l;
}
if(l < 0) {
l = 0;
for(int j = 0; j <= d_msi; j++) {
l += (sw4) (uw2) d[j] << (odd_2 ? w1_length : 0);
l += r1[k2_i + j];
r1[k2_i + j] = (uw2) l;
l >>= w2_length;
}
if(odd_2 | d_mss_odd)
r1[k2_i + d_msi + 1] += (uw2) l;
q1--;
}
if(Q && k2_i < Q) {
if(odd_2)
q[k2_i] = q1 << w1_length;
else
q[k2_i] |= q1;
}
}
if(R) {
int r_msi = AC_MIN(R-1, n_msi);
for(int j = 0; j <= r_msi; j++)
r[j] = r1[j];
for(int j = r_msi+1; j < R; j++)
r[j] = 0;
}
}
}
template<int N1, int Num_s, int N2, int Den_s, int Nr>
inline void iv_div(const int *op1, const int *op2, int *r) {
enum { N1_over = N1+(Den_s && (Num_s==2)) };
if(N1_over==1 && N2==1) {
r[0] = op1[0] / op2[0];
iv_extend<Nr-N1>(r+1, ((Num_s || Den_s) && (r[0] < 0)) ? ~0 : 0);
}
else if(N1_over==1 && N2==2)
iv_assign_int64<Nr>(r, ( (Slong) op1[0]) / (((Slong) op2[1] << 32) | (unsigned) op2[0]) );
else if(N1_over==2 && N2==1)
if(N1 == 1)
iv_assign_int64<Nr>(r, ( (Slong) op1[0]) / ( (Slong) op2[0]) );
else
iv_assign_int64<Nr>(r, (((Slong) op1[1] << 32) | (unsigned) op1[0]) / ( (Slong) op2[0]) );
else if(N1_over==2 && N2==2)
if(N1 == 1)
iv_assign_int64<Nr>(r, ( (Slong) op1[0]) / (((Slong) op2[1] << 32) | (unsigned) op2[0]) );
else
iv_assign_int64<Nr>(r, (((Slong) op1[1] << 32) | (unsigned) op1[0]) / (((Slong) op2[1] << 32) | (unsigned) op2[0]) );
else if(!Num_s && !Den_s) {
iv_udiv<N1,N2,N1,0,int,unsigned,Slong,Ulong,16>(op1, op2, r, 0);
iv_extend<Nr-N1>(r+N1, 0);
}
else {
enum { N1_neg = N1+(Num_s==2), N2_neg = N2+(Den_s==2)};
int numerator[N1_neg];
int denominator[N2_neg];
int quotient[N1_neg];
iv_abs<N1, (bool) Num_s, N1_neg>(op1, numerator);
iv_abs<N2, (bool) Den_s, N2_neg>(op2, denominator);
iv_udiv<N1_neg,N2_neg,N1_neg,0,int,unsigned,Slong,Ulong,16>(numerator, denominator, quotient, 0);
if( (Num_s && op1[N1-1] < 0) ^ (Den_s && op2[N2-1] < 0) )
iv_neg<N1_neg, Nr>(quotient, r);
else {
iv_copy<AC_MIN(N1_neg,Nr)>(quotient, r);
iv_extend<Nr-N1_neg>(r+N1_neg, (Num_s || Den_s) && r[N1_neg-1] < 0 ? ~0 : 0);
}
}
}
template<int N1, int Num_s, int N2, int Den_s, int Nr>
inline void iv_rem(const int *op1, const int *op2, int *r) {
enum { N1_over = N1+(Den_s && (Num_s==2)) }; // N1_over corresponds to the division
if(N1_over==1 && N2==1) {
r[0] = op1[0] % op2[0];
iv_extend<Nr-1>(r+1, Num_s && r[0] < 0 ? ~0 : 0);
}
else if(N1_over==1 && N2==2)
iv_assign_int64<Nr>(r, ( (Slong) op1[0]) % (((Slong) op2[1] << 32) | (unsigned) op2[0]) );
else if(N1_over==2 && N2==1)
if(N1 == 1)
iv_assign_int64<Nr>(r, ( (Slong) op1[0]) % ( (Slong) op2[0]) );
else
iv_assign_int64<Nr>(r, (((Slong) op1[1] << 32) | (unsigned) op1[0]) % ( (Slong) op2[0]) );
else if(N1_over==2 && N2==2)
if(N1 == 1)
iv_assign_int64<Nr>(r, ( (Slong) op1[0]) % (((Slong) op2[1] << 32) | (unsigned) op2[0]) );
else
iv_assign_int64<Nr>(r, (((Slong) op1[1] << 32) | (unsigned) op1[0]) % (((Slong) op2[1] << 32) | (unsigned) op2[0]) );
else if(!Num_s && !Den_s) {
iv_udiv<N1,N2,0,N2,int,unsigned,Slong,Ulong,16>(op1, op2, 0, r);
iv_extend<Nr-N2>(r+N2, 0);
}
else {
enum { N1_neg = N1+(Num_s==2), N2_neg = N2+(Den_s==2)};
int numerator[N1_neg];
int denominator[N2_neg];
int remainder[N2];
iv_abs<N1, (bool) Num_s, N1_neg>(op1, numerator);
iv_abs<N2, (bool) Den_s, N2_neg>(op2, denominator);
iv_udiv<N1_neg,N2_neg,0,N2,int,unsigned,Slong,Ulong,16>(numerator, denominator, 0, remainder);
if( (Num_s && op1[N1-1] < 0) )
iv_neg<N2, Nr>(remainder, r);
else {
iv_copy<AC_MIN(N2,Nr)>(remainder, r);
iv_extend<Nr-N2>(r+N2, Num_s && r[N2-1] < 0 ? ~0 : 0);
}
}
}
template<int N>
inline void iv_bitwise_complement_n(const int *op, int *r) {
for(int i=0; i < N; i++)
r[i] = ~op[i];
}
template<> inline void iv_bitwise_complement_n<1>(const int *op, int *r) {
r[0] = ~op[0];
}
template<> inline void iv_bitwise_complement_n<2>(const int *op, int *r) {
r[0] = ~op[0];
r[1] = ~op[1];
}
template<int N, int Nr>
inline void iv_bitwise_complement(const int *op, int *r) {
const int M = AC_MIN(N,Nr);
iv_bitwise_complement_n<M>(op, r);
iv_extend<Nr-M>(r+M, (r[M-1] < 0) ? ~0 : 0);
}
template<int N>
inline void iv_bitwise_and_n(const int *op1, const int *op2, int *r) {
for(int i=0; i < N; i++)
r[i] = op1[i] & op2[i];
}
template<> inline void iv_bitwise_and_n<1>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] & op2[0];
}
template<> inline void iv_bitwise_and_n<2>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] & op2[0];
r[1] = op1[1] & op2[1];
}
template<int N1, int N2, int Nr>
inline void iv_bitwise_and(const int *op1, const int *op2, int *r) {
const int M1 = AC_MIN(AC_MAX(N1,N2), Nr);
const int M2 = AC_MIN(AC_MIN(N1,N2), Nr);
const int *OP1 = N1 > N2 ? op1 : op2;
const int *OP2 = N1 > N2 ? op2 : op1;
iv_bitwise_and_n<M2>(op1, op2, r);
if(OP2[M2-1] < 0)
iv_copy<M1-M2>(OP1+M2, r+M2);
else
iv_extend<M1-M2>(r+M2, 0);
iv_extend<Nr-M1>(r+M1, (r[M1-1] < 0) ? ~0 : 0);
}
template<int N>
inline void iv_bitwise_or_n(const int *op1, const int *op2, int *r) {
for(int i=0; i < N; i++)
r[i] = op1[i] | op2[i];
}
template<> inline void iv_bitwise_or_n<1>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] | op2[0];
}
template<> inline void iv_bitwise_or_n<2>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] | op2[0];
r[1] = op1[1] | op2[1];
}
template<int N1, int N2, int Nr>
inline void iv_bitwise_or(const int *op1, const int *op2, int *r) {
const int M1 = AC_MIN(AC_MAX(N1,N2), Nr);
const int M2 = AC_MIN(AC_MIN(N1,N2), Nr);
const int *OP1 = N1 >= N2 ? op1 : op2;
const int *OP2 = N1 >= N2 ? op2 : op1;
iv_bitwise_or_n<M2>(op1, op2, r);
if(OP2[M2-1] < 0)
iv_extend<M1-M2>(r+M2, ~0);
else
iv_copy<M1-M2>(OP1+M2, r+M2);
iv_extend<Nr-M1>(r+M1, (r[M1-1] < 0) ? ~0 : 0);
}
template<int N>
inline void iv_bitwise_xor_n(const int *op1, const int *op2, int *r) {
for(int i=0; i < N; i++)
r[i] = op1[i] ^ op2[i];
}
template<> inline void iv_bitwise_xor_n<1>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] ^ op2[0];
}
template<> inline void iv_bitwise_xor_n<2>(const int *op1, const int *op2, int *r) {
r[0] = op1[0] ^ op2[0];
r[1] = op1[1] ^ op2[1];
}
template<int N1, int N2, int Nr>
inline void iv_bitwise_xor(const int *op1, const int *op2, int *r) {
const int M1 = AC_MIN(AC_MAX(N1,N2), Nr);
const int M2 = AC_MIN(AC_MIN(N1,N2), Nr);
const int *OP1 = N1 >= N2 ? op1 : op2;
const int *OP2 = N1 >= N2 ? op2 : op1;
iv_bitwise_xor_n<M2>(op1, op2, r);
if(OP2[M2-1] < 0)
iv_bitwise_complement_n<M1-M2>(OP1+M2, r+M2);
else
iv_copy<M1-M2>(OP1+M2, r+M2);
iv_extend<Nr-M1>(r+M1, (r[M1-1] < 0) ? ~0 : 0);
}
template<int N, int Nr>
inline void iv_shift_l(const int *op1, unsigned op2, int *r) {
AC_ASSERT(Nr <= N, "iv_shift_l, incorrect usage Nr > N");
unsigned s31 = op2 & 31;
unsigned ishift = (op2 >> 5) > Nr ? Nr : (op2 >> 5);
if(s31 && ishift!=Nr) {
unsigned lw = 0;
for(unsigned i=0; i < Nr; i++) {
unsigned hw = (i >= ishift) ? op1[i-ishift] : 0;
r[i] = (hw << s31) | (lw >> (32-s31));
lw = hw;
}
} else {
for(unsigned i=0; i < Nr ; i++)
r[i] = (i >= ishift) ? op1[i-ishift] : 0;
}
}
template<int N, int Nr>
inline void iv_shift_r(const int *op1, unsigned op2, int *r) {
unsigned s31 = op2 & 31;
unsigned ishift = (op2 >> 5) > N ? N : (op2 >> 5);
int ext = op1[N-1] < 0 ? ~0 : 0;
if(s31 && ishift!=N) {
unsigned lw = (ishift < N) ? op1[ishift] : ext;
for(unsigned i=0; i < Nr; i++) {
unsigned hw = (i+ishift+1 < N) ? op1[i+ishift+1] : ext;
r[i] = (lw >> s31) | (hw << (32-s31));
lw = hw;
}
} else {
for(unsigned i=0; i < Nr ; i++)
r[i] = (i+ishift < N) ? op1[i+ishift] : ext;
}
}
template<int N, int Nr, bool S>
inline void iv_shift_l2(const int *op1, signed op2, int *r) {
if(S && op2 < 0)
iv_shift_r<N,Nr>(op1, -op2, r);
else
iv_shift_l<N,Nr>(op1, op2, r);
}
template<> inline void iv_shift_l2<1,1,false>(const int *op1, signed op2, int *r) {
r[0] = (op2 < 32) ? (op1[0] << op2) : 0;
}
template<> inline void iv_shift_l2<1,1,true>(const int *op1, signed op2, int *r) {
r[0] = (op2 >= 0) ?
(op2 < 32) ? (op1[0] << op2) : 0 :
(op2 > -32) ? (op1[0] >> -op2) : (op1[0] >> 31);
}
template<int N, int Nr, bool S>
inline void iv_shift_r2(const int *op1, signed op2, int *r) {
if(S && op2 < 0)
iv_shift_l<N,Nr>(op1, -op2, r);
else
iv_shift_r<N,Nr>(op1, op2, r);
}
template<> inline void iv_shift_r2<1,1,false>(const int *op1, signed op2, int *r) {
r[0] = (op2 < 32) ? (op1[0] >> op2) : (op1[0] >> 31);
}
template<> inline void iv_shift_r2<1,1,true>(const int *op1, signed op2, int *r) {
r[0] = (op2 >= 0) ?
(op2 < 32) ? (op1[0] >> op2) : (op1[0] >> 31) :
(op2 > -32) ? (op1[0] << -op2) : 0;
}
template<int N, int Nr, int B>
inline void iv_const_shift_l(const int *op1, int *r) {
// B >= 0
if(!B) {
const int M1 = AC_MIN(N,Nr);
iv_copy<M1>(op1, r);
iv_extend<Nr-M1>(r+M1, r[M1-1] < 0 ? -1 : 0);
}
else {
const unsigned s31 = B & 31;
const int ishift = (((B >> 5) > Nr) ? Nr : (B >> 5));
iv_extend<ishift>(r, 0);
const int M1 = AC_MIN(N+ishift,Nr);
if(s31) {
unsigned lw = 0;
for(int i=ishift; i < M1; i++) {
unsigned hw = op1[i-ishift];
r[i] = (hw << s31) | (lw >> ((32-s31)&31)); // &31 is to quiet compilers
lw = hw;
}
if(Nr > M1) {
r[M1] = (signed) lw >> ((32-s31)&31); // &31 is to quiet compilers
iv_extend<Nr-M1-1>(r+M1+1, r[M1] < 0 ? ~0 : 0);
}
} else {
for(int i=ishift; i < M1 ; i++)
r[i] = op1[i-ishift];
iv_extend<Nr-M1>(r+M1, r[M1-1] < 0 ? -1 : 0);
}
}
}
template<> inline void iv_const_shift_l<1,1,0>(const int *op1, int *r) {
r[0] = op1[0];
}
template<> inline void iv_const_shift_l<2,1,0>(const int *op1, int *r) {
r[0] = op1[0];
}
template<int N, int Nr, int B>
inline void iv_const_shift_r(const int *op1, int *r) {
if(!B) {
const int M1 = AC_MIN(N,Nr);
iv_copy<M1>(op1, r);
iv_extend<Nr-M1>(r+M1, r[M1-1] < 0 ? ~0 : 0);
}
else {
const unsigned s31 = B & 31;
const int ishift = (((B >> 5) > N) ? N : (B >> 5));
int ext = op1[N-1] < 0 ? ~0 : 0;
if(s31 && ishift!=N) {
unsigned lw = (ishift < N) ? op1[ishift] : ext;
for(int i=0; i < Nr; i++) {
unsigned hw = (i+ishift+1 < N) ? op1[i+ishift+1] : ext;
r[i] = (lw >> s31) | (hw << ((32-s31)&31)); // &31 is to quiet compilers
lw = hw;
}
} else {
for(int i=0; i < Nr ; i++)
r[i] = (i+ishift < N) ? op1[i+ishift] : ext;
}
}
}
template<> inline void iv_const_shift_r<1,1,0>(const int *op1, int *r) {
r[0] = op1[0];
}
template<> inline void iv_const_shift_r<2,1,0>(const int *op1, int *r) {
r[0] = op1[0];
}
template<int N>
inline void iv_conv_from_fraction(double d, int *r, bool *qb, bool *rbits, bool *o) {
bool b = d < 0;
double d2 = b ? -d : d;
double dfloor = mgc_floor(d2);
*o = dfloor != 0.0;
d2 = d2 - dfloor;
for(int i=N-1; i >=0; i--) {
d2 *= (Ulong) 1 << 32;
unsigned k = (unsigned int) d2;
r[i] = b ? ~k : k;
d2 -= k;
}
d2 *= 2;
bool k = ((int) d2) != 0; // is 0 or 1
d2 -= k;
*rbits = d2 != 0.0;
*qb = (b && *rbits) ^ k;
if(b && !*rbits && !*qb)
iv_uadd_carry<N>(r, true, r);
*o |= b ^ (r[N-1] < 0);
}
template<ac_base_mode b>
inline int to_str(int *v, int w, bool left_just, char *r) {
const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
const unsigned char B = b==AC_BIN ? 1 : (b==AC_OCT ? 3 : (b==AC_HEX ? 4 : 0));
int k = (w+B-1)/B;
int n = (w+31) >> 5;
int bits = 0;
if(b != AC_BIN && left_just) {
if( (bits = -(w % B)) )
r[--k] = 0;
}
for(int i = 0; i < n; i++) {
if (b != AC_BIN && bits < 0)
r[k] += (unsigned char) ((v[i] << (B+bits)) & (b-1));
unsigned int m = (unsigned) v[i] >> -bits;
for(bits += 32; bits > 0 && k; bits -= B) {
r[--k] = (char) (m & (b-1));
m >>= B;
}
}
for(int i=0; i < (w+B-1)/B; i++)
r[i] = digits[(int)r[i]];
return (w+B-1)/B;
}
template<> inline int to_str<AC_DEC>(int *v, int w, bool left_just, char *r) {
int k = 0;
int msw = (w-1) >> 5;
if(left_just) {
unsigned bits_msw = w & 31;
if(bits_msw) {
unsigned left_shift = 32 - bits_msw;
for(int i=msw; i > 0; i--)
v[i] = v[i] << left_shift | (unsigned) v[i-1] >> bits_msw;
v[0] = v[0] << left_shift;
}
int lsw = 0;
while(lsw < msw || v[msw] ) {
Ulong l = 0;
for(int i=lsw; i <= msw; i++) {
l += (Ulong) (unsigned) v[i] * 10;
v[i] = l;
l >>= 32;
if(i==lsw && !v[i])
lsw++;
}
r[k++] = (char) ('0' + (int) l);
}
} else {
const unsigned d = 1000000000; // 10E9
for(; msw > 0 && !v[msw]; msw--) {}
while(msw >= 0) {
Ulong nl = 0;
for(int i = msw; i >= 0; i--) {
nl <<= 32;
nl |= (unsigned) v[i];
unsigned q = nl/d;
nl -= (Ulong) q * d;
v[i] = q;
}
if(!v[msw])
msw--;
bool last = msw == -1;
unsigned rem = (unsigned) nl;
for(int i=0; (i < 9 && !last) || rem; i++) {
r[k++] = (char) ('0' + (int) (rem % 10));
rem /= 10;
}
}
for(int i=0; i < k/2; i++) {
char c = r[i];
r[i] = r[k-1-i];
r[k-1-i] = c;
}
}
r[k] = 0;
return k;
}
inline int to_string(int *v, int w, bool sign_mag, ac_base_mode base, bool left_just, char *r) {
int n = (w+31) >> 5;
bool neg = !sign_mag && v[n-1] < 0;
if(!left_just) {
while(n-- && v[n] == (neg ? ~0 : 0)) {}
int w2 = 32*(n+1);
if(w2) {
int m = v[n];
for(int i = 16; i > 0; i >>= 1) {
if((m >> i) == (neg ? ~0 : 0))
w2 -= i;
else
m >>= i;
}
}
if(w2 < w)
w = w2;
w += !sign_mag;
}
if(base == AC_DEC)
return to_str<AC_DEC>(v, w, left_just, r);
else if (base == AC_HEX)
return to_str<AC_HEX>(v, w, left_just, r);
else if (base == AC_OCT)
return to_str<AC_OCT>(v, w, left_just, r);
else if (base == AC_BIN)
return to_str<AC_BIN>(v, w, left_just, r);
return 0;
}
template<int N>
inline unsigned iv_leading_bits(const int *op, bool bit);
template<> inline unsigned iv_leading_bits<1>(const int *op, bool bit) {
const unsigned char tab[] = {4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
unsigned t = bit ? ~*op : *op;
unsigned cnt = 0;
if(t >> 16)
t >>= 16;
else
cnt += 16;
if(t >> 8)
t >>= 8;
else
cnt += 8;
if(t >> 4)
t >>= 4;
else
cnt += 4;
cnt += tab[t];
return cnt;
}
template<int N>
inline unsigned iv_leading_bits(const int *op, bool bit) {
int ext_sign = bit ? -1 : 0;
int k;
for(k = N-1; k >= 0 && op[k] == ext_sign; k--) {}
return 32*(N-1-k) + (k < 0 ? 0 : iv_leading_bits<1>(op+k, bit));
}
//////////////////////////////////////////////////////////////////////////////
// Integer Vector class: iv
//////////////////////////////////////////////////////////////////////////////
template<int N>
class iv {
protected:
#ifdef __SYNTHESIS__
int v[N];
#else // __SYNTHESIS__
// Fully initialize the underlying int vector for non-synthesis builds.
// Otherwise, LLVM may take advantage of the uninitialized values during
// optimization and will occasionally produce garbage.
int v[N] = {};
#endif // __SYNTHESIS__
public:
template<int N2> friend class iv;
iv() {}
template<int N2>
iv ( const iv<N2> &b ) {
const int M = AC_MIN(N,N2);
iv_copy<M>(b.v, v);
iv_extend<N-M>(v+M, (v[M-1] < 0) ? ~0 : 0);
}
iv ( Slong t) {
iv_assign_int64<N>(v, t);
}
iv ( Ulong t) {
iv_assign_uint64<N>(v, t);
}
iv ( int t) {
v[0] = t;
iv_extend<N-1>(v+1, (t < 0) ? ~0 : 0);
}
iv ( unsigned int t) {
v[0] = t;
iv_extend<N-1>(v+1, 0);
}
iv ( long t) {
if(long_w == 32) {
v[0] = t;
iv_extend<N-1>(v+1, (t < 0) ? ~0 : 0);
} else
iv_assign_int64<N>(v, t);
}
iv ( unsigned long t) {
if(long_w == 32) {
v[0] = t;
iv_extend<N-1>(v+1, 0);
} else
iv_assign_uint64<N>(v, t);
}
iv ( double d ) {
double d2 = ldexpr32<-N>(d);
bool qb, rbits, o;
iv_conv_from_fraction<N>(d2, v, &qb, &rbits, &o);
}
// Explicit conversion functions to C built-in types -------------
inline Slong to_int64() const { return N==1 ? v[0] : ((Ulong)v[1] << 32) | (Ulong) (unsigned) v[0]; }
inline Ulong to_uint64() const { return N==1 ? (Ulong) v[0] : ((Ulong)v[1] << 32) | (Ulong) (unsigned) v[0]; }
inline double to_double() const {
double a = v[N-1];
for(int i=N-2; i >= 0; i--) {
a *= (Ulong) 1 << 32;
a += (unsigned) v[i];
}
return a;
}
inline void conv_from_fraction(double d, bool *qb, bool *rbits, bool *o) {
iv_conv_from_fraction<N>(d, v, qb, rbits, o);
}
template<int N2, int Nr>
inline void mult(const iv<N2> &op2, iv<Nr> &r) const {
iv_mult<N,N2,Nr>(v, op2.v, r.v);
}
template<int N2, int Nr>
void add(const iv<N2> &op2, iv<Nr> &r) const {
iv_add<N,N2,Nr>(v, op2.v, r.v);
}
template<int N2, int Nr>
void sub(const iv<N2> &op2, iv<Nr> &r) const {
iv_sub<N,N2,Nr>(v, op2.v, r.v);
}
template<int Num_s, int N2, int Den_s, int Nr>
void div(const iv<N2> &op2, iv<Nr> &r) const {
iv_div<N,Num_s,N2,Den_s,Nr>(v, op2.v, r.v);
}
template<int Num_s, int N2, int Den_s, int Nr>
void rem(const iv<N2> &op2, iv<Nr> &r) const {
iv_rem<N,Num_s,N2,Den_s,Nr>(v, op2.v, r.v);
}
void increment() {
iv_uadd_carry<N>(v, true, v);
}
void decrement() {
iv_sub_int_borrow<N>(v, 0, true, v);
}
template<int Nr>
void neg(iv<Nr> &r) const {
iv_neg<N,Nr>(v, r.v);
}
template<int Nr>
void shift_l(unsigned op2, iv<Nr> &r) const {
iv_shift_l<N,Nr>(v, op2, r.v);
}
template<int Nr>
void shift_l2(signed op2, iv<Nr> &r) const {
iv_shift_l2<N,Nr,true>(v, op2, r.v);
}
template<int Nr>
void shift_r(unsigned op2, iv<Nr> &r) const {
iv_shift_r<N,Nr>(v, op2, r.v);
}
template<int Nr>
void shift_r2(signed op2, iv<Nr> &r) const {
iv_shift_r2<N,Nr,true>(v, op2, r.v);
}
template<int Nr, int B>
void const_shift_l(iv<Nr> &r) const {
iv_const_shift_l<N,Nr,B>(v, r.v);
}
template<int Nr, int B>
void const_shift_r(iv<Nr> &r) const {
iv_const_shift_r<N,Nr,B>(v, r.v);
}
template<int Nr>
void bitwise_complement(iv<Nr> &r) const {
iv_bitwise_complement<N,Nr>(v, r.v);
}
template<int N2, int Nr>
void bitwise_and(const iv<N2> &op2, iv<Nr> &r) const {
iv_bitwise_and<N,N2,Nr>(v, op2.v, r.v);
}
template<int N2, int Nr>
void bitwise_or(const iv<N2> &op2, iv<Nr> &r) const {
iv_bitwise_or<N,N2,Nr>(v, op2.v, r.v);
}
template<int N2, int Nr>
void bitwise_xor(const iv<N2> &op2, iv<Nr> &r) const {
iv_bitwise_xor<N,N2,Nr>(v, op2.v, r.v);
}
template<int N2>
bool equal(const iv<N2> &op2) const {
return iv_equal<N,N2>(v, op2.v);
}
template<int N2>
bool greater_than(const iv<N2> &op2) const {
return iv_compare<N,N2,true>(v, op2.v);
}
template<int N2>
bool less_than(const iv<N2> &op2) const {
return iv_compare<N,N2,false>(v, op2.v);
}
bool equal_zero() const {
return iv_equal_zero<N>(v);
}
template<int N2>
void set_slc(unsigned lsb, int WS, const iv<N2> &op2) {
AC_ASSERT((31+WS)/32 == N2, "Bad usage: WS greater than length of slice");
unsigned msb = lsb+WS-1;
unsigned lsb_v = lsb >> 5;
unsigned lsb_b = lsb & 31;
unsigned msb_v = msb >> 5;
unsigned msb_b = msb & 31;
if(N2==1) {
if(msb_v == lsb_v)
v[lsb_v] ^= (v[lsb_v] ^ (op2.v[0] << lsb_b)) & (~(WS==32 ? 0 : all_ones<<WS) << lsb_b);
else {
v[lsb_v] ^= (v[lsb_v] ^ (op2.v[0] << lsb_b)) & (all_ones << lsb_b);
unsigned m = (((unsigned) op2.v[0] >> 1) >> (31-lsb_b));
v[msb_v] ^= (v[msb_v] ^ m) & ~((all_ones<<1)<<msb_b);
}
} else {
v[lsb_v] ^= (v[lsb_v] ^ (op2.v[0] << lsb_b)) & (all_ones << lsb_b);
for(int i = 1; i < N2-1; i++)
v[lsb_v+i] = (op2.v[i] << lsb_b) | (((unsigned) op2.v[i-1] >> 1) >> (31-lsb_b));
unsigned t = (op2.v[N2-1] << lsb_b) | (((unsigned) op2.v[N2-2] >> 1) >> (31-lsb_b));
unsigned m;
if(msb_v-lsb_v == N2) {
v[msb_v-1] = t;
m = (((unsigned) op2.v[N2-1] >> 1) >> (31-lsb_b));
}
else
m = t;
v[msb_v] ^= (v[msb_v] ^ m) & ~((all_ones<<1)<<msb_b);
}
}
unsigned leading_bits(bool bit) const {
return iv_leading_bits<N>(v, bit);
}
};
template<> inline Slong iv<1>::to_int64() const { return v[0]; }
template<> inline Ulong iv<1>::to_uint64() const { return v[0]; }
template<> inline Slong iv<2>::to_int64() const {
return ((Ulong)v[1] << 32) | (Ulong) (unsigned) v[0];
}
template<> inline Ulong iv<2>::to_uint64() const {
return ((Ulong)v[1] << 32) | (Ulong) (unsigned) v[0];
}
template<> template<> inline void iv<1>::set_slc(unsigned lsb, int WS, const iv<1> &op2) {
v[0] ^= (v[0] ^ (op2.v[0] << lsb)) & (~(WS==32 ? 0 : all_ones<<WS) << lsb);
}
template<> template<> inline void iv<2>::set_slc(unsigned lsb, int WS, const iv<1> &op2) {
Ulong l = to_uint64();
Ulong l2 = op2.to_uint64();
l ^= (l ^ (l2 << lsb)) & (~((~(Ulong)0)<<WS) << lsb); // WS <= 32
*this = l;
}
template<> template<> inline void iv<2>::set_slc(unsigned lsb, int WS, const iv<2> &op2) {
Ulong l = to_uint64();
Ulong l2 = op2.to_uint64();
l ^= (l ^ (l2 << lsb)) & (~(WS==64 ? (Ulong) 0 : ~(Ulong)0<<WS) << lsb);
*this = l;
}
// add automatic conversion to Slong/Ulong depending on S and C
template<int N, bool S, bool C>
class iv_conv : public iv<N> {
protected:
iv_conv() {}
template<class T> iv_conv(const T& t) : iv<N>(t) {}
};
template<int N>
class iv_conv<N,false,true> : public iv<N> {
public:
operator Ulong () const { return iv<N>::to_uint64(); }
protected:
iv_conv() {}
template<class T> iv_conv(const T& t) : iv<N>(t) {}
};
template<int N>
class iv_conv<N,true,true> : public iv<N> {
public:
operator Slong () const { return iv<N>::to_int64(); }
protected:
iv_conv() {}
template<class T> iv_conv(const T& t) : iv<N>(t) {}
};
// Set default to promote to int as this is the case for almost all types
// create exceptions using specializations
template<typename T>
struct c_prom {
typedef int promoted_type;
};
template<> struct c_prom<unsigned> {
typedef unsigned promoted_type;
};
template<> struct c_prom<long> {
typedef long promoted_type;
};
template<> struct c_prom<unsigned long> {
typedef unsigned long promoted_type;
};
template<> struct c_prom<Slong> {
typedef Slong promoted_type;
};
template<> struct c_prom<Ulong> {
typedef Ulong promoted_type;
};
template<> struct c_prom<float> {
typedef float promoted_type;
};
template<> struct c_prom<double> {
typedef double promoted_type;
};
template<typename T, typename T2>
struct c_arith {
// will error out for pairs of T and T2 that are not defined through specialization
};
template<typename T> struct c_arith<T,T> {
typedef T arith_conv;
};
#define C_ARITH(C_TYPE1, C_TYPE2) \
template<> struct c_arith<C_TYPE1, C_TYPE2> { \
typedef C_TYPE1 arith_conv; \
}; \
template<> struct c_arith<C_TYPE2, C_TYPE1> { \
typedef C_TYPE1 arith_conv; \
};
C_ARITH(double, float)
C_ARITH(double, int)
C_ARITH(double, unsigned)
C_ARITH(double, long)
C_ARITH(double, unsigned long)
C_ARITH(double, Slong)
C_ARITH(double, Ulong)
C_ARITH(float, int)
C_ARITH(float, unsigned)
C_ARITH(float, long)
C_ARITH(float, unsigned long)
C_ARITH(float, Slong)
C_ARITH(float, Ulong)
C_ARITH(Slong, int)
C_ARITH(Slong, unsigned)
C_ARITH(Ulong, int)
C_ARITH(Ulong, unsigned)
template<typename T>
struct map {
typedef T t;
};
template<typename T>
struct c_type_params {
// will error out for T for which this template struct is not specialized
};
template<typename T> inline const char *c_type_name() { return "unknown"; }
template<> inline const char *c_type_name<bool>() { return "bool";}
template<> inline const char *c_type_name<char>() { return "char";}
template<> inline const char *c_type_name<signed char>() { return "signed char";}
template<> inline const char *c_type_name<unsigned char>() { return "unsigned char";}
template<> inline const char *c_type_name<signed short>() { return "signed short";}
template<> inline const char *c_type_name<unsigned short>() { return "unsigned short";}
template<> inline const char *c_type_name<int>() { return "int";}
template<> inline const char *c_type_name<unsigned>() { return "unsigned";}
template<> inline const char *c_type_name<signed long>() { return "signed long";}
template<> inline const char *c_type_name<unsigned long>() { return "unsigned long";}
template<> inline const char *c_type_name<signed long long>() { return "signed long long";}
template<> inline const char *c_type_name<unsigned long long>() { return "unsigned long long";}
template<> inline const char *c_type_name<float>() { return "float";}
template<> inline const char *c_type_name<double>() { return "double";}
template<typename T> struct c_type;
template<typename T>
struct rt_c_type_T {
template<typename T2>
struct op1 {
typedef typename T::template rt_T< c_type<T2> >::mult mult;
typedef typename T::template rt_T< c_type<T2> >::plus plus;
typedef typename T::template rt_T< c_type<T2> >::minus2 minus;
typedef typename T::template rt_T< c_type<T2> >::minus minus2;
typedef typename T::template rt_T< c_type<T2> >::logic logic;
typedef typename T::template rt_T< c_type<T2> >::div2 div;
typedef typename T::template rt_T< c_type<T2> >::div div2;
};
};
template<typename T>
struct c_type {
typedef typename c_prom<T>::promoted_type c_prom_T;
struct rt_unary {
typedef c_prom_T neg;
typedef c_prom_T mag_sqr;
typedef c_prom_T mag;
template<unsigned N>
struct set {
typedef c_prom_T sum;
};
};
template<typename T2>
struct rt_T {
typedef typename rt_c_type_T<T2>::template op1<T>::mult mult;
typedef typename rt_c_type_T<T2>::template op1<T>::plus plus;
typedef typename rt_c_type_T<T2>::template op1<T>::minus minus;
typedef typename rt_c_type_T<T2>::template op1<T>::minus2 minus2;
typedef typename rt_c_type_T<T2>::template op1<T>::logic logic;
typedef typename rt_c_type_T<T2>::template op1<T>::div div;
typedef typename rt_c_type_T<T2>::template op1<T>::div2 div2;
};
inline static std::string type_name() {
std::string r = c_type_name<T>();
return r;
}
};
// with T == c_type
template<typename T>
struct rt_c_type_T< c_type<T> > {
typedef typename c_prom<T>::promoted_type c_prom_T;
template<typename T2>
struct op1 {
typedef typename c_prom<T2>::promoted_type c_prom_T2;
typedef typename c_arith< c_prom_T, c_prom_T2 >::arith_conv mult;
typedef typename c_arith< c_prom_T, c_prom_T2 >::arith_conv plus;
typedef typename c_arith< c_prom_T, c_prom_T2 >::arith_conv minus;
typedef typename c_arith< c_prom_T, c_prom_T2 >::arith_conv minus2;
typedef typename c_arith< c_prom_T, c_prom_T2 >::arith_conv logic;
typedef typename c_arith< c_prom_T, c_prom_T2 >::arith_conv div;
typedef typename c_arith< c_prom_T, c_prom_T2 >::arith_conv div2;
};
};
#define C_TYPE_MAP(C_TYPE) \
template<> struct map<C_TYPE> { \
typedef c_type<C_TYPE> t; \
};
#define C_TYPE_PARAMS(C_TYPE, WI, SI) \
template<> struct c_type_params<C_TYPE> { \
enum { W = WI, I = WI, E = 0, S = SI, floating_point = 0 }; \
};
#define C_TYPE_MAP_INT(C_TYPE, WI, SI) \
C_TYPE_MAP(C_TYPE) \
C_TYPE_PARAMS(C_TYPE, WI, SI)
#define C_TYPE_MAP_FLOAT(C_TYPE, FP, WFP, IFP, EFP) \
C_TYPE_MAP(C_TYPE) \
template<> struct c_type_params<C_TYPE> { \
enum { W = WFP, I = IFP, E = EFP, S = true, floating_point = FP }; \
};
C_TYPE_MAP_INT(bool, 1, false)
C_TYPE_MAP_INT(char, 8, true)
C_TYPE_MAP_INT(signed char, 8, true)
C_TYPE_MAP_INT(unsigned char, 8, false)
C_TYPE_MAP_INT(signed short, 16, true)
C_TYPE_MAP_INT(unsigned short, 16, false)
C_TYPE_MAP_INT(signed int, 32, true)
C_TYPE_MAP_INT(unsigned int, 32, false)
C_TYPE_MAP_INT(signed long, ac_private::long_w, true)
C_TYPE_MAP_INT(unsigned long, ac_private::long_w, false)
C_TYPE_MAP_INT(signed long long, 64, true)
C_TYPE_MAP_INT(unsigned long long, 64, false)
C_TYPE_MAP_FLOAT(float, 1, 25, 1, 8)
C_TYPE_MAP_FLOAT(double, 2, 54, 1, 11)
#undef C_TYPE_INT
#undef C_TYPE_PARAMS
#undef C_TYPE_FLOAT
#undef C_TYPE_MAP
// specializations for following struct declared/defined after definition of ac_int
template<typename T>
struct rt_ac_int_T {
template<int W, bool S>
struct op1 {
typedef typename T::template rt_T< ac_int<W,S> >::mult mult;
typedef typename T::template rt_T< ac_int<W,S> >::plus plus;
typedef typename T::template rt_T< ac_int<W,S> >::minus2 minus;
typedef typename T::template rt_T< ac_int<W,S> >::minus minus2;
typedef typename T::template rt_T< ac_int<W,S> >::logic logic;
typedef typename T::template rt_T< ac_int<W,S> >::div2 div;
typedef typename T::template rt_T< ac_int<W,S> >::div div2;
};
};
}
namespace ac {
// compiler time constant for log2 like functions
template<unsigned X>
struct nbits {
enum { val = ac_private::s_N<16>::s_X<X>::nbits };
};
template<unsigned X>
struct log2_floor {
enum { val = nbits<X>::val - 1 };
};
// log2 of 0 is not defined: generate compiler error
template<> struct log2_floor<0> {};
template<unsigned X>
struct log2_ceil {
enum { lf = log2_floor<X>::val, val = (X == (1 << lf) ? lf : lf+1) };
};
// log2 of 0 is not defined: generate compiler error
template<> struct log2_ceil<0> {};
template<int LowerBound, int UpperBound>
struct int_range {
enum { l_s = (LowerBound < 0), u_s = (UpperBound < 0),
signedness = l_s || u_s,
l_nbits = nbits<AC_ABS(LowerBound+l_s)+l_s>::val,
u_nbits = nbits<AC_ABS(UpperBound+u_s)+u_s>::val,
nbits = AC_MAX(l_nbits, u_nbits + (!u_s && signedness))
};
typedef ac_int<nbits, signedness> type;
};
}
enum ac_q_mode { AC_TRN, AC_RND, AC_TRN_ZERO, AC_RND_ZERO, AC_RND_INF, AC_RND_MIN_INF, AC_RND_CONV, AC_RND_CONV_ODD };
enum ac_o_mode { AC_WRAP, AC_SAT, AC_SAT_ZERO, AC_SAT_SYM };
template<int W2, int I2, bool S2, ac_q_mode Q2, ac_o_mode O2> class ac_fixed;
//////////////////////////////////////////////////////////////////////////////
// Arbitrary-Length Integer: ac_int
//////////////////////////////////////////////////////////////////////////////
template<int W, bool S=true>
class ac_int : public ac_private::iv_conv<(W+31+!S)/32, S, W<=64>,public ac_base_type
#ifndef __SYNTHESIS__
__AC_INT_UTILITY_BASE
#endif
{
#if defined(__SYNTHESIS__) && !defined(AC_IGNORE_BUILTINS)
#pragma builtin
#endif
enum {N=(W+31+!S)/32};
typedef ac_private::iv_conv<N, S, W <= 64> ConvBase;
typedef ac_private::iv<N> Base;
inline void bit_adjust() {
const unsigned rem = (32-W)&31;
Base::v[N-1] = S ? ((Base::v[N-1] << rem) >> rem) : (rem ?
((unsigned) Base::v[N-1] << rem) >> rem : 0);
}
inline bool is_neg() const { return S && Base::v[N-1] < 0; }
// returns false if number is denormal
template<int WE, bool SE>
bool normalize_private(ac_int<WE,SE> &exp, bool reserved_min_exp=false) {
int expt = exp;
int lshift = leading_sign();
bool fully_normalized = true;
ac_int<WE, SE> min_exp;
min_exp.template set_val<AC_VAL_MIN>();
int max_shift = exp - min_exp - reserved_min_exp;
if(lshift > max_shift) {
lshift = ac_int<WE,false>(max_shift);
expt = min_exp + reserved_min_exp;
fully_normalized = false;
} else {
expt -= lshift;
}
if(Base::equal_zero()) {
expt = 0;
fully_normalized = true;
}
exp = expt;
Base r;
Base::shift_l(lshift, r);
Base::operator=(r);
bit_adjust();
return fully_normalized;
}
public:
static const int width = W;
static const int i_width = W;
static const bool sign = S;
static const ac_q_mode q_mode = AC_TRN;
static const ac_o_mode o_mode = AC_WRAP;
static const int e_width = 0;
struct is_ac_basic_type : std::true_type {};
template<int W2, bool S2>
struct rt {
enum {
mult_w = W+W2,
mult_s = S||S2,
plus_w = AC_MAX(W+(S2&&!S),W2+(S&&!S2))+1,
plus_s = S||S2,
minus_w = AC_MAX(W+(S2&&!S),W2+(S&&!S2))+1,
minus_s = true,
div_w = W+S2,
div_s = S||S2,
mod_w = AC_MIN(W,W2+(!S2&&S)),
mod_s = S,
logic_w = AC_MAX(W+(S2&&!S),W2+(S&&!S2)),
logic_s = S||S2
};
typedef ac_int<mult_w, mult_s> mult;
typedef ac_int<plus_w, plus_s> plus;
typedef ac_int<minus_w, minus_s> minus;
typedef ac_int<logic_w, logic_s> logic;
typedef ac_int<div_w, div_s> div;
typedef ac_int<mod_w, mod_s> mod;
typedef ac_int<W, S> arg1;
};
template<typename T>
struct rt_T {
typedef typename ac_private::map<T>::t map_T;
typedef typename ac_private::rt_ac_int_T<map_T>::template op1<W,S>::mult mult;
typedef typename ac_private::rt_ac_int_T<map_T>::template op1<W,S>::plus plus;
typedef typename ac_private::rt_ac_int_T<map_T>::template op1<W,S>::minus minus;
typedef typename ac_private::rt_ac_int_T<map_T>::template op1<W,S>::minus2 minus2;
typedef typename ac_private::rt_ac_int_T<map_T>::template op1<W,S>::logic logic;
typedef typename ac_private::rt_ac_int_T<map_T>::template op1<W,S>::div div;
typedef typename ac_private::rt_ac_int_T<map_T>::template op1<W,S>::div2 div2;
typedef ac_int<W, S> arg1;
};
struct rt_unary {
enum {
neg_w = W+1,
neg_s = true,
mag_sqr_w = 2*W-S,
mag_sqr_s = false,
mag_w = W+S,
mag_s = false,
leading_sign_w = ac::log2_ceil<W+!S>::val,
leading_sign_s = false
};
typedef ac_int<neg_w, neg_s> neg;
typedef ac_int<mag_sqr_w, mag_sqr_s> mag_sqr;
typedef ac_int<mag_w, mag_s> mag;
typedef ac_int<leading_sign_w, leading_sign_s> leading_sign;
template<unsigned N>
struct set {
enum { sum_w = W + ac::log2_ceil<N>::val, sum_s = S};
typedef ac_int<sum_w, sum_s> sum;
};
};
template<int W2, bool S2> friend class ac_int;
template<int W2, int I2, bool S2, ac_q_mode Q2, ac_o_mode O2> friend class ac_fixed;
ac_int() {
#if !defined(__SYNTHESIS__) && defined(AC_DEFAULT_IN_RANGE)
bit_adjust();
#endif
}
template<int W2, bool S2>
inline ac_int (const ac_int<W2,S2> &op) {
Base::operator =(op);
bit_adjust();
}
inline ac_int( bool b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( char b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( signed char b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( unsigned char b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( signed short b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( unsigned short b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( signed int b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( unsigned int b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( signed long b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( unsigned long b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( Slong b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( Ulong b ) : ConvBase(b) { bit_adjust(); }
inline ac_int( double d ) : ConvBase(d) { bit_adjust(); }
#if (defined(_MSC_VER) && !defined(__EDG__))
#pragma warning( push )
#pragma warning( disable: 4700 )
#endif
#if (defined(__GNUC__) && ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 || __GNUC__ > 4 ) && !defined(__EDG__))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
#endif
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wuninitialized"
#endif
template<ac_special_val V>
inline ac_int &set_val() {
if(V == AC_VAL_DC) {
ac_int r;
Base::operator =(r);
bit_adjust();
}
else if(V == AC_VAL_0 || V == AC_VAL_MIN || V == AC_VAL_QUANTUM) {
Base::operator =(0);
if(S && V == AC_VAL_MIN) {
const unsigned int rem = (W-1)&31;
Base::v[N-1] = (-1 << rem);
} else if(V == AC_VAL_QUANTUM)
Base::v[0] = 1;
}
else if(AC_VAL_MAX) {
Base::operator =(-1);
const unsigned int rem = (32-W - (unsigned) !S )&31;
Base::v[N-1] = ((unsigned) (-1) >> 1) >> rem;
}
return *this;
}
#if (defined(_MSC_VER) && !defined(__EDG__))
#pragma warning( pop )
#endif
#if (defined(__GNUC__) && ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 || __GNUC__ > 4 ) && !defined(__EDG__))
#pragma GCC diagnostic pop
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
// Explicit conversion functions to C built-in types -------------
inline int to_int() const { return Base::v[0]; }
inline unsigned to_uint() const { return Base::v[0]; }
inline long to_long() const {
return ac_private::long_w == 32 ? (long) Base::v[0] : (long) Base::to_int64();
}
inline unsigned long to_ulong() const {
return ac_private::long_w == 32 ? (unsigned long) Base::v[0] : (unsigned long) Base::to_uint64();
}
inline Slong to_int64() const { return Base::to_int64(); }
inline Ulong to_uint64() const { return Base::to_uint64(); }
inline double to_double() const { return Base::to_double(); }
inline int length() const { return W; }
inline std::string to_string(ac_base_mode base_rep, bool sign_mag = false) const {
// base_rep == AC_DEC => sign_mag == don't care (always print decimal in sign magnitude)
char r[N*32+4] = {0};
int i = 0;
if(sign_mag)
r[i++] = is_neg() ? '-' : '+';
else if (base_rep == AC_DEC && is_neg())
r[i++] = '-';
if(base_rep != AC_DEC) {
r[i++] = '0';
r[i++] = base_rep == AC_BIN ? 'b' : (base_rep == AC_OCT ? 'o' : 'x');
}
int str_w;
if( (base_rep == AC_DEC || sign_mag) && is_neg() ) {
ac_int<W, false> mag = operator -();
str_w = ac_private::to_string(mag.v, W+1, sign_mag, base_rep, false, r+i);
} else {
ac_int<W,S> tmp = *this;
str_w = ac_private::to_string(tmp.v, W+!S, sign_mag, base_rep, false, r+i);
}
if(!str_w) {
r[i] = '0';
r[i+1] = 0;
}
return std::string(r);
}
inline static std::string type_name() {
const char *tf[] = {",false>", ",true>"};
std::string r = "ac_int<";
r += ac_int<32,true>(W).to_string(AC_DEC);
r += tf[S];
return r;
}
// Arithmetic : Binary ----------------------------------------------------
template<int W2, bool S2>
typename rt<W2,S2>::mult operator *( const ac_int<W2,S2> &op2) const {
typename rt<W2,S2>::mult r;
Base::mult(op2, r);
return r;
}
template<int W2, bool S2>
typename rt<W2,S2>::plus operator +( const ac_int<W2,S2> &op2) const {
typename rt<W2,S2>::plus r;
Base::add(op2, r);
return r;
}
template<int W2, bool S2>
typename rt<W2,S2>::minus operator -( const ac_int<W2,S2> &op2) const {
typename rt<W2,S2>::minus r;
Base::sub(op2, r);
return r;
}
#if (defined(__GNUC__) && ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 || __GNUC__ > 4 ) && !defined(__EDG__))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wenum-compare"
#endif
template<int W2, bool S2>
typename rt<W2,S2>::div operator /( const ac_int<W2,S2> &op2) const {
typename rt<W2,S2>::div r;
enum {Nminus = ac_int<W+S,S>::N, N2 = ac_int<W2,S2>::N, N2minus = ac_int<W2+S2,S2>::N,
num_s = S + (Nminus > N), den_s = S2 + (N2minus > N2), Nr = rt<W2,S2>::div::N };
Base::template div<num_s, N2, den_s, Nr>(op2, r);
return r;
}
template<int W2, bool S2>
typename rt<W2,S2>::mod operator %( const ac_int<W2,S2> &op2) const {
typename rt<W2,S2>::mod r;
enum {Nminus = ac_int<W+S,S>::N, N2 = ac_int<W2,S2>::N, N2minus = ac_int<W2+S2,S2>::N,
num_s = S + (Nminus > N), den_s = S2 + (N2minus > N2), Nr = rt<W2,S2>::mod::N };
Base::template rem<num_s, N2, den_s, Nr>(op2, r);
return r;
}
#if (defined(__GNUC__) && ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 || __GNUC__ > 4 ) && !defined(__EDG__))
#pragma GCC diagnostic pop
#endif
// Arithmetic assign ------------------------------------------------------
template<int W2, bool S2>
ac_int &operator *=( const ac_int<W2,S2> &op2) {
Base r;
Base::mult(op2, r);
Base::operator=(r);
bit_adjust();
return *this;
}
template<int W2, bool S2>
ac_int &operator +=( const ac_int<W2,S2> &op2) {
Base r;
Base::add(op2, r);
Base::operator=(r);
bit_adjust();
return *this;
}
template<int W2, bool S2>
ac_int &operator -=( const ac_int<W2,S2> &op2) {
Base r;
Base::sub(op2, r);
Base::operator=(r);
bit_adjust();
return *this;
}
#if (defined(__GNUC__) && ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 || __GNUC__ > 4 ) && !defined(__EDG__))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wenum-compare"
#endif
template<int W2, bool S2>
ac_int &operator /=( const ac_int<W2,S2> &op2) {
enum {Nminus = ac_int<W+S,S>::N, N2 = ac_int<W2,S2>::N, N2minus = ac_int<W2+S2,S2>::N,
num_s = S + (Nminus > N), den_s = S2 + (N2minus > N2), Nr = N };
Base r;
Base::template div<num_s, N2, den_s, Nr>(op2, r);
Base::operator=(r);
bit_adjust();
return *this;
}
template<int W2, bool S2>
ac_int &operator %=( const ac_int<W2,S2> &op2) {
enum {Nminus = ac_int<W+S,S>::N, N2 = ac_int<W2,S2>::N, N2minus = ac_int<W2+S2,S2>::N,
num_s = S + (Nminus > N), den_s = S2 + (N2minus > N2), Nr = N };
Base r;
Base::template rem<num_s, N2, den_s, Nr>(op2, r);
Base::operator=(r);
bit_adjust();
return *this;
}
#if (defined(__GNUC__) && ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 || __GNUC__ > 4 ) && !defined(__EDG__))
#pragma GCC diagnostic pop
#endif
// Arithmetic prefix increment, decrement ----------------------------------
ac_int &operator ++() {
Base::increment();
bit_adjust();
return *this;
}
ac_int &operator --() {
Base::decrement();
bit_adjust();
return *this;
}
// Arithmetic postfix increment, decrement ---------------------------------
const ac_int operator ++(int) {
ac_int t = *this;
Base::increment();
bit_adjust();
return t;
}
const ac_int operator --(int) {
ac_int t = *this;
Base::decrement();
bit_adjust();
return t;
}
// Arithmetic Unary --------------------------------------------------------
ac_int operator +() {
return *this;
}
typename rt_unary::neg operator -() const {
typename rt_unary::neg r;
Base::neg(r);
r.bit_adjust();
return r;
}
// ! ------------------------------------------------------------------------
bool operator ! () const {
return Base::equal_zero();
}
// Bitwise (arithmetic) unary: complement -----------------------------
ac_int<W+!S, true> operator ~() const {
ac_int<W+!S, true> r;
Base::bitwise_complement(r);
return r;
}
// Bitwise (non-arithmetic) bit_complement -----------------------------
ac_int<W, false> bit_complement() const {
ac_int<W, false> r;
Base::bitwise_complement(r);
r.bit_adjust();
return r;
}
// Bitwise (arithmetic): and, or, xor ----------------------------------
template<int W2, bool S2>
typename rt<W2,S2>::logic operator & ( const ac_int<W2,S2> &op2) const {
typename rt<W2,S2>::logic r;
Base::bitwise_and(op2, r);
return r;
}
template<int W2, bool S2>
typename rt<W2,S2>::logic operator | ( const ac_int<W2,S2> &op2) const {
typename rt<W2,S2>::logic r;
Base::bitwise_or(op2, r);
return r;
}
template<int W2, bool S2>
typename rt<W2,S2>::logic operator ^ ( const ac_int<W2,S2> &op2) const {
typename rt<W2,S2>::logic r;
Base::bitwise_xor(op2, r);
return r;
}
// Bitwise assign (not arithmetic): and, or, xor ----------------------------
template<int W2, bool S2>
ac_int &operator &= ( const ac_int<W2,S2> &op2 ) {
Base r;
Base::bitwise_and(op2, r);
Base::operator=(r);
bit_adjust();
return *this;
}
template<int W2, bool S2>
ac_int &operator |= ( const ac_int<W2,S2> &op2 ) {
Base r;
Base::bitwise_or(op2, r);
Base::operator=(r);
bit_adjust();
return *this;
}
template<int W2, bool S2>
ac_int &operator ^= ( const ac_int<W2,S2> &op2 ) {
Base r;
Base::bitwise_xor(op2, r);
Base::operator=(r);
bit_adjust();
return *this;
}
// Shift (result constrained by left operand) -------------------------------
template<int W2>
ac_int operator << ( const ac_int<W2,true> &op2 ) const {
ac_int r;
Base::shift_l2(op2.to_int(), r);
r.bit_adjust();
return r;
}
template<int W2>
ac_int operator << ( const ac_int<W2,false> &op2 ) const {
ac_int r;
Base::shift_l(op2.to_uint(), r);
r.bit_adjust();
return r;
}
template<int W2>
ac_int operator >> ( const ac_int<W2,true> &op2 ) const {
ac_int r;
Base::shift_r2(op2.to_int(), r);
r.bit_adjust();
return r;
}
template<int W2>
ac_int operator >> ( const ac_int<W2,false> &op2 ) const {
ac_int r;
Base::shift_r(op2.to_uint(), r);
r.bit_adjust();
return r;
}
// Shift assign ------------------------------------------------------------
template<int W2>
ac_int &operator <<= ( const ac_int<W2,true> &op2 ) {
Base r;
Base::shift_l2(op2.to_int(), r);
Base::operator=(r);
bit_adjust();
return *this;
}
template<int W2>
ac_int &operator <<= ( const ac_int<W2,false> &op2 ) {
Base r;
Base::shift_l(op2.to_uint(), r);
Base::operator=(r);
bit_adjust();
return *this;
}
template<int W2>
ac_int &operator >>= ( const ac_int<W2,true> &op2 ) {
Base r;
Base::shift_r2(op2.to_int(), r);
Base::operator=(r);
bit_adjust();
return *this;
}
template<int W2>
ac_int &operator >>= ( const ac_int<W2,false> &op2 ) {
Base r;
Base::shift_r(op2.to_uint(), r);
Base::operator=(r);
bit_adjust();
return *this;
}
// Relational ---------------------------------------------------------------
template<int W2, bool S2>
bool operator == ( const ac_int<W2,S2> &op2) const {
return Base::equal(op2);
}
template<int W2, bool S2>
bool operator != ( const ac_int<W2,S2> &op2) const {
return !Base::equal(op2);
}
template<int W2, bool S2>
bool operator < ( const ac_int<W2,S2> &op2) const {
return Base::less_than(op2);
}
template<int W2, bool S2>
bool operator >= ( const ac_int<W2,S2> &op2) const {
return !Base::less_than(op2);
}
template<int W2, bool S2>
bool operator > ( const ac_int<W2,S2> &op2) const {
return Base::greater_than(op2);
}
template<int W2, bool S2>
bool operator <= ( const ac_int<W2,S2> &op2) const {
return !Base::greater_than(op2);
}
// Bit and Slice Select -----------------------------------------------------
template<int WS, int WX, bool SX>
inline ac_int<WS,S> slc(const ac_int<WX,SX> &index) const {
using ac_intX = ac_int<WX,SX>;
ac_int<WS,S> r;
AC_ASSERT(index >= ac_intX(0), "Attempting to read slc with negative indeces");
ac_int<WX-SX, false> uindex = index;
Base::shift_r(uindex.to_uint(), r);
r.bit_adjust();
return r;
}
template<int WS>
inline ac_int<WS,S> slc(signed index) const {
ac_int<WS,S> r;
AC_ASSERT(index >= 0, "Attempting to read slc with negative indeces");
unsigned uindex = index & ((unsigned)~0 >> 1);
Base::shift_r(uindex, r);
r.bit_adjust();
return r;
}
template<int WS>
inline ac_int<WS,S> slc(unsigned uindex) const {
ac_int<WS,S> r;
Base::shift_r(uindex, r);
r.bit_adjust();
return r;
}
template<int W2, bool S2, int WX, bool SX>
inline ac_int &set_slc(const ac_int<WX,SX> lsb, const ac_int<W2,S2> &slc) {
AC_ASSERT(lsb.to_int() + W2 <= W && lsb.to_int() >= 0, "Out of bounds set_slc");
ac_int<WX-SX, false> ulsb = lsb;
Base::set_slc(ulsb.to_uint(), W2, (ac_int<W2,true>) slc);
bit_adjust(); // in case sign bit was assigned
return *this;
}
template<int W2, bool S2>
inline ac_int &set_slc(signed lsb, const ac_int<W2,S2> &slc) {
AC_ASSERT(lsb + W2 <= W && lsb >= 0, "Out of bounds set_slc");
unsigned ulsb = lsb & ((unsigned)~0 >> 1);
Base::set_slc(ulsb, W2, (ac_int<W2,true>) slc);
bit_adjust(); // in case sign bit was assigned
return *this;
}
template<int W2, bool S2>
inline ac_int &set_slc(unsigned ulsb, const ac_int<W2,S2> &slc) {
AC_ASSERT(ulsb + W2 <= W, "Out of bounds set_slc");
Base::set_slc(ulsb, W2, (ac_int<W2,true>) slc);
bit_adjust(); // in case sign bit was assigned
return *this;
}
class ac_bitref {
# if defined(__SYNTHESIS__) && !defined(AC_IGNORE_BUILTINS)
# pragma builtin
# endif
ac_int &d_bv;
unsigned d_index;
public:
ac_bitref( ac_int *bv, unsigned index=0 ) : d_bv(*bv), d_index(index) {}
operator bool () const { return (d_index < W) ? (d_bv.v[d_index>>5]>>(d_index&31) & 1) : 0; }
template<int W2, bool S2>
operator ac_int<W2,S2> () const { return operator bool (); }
inline ac_bitref operator = ( int val ) {
// lsb of int (val&1) is written to bit
if(d_index < W) {
int *pval = &d_bv.v[d_index>>5];
*pval ^= (*pval ^ (val << (d_index&31) )) & 1 << (d_index&31);
d_bv.bit_adjust(); // in case sign bit was assigned
}
return *this;
}
template<int W2, bool S2>
inline ac_bitref operator = ( const ac_int<W2,S2> &val ) {
return operator =(val.to_int());
}
inline ac_bitref operator = ( const ac_bitref &val ) {
return operator =((int) (bool) val);
}
};
ac_bitref operator [] ( unsigned int uindex) {
AC_ASSERT(uindex < W, "Attempting to read bit beyond MSB");
ac_bitref bvh( this, uindex );
return bvh;
}
ac_bitref operator [] ( int index) {
AC_ASSERT(index >= 0, "Attempting to read bit with negative index");
AC_ASSERT(index < W, "Attempting to read bit beyond MSB");
unsigned uindex = index & ((unsigned)~0 >> 1);
ac_bitref bvh( this, uindex );
return bvh;
}
template<int W2, bool S2>
ac_bitref operator [] ( const ac_int<W2,S2> &index) {
AC_ASSERT(index >= 0, "Attempting to read bit with negative index");
AC_ASSERT(index < W, "Attempting to read bit beyond MSB");
ac_int<W2-S2,false> uindex = index;
ac_bitref bvh( this, uindex.to_uint() );
return bvh;
}
bool operator [] ( unsigned int uindex) const {
AC_ASSERT(uindex < W, "Attempting to read bit beyond MSB");
return (uindex < W) ? (Base::v[uindex>>5]>>(uindex&31) & 1) : 0;
}
bool operator [] ( int index) const {
AC_ASSERT(index >= 0, "Attempting to read bit with negative index");
AC_ASSERT(index < W, "Attempting to read bit beyond MSB");
unsigned uindex = index & ((unsigned)~0 >> 1);
return (uindex < W) ? (Base::v[uindex>>5]>>(uindex&31) & 1) : 0;
}
template<int W2, bool S2>
bool operator [] ( const ac_int<W2,S2> &index) const {
AC_ASSERT(index >= 0, "Attempting to read bit with negative index");
AC_ASSERT(index < W, "Attempting to read bit beyond MSB");
ac_int<W2-S2,false> uindex = index;
return (uindex < W) ? (Base::v[uindex>>5]>>(uindex.to_uint()&31) & 1) : 0;
}
#if 0
unsigned int leading_bits(bool bit) const {
return Base::leading_bits(bit) - (32*N - W);
}
#endif
typename rt_unary::leading_sign leading_sign() const {
unsigned ls = Base::leading_bits(S & (Base::v[N-1] < 0)) - (32*N - W)-S;
return ls;
}
typename rt_unary::leading_sign leading_sign(bool &all_sign) const {
unsigned ls = Base::leading_bits(S & (Base::v[N-1] < 0)) - (32*N - W)-S;
all_sign = (ls == W-S);
return ls;
}
// returns false if number is denormal
template<int WE, bool SE>
bool normalize(ac_int<WE,SE> &exp) {
return normalize_private(exp);
}
// returns false if number is denormal, minimum exponent is reserved (usually for encoding special values/errors)
template<int WE, bool SE>
bool normalize_RME(ac_int<WE,SE> &exp) {
return normalize_private(exp, true);
}
bool and_reduce() const {
return ac_private::iv_equal_ones_to<W,N>(Base::v);
}
bool or_reduce() const {
return !Base::equal_zero();
}
bool xor_reduce() const {
unsigned r = Base::v[N-1];
if(S) {
const unsigned rem = (32-W)&31;
r = (r << rem) >> rem;
}
if(N > 1)
r ^= Base::v[N-2];
if(N > 2) {
for(int i=0; i<N-2; i++)
r ^= Base::v[i];
}
if(W > 16)
r ^= r >> 16;
if(W > 8)
r ^= r >> 8;
if(W > 4)
r ^= r >> 4;
if(W > 2)
r ^= r >> 2;
if(W > 1)
r ^= r >> 1;
return r&1;
}
inline void bit_fill_hex(const char *str) {
// Zero Pads if str is too short, throws ms bits away if str is too long
// Asserts if anything other than 0-9a-fA-F is encountered
ac_int<W,S> res = 0;
while(str) {
char c = *str;
int h = 0;
if(c >= '0' && c <= '9')
h = c - '0';
else if(c >= 'A' && c <= 'F')
h = c - 'A' + 10;
else if(c >= 'a' && c <= 'f')
h = c - 'a' + 10;
else {
AC_ASSERT(!c, "Invalid hex digit");
break;
}
res <<= 4;
res |= h;
str++;
}
*this = res;
}
template<int Na>
inline void bit_fill(const int (&ivec)[Na], bool bigendian=true) {
// bit_fill from integer vector
// if W > N*32, missing most significant bits are zeroed
// if W < N*32, additional bits in ivec are ignored (no overflow checking)
// Example:
// ac_int<80,false> x; int vec[] = { 0xffffa987, 0x6543210f, 0xedcba987 };
// x.bit_fill(vec); // vec[0] fill bits 79-64
enum { N0 = (W+31)/32, M = AC_MIN(N0,Na) };
ac_int<M*32,false> res = 0;
for(int i=0; i < M; i++)
res.set_slc(i*32, ac_int<32>(ivec[bigendian ? M-1-i : i]));
*this = res;
}
};
namespace ac {
template<typename T, typename T2>
struct rt_2T {
typedef typename ac_private::map<T>::t map_T;
typedef typename ac_private::map<T2>::t map_T2;
typedef typename map_T::template rt_T< map_T2 >::mult mult;
typedef typename map_T::template rt_T< map_T2 >::plus plus;
typedef typename map_T::template rt_T< map_T2 >::minus minus;
typedef typename map_T::template rt_T< map_T2 >::minus2 minus2;
typedef typename map_T::template rt_T< map_T2 >::logic logic;
typedef typename map_T::template rt_T< map_T2 >::div div;
typedef typename map_T::template rt_T< map_T2 >::div2 div2;
};
}
namespace ac {
template<typename T>
struct ac_int_represent {
enum { t_w = ac_private::c_type_params<T>::W, t_s = ac_private::c_type_params<T>::S };
typedef ac_int<t_w,t_s> type;
};
template<> struct ac_int_represent<float> {};
template<> struct ac_int_represent<double> {};
template<int W, bool S>
struct ac_int_represent< ac_int<W,S> > {
typedef ac_int<W,S> type;
};
}
namespace ac_private {
template<int W2, bool S2>
struct rt_ac_int_T< ac_int<W2,S2> > {
typedef ac_int<W2,S2> i2_t;
template<int W, bool S>
struct op1 {
typedef ac_int<W,S> i_t;
typedef typename i_t::template rt<W2,S2>::mult mult;
typedef typename i_t::template rt<W2,S2>::plus plus;
typedef typename i_t::template rt<W2,S2>::minus minus;
typedef typename i2_t::template rt<W,S>::minus minus2;
typedef typename i_t::template rt<W2,S2>::logic logic;
typedef typename i_t::template rt<W2,S2>::div div;
typedef typename i2_t::template rt<W,S>::div div2;
typedef typename i_t::template rt<W2,S2>::mod mod;
typedef typename i2_t::template rt<W,S>::mod mod2;
};
};
template<typename T>
struct rt_ac_int_T< c_type<T> > {
typedef typename ac::ac_int_represent<T>::type i2_t;
enum { W2 = i2_t::width, S2 = i2_t::sign };
template<int W, bool S>
struct op1 {
typedef ac_int<W,S> i_t;
typedef typename i_t::template rt<W2,S2>::mult mult;
typedef typename i_t::template rt<W2,S2>::plus plus;
typedef typename i_t::template rt<W2,S2>::minus minus;
typedef typename i2_t::template rt<W,S>::minus minus2;
typedef typename i_t::template rt<W2,S2>::logic logic;
typedef typename i_t::template rt<W2,S2>::div div;
typedef typename i2_t::template rt<W,S>::div div2;
typedef typename i_t::template rt<W2,S2>::mod mod;
typedef typename i2_t::template rt<W,S>::mod mod2;
};
};
}
// Specializations for constructors on integers that bypass bit adjusting
// and are therefore more efficient
template<> inline ac_int<1,true>::ac_int( bool b ) { v[0] = b ? -1 : 0; }
template<> inline ac_int<1,false>::ac_int( bool b ) { v[0] = b; }
template<> inline ac_int<1,false>::ac_int( signed char b ) { v[0] = b&1; }
template<> inline ac_int<1,false>::ac_int( unsigned char b ) { v[0] = b&1; }
template<> inline ac_int<1,false>::ac_int( signed short b ) { v[0] = b&1; }
template<> inline ac_int<1,false>::ac_int( unsigned short b ) { v[0] = b&1; }
template<> inline ac_int<1,false>::ac_int( signed int b ) { v[0] = b&1; }
template<> inline ac_int<1,false>::ac_int( unsigned int b ) { v[0] = b&1; }
template<> inline ac_int<1,false>::ac_int( signed long b ) { v[0] = b&1; }
template<> inline ac_int<1,false>::ac_int( unsigned long b ) { v[0] = b&1; }
template<> inline ac_int<1,false>::ac_int( Ulong b ) { v[0] = (int) b&1; }
template<> inline ac_int<1,false>::ac_int( Slong b ) { v[0] = (int) b&1; }
template<> inline ac_int<8,true>::ac_int( bool b ) { v[0] = b; }
template<> inline ac_int<8,false>::ac_int( bool b ) { v[0] = b; }
template<> inline ac_int<8,true>::ac_int( signed char b ) { v[0] = b; }
template<> inline ac_int<8,false>::ac_int( unsigned char b ) { v[0] = b; }
template<> inline ac_int<8,true>::ac_int( unsigned char b ) { v[0] = (signed char) b; }
template<> inline ac_int<8,false>::ac_int( signed char b ) { v[0] = (unsigned char) b; }
template<> inline ac_int<16,true>::ac_int( bool b ) { v[0] = b; }
template<> inline ac_int<16,false>::ac_int( bool b ) { v[0] = b; }
template<> inline ac_int<16,true>::ac_int( signed char b ) { v[0] = b; }
template<> inline ac_int<16,false>::ac_int( unsigned char b ) { v[0] = b; }
template<> inline ac_int<16,true>::ac_int( unsigned char b ) { v[0] = b; }
template<> inline ac_int<16,false>::ac_int( signed char b ) { v[0] = (unsigned short) b; }
template<> inline ac_int<16,true>::ac_int( signed short b ) { v[0] = b; }
template<> inline ac_int<16,false>::ac_int( unsigned short b ) { v[0] = b; }
template<> inline ac_int<16,true>::ac_int( unsigned short b ) { v[0] = (signed short) b; }
template<> inline ac_int<16,false>::ac_int( signed short b ) { v[0] = (unsigned short) b; }
template<> inline ac_int<32,true>::ac_int( signed int b ) { v[0] = b; }
template<> inline ac_int<32,true>::ac_int( unsigned int b ) { v[0] = b; }
template<> inline ac_int<32,false>::ac_int( signed int b ) { v[0] = b; v[1] = 0;}
template<> inline ac_int<32,false>::ac_int( unsigned int b ) { v[0] = b; v[1] = 0;}
template<> inline ac_int<32,true>::ac_int( Slong b ) { v[0] = (int) b; }
template<> inline ac_int<32,true>::ac_int( Ulong b ) { v[0] = (int) b; }
template<> inline ac_int<32,false>::ac_int( Slong b ) { v[0] = (int) b; v[1] = 0;}
template<> inline ac_int<32,false>::ac_int( Ulong b ) { v[0] = (int) b; v[1] = 0;}
template<> inline ac_int<64,true>::ac_int( Slong b ) { v[0] = (int) b; v[1] = (int) (b >> 32); }
template<> inline ac_int<64,true>::ac_int( Ulong b ) { v[0] = (int) b; v[1] = (int) (b >> 32);}
template<> inline ac_int<64,false>::ac_int( Slong b ) { v[0] = (int) b; v[1] = (int) ((Ulong) b >> 32); v[2] = 0; }
template<> inline ac_int<64,false>::ac_int( Ulong b ) { v[0] = (int) b; v[1] = (int) (b >> 32); v[2] = 0; }
// Stream --------------------------------------------------------------------
template<int W, bool S>
inline std::ostream& operator << (std::ostream &os, const ac_int<W,S> &x) {
#ifndef __SYNTHESIS__
if ((os.flags() & std::ios::hex) != 0) {
os << x.to_string(AC_HEX);
} else if ((os.flags() & std::ios::oct) != 0) {
os << x.to_string(AC_OCT);
} else {
os << x.to_string(AC_DEC);
}
#endif
return os;
}
// Macros for Binary Operators with Integers --------------------------------------------
#define BIN_OP_WITH_INT(BIN_OP, C_TYPE, WI, SI, RTYPE) \
template<int W, bool S> \
inline typename ac_int<WI,SI>::template rt<W,S>::RTYPE operator BIN_OP ( C_TYPE i_op, const ac_int<W,S> &op) { \
return ac_int<WI,SI>(i_op).operator BIN_OP (op); \
} \
template<int W, bool S> \
inline typename ac_int<W,S>::template rt<WI,SI>::RTYPE operator BIN_OP ( const ac_int<W,S> &op, C_TYPE i_op) { \
return op.operator BIN_OP (ac_int<WI,SI>(i_op)); \
}
#define REL_OP_WITH_INT(REL_OP, C_TYPE, W2, S2) \
template<int W, bool S> \
inline bool operator REL_OP ( const ac_int<W,S> &op, C_TYPE op2) { \
return op.operator REL_OP (ac_int<W2,S2>(op2)); \
} \
template<int W, bool S> \
inline bool operator REL_OP ( C_TYPE op2, const ac_int<W,S> &op) { \
return ac_int<W2,S2>(op2).operator REL_OP (op); \
}
#define ASSIGN_OP_WITH_INT(ASSIGN_OP, C_TYPE, W2, S2) \
template<int W, bool S> \
inline ac_int<W,S> &operator ASSIGN_OP ( ac_int<W,S> &op, C_TYPE op2) { \
return op.operator ASSIGN_OP (ac_int<W2,S2>(op2)); \
}
#define OPS_WITH_INT(C_TYPE, WI, SI) \
BIN_OP_WITH_INT(*, C_TYPE, WI, SI, mult) \
BIN_OP_WITH_INT(+, C_TYPE, WI, SI, plus) \
BIN_OP_WITH_INT(-, C_TYPE, WI, SI, minus) \
BIN_OP_WITH_INT(/, C_TYPE, WI, SI, div) \
BIN_OP_WITH_INT(%, C_TYPE, WI, SI, mod) \
BIN_OP_WITH_INT(>>, C_TYPE, WI, SI, arg1) \
BIN_OP_WITH_INT(<<, C_TYPE, WI, SI, arg1) \
BIN_OP_WITH_INT(&, C_TYPE, WI, SI, logic) \
BIN_OP_WITH_INT(|, C_TYPE, WI, SI, logic) \
BIN_OP_WITH_INT(^, C_TYPE, WI, SI, logic) \
\
REL_OP_WITH_INT(==, C_TYPE, WI, SI) \
REL_OP_WITH_INT(!=, C_TYPE, WI, SI) \
REL_OP_WITH_INT(>, C_TYPE, WI, SI) \
REL_OP_WITH_INT(>=, C_TYPE, WI, SI) \
REL_OP_WITH_INT(<, C_TYPE, WI, SI) \
REL_OP_WITH_INT(<=, C_TYPE, WI, SI) \
\
ASSIGN_OP_WITH_INT(+=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(-=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(*=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(/=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(%=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(>>=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(<<=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(&=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(|=, C_TYPE, WI, SI) \
ASSIGN_OP_WITH_INT(^=, C_TYPE, WI, SI)
// ------------------------------------- End of Macros for Binary Operators with Integers
namespace ac {
namespace ops_with_other_types {
// Mixed Operators with Integers -----------------------------------------------
OPS_WITH_INT(bool, 1, false)
OPS_WITH_INT(char, 8, true)
OPS_WITH_INT(signed char, 8, true)
OPS_WITH_INT(unsigned char, 8, false)
OPS_WITH_INT(short, 16, true)
OPS_WITH_INT(unsigned short, 16, false)
OPS_WITH_INT(int, 32, true)
OPS_WITH_INT(unsigned int, 32, false)
OPS_WITH_INT(long, ac_private::long_w, true)
OPS_WITH_INT(unsigned long, ac_private::long_w, false)
OPS_WITH_INT(Slong, 64, true)
OPS_WITH_INT(Ulong, 64, false)
// ----------------------------------------- End of Mixed Operators with Integers
} // ops_with_other_types namespace
// Functions to fill bits
template<typename T>
inline T bit_fill_hex(const char *str) {
T res;
res.bit_fill_hex(str);
return res;
}
// returns bit_fill for type
// example:
// ac_int<80,false> x = ac::bit_fill< ac_int<80,false> > ((int [3]) {0xffffa987, 0x6543210f, 0xedcba987 });
template<typename T, int N>
inline T bit_fill(const int (&ivec)[N], bool bigendian=true) {
T res;
res.bit_fill(ivec, bigendian);
return res;
}
} // ac namespace
// Mixed Operators with Pointers -----------------------------------------------
// Addition of ac_int and pointer
template<typename T, int W, bool S>
T *operator +(T *ptr, const ac_int<W,S> &op2) {
return ptr + op2.to_int64();
}
template<typename T, int W, bool S>
T *operator +(const ac_int<W,S> &op2, T *ptr) {
return ptr + op2.to_int64();
}
// Subtraction of ac_int from pointer
template<typename T, int W, bool S>
T *operator -(T *ptr, const ac_int<W,S> &op2) {
return ptr - op2.to_int64();
}
// ----------------------------------------- End of Mixed Operators with Pointers
using namespace ac::ops_with_other_types;
namespace ac_intN {
///////////////////////////////////////////////////////////////////////////////
// Predefined for ease of use
///////////////////////////////////////////////////////////////////////////////
typedef ac_int<1, true> int1;
typedef ac_int<1, false> uint1;
typedef ac_int<2, true> int2;
typedef ac_int<2, false> uint2;
typedef ac_int<3, true> int3;
typedef ac_int<3, false> uint3;
typedef ac_int<4, true> int4;
typedef ac_int<4, false> uint4;
typedef ac_int<5, true> int5;
typedef ac_int<5, false> uint5;
typedef ac_int<6, true> int6;
typedef ac_int<6, false> uint6;
typedef ac_int<7, true> int7;
typedef ac_int<7, false> uint7;
typedef ac_int<8, true> int8;
typedef ac_int<8, false> uint8;
typedef ac_int<9, true> int9;
typedef ac_int<9, false> uint9;
typedef ac_int<10, true> int10;
typedef ac_int<10, false> uint10;
typedef ac_int<11, true> int11;
typedef ac_int<11, false> uint11;
typedef ac_int<12, true> int12;
typedef ac_int<12, false> uint12;
typedef ac_int<13, true> int13;
typedef ac_int<13, false> uint13;
typedef ac_int<14, true> int14;
typedef ac_int<14, false> uint14;
typedef ac_int<15, true> int15;
typedef ac_int<15, false> uint15;
typedef ac_int<16, true> int16;
typedef ac_int<16, false> uint16;
typedef ac_int<17, true> int17;
typedef ac_int<17, false> uint17;
typedef ac_int<18, true> int18;
typedef ac_int<18, false> uint18;
typedef ac_int<19, true> int19;
typedef ac_int<19, false> uint19;
typedef ac_int<20, true> int20;
typedef ac_int<20, false> uint20;
typedef ac_int<21, true> int21;
typedef ac_int<21, false> uint21;
typedef ac_int<22, true> int22;
typedef ac_int<22, false> uint22;
typedef ac_int<23, true> int23;
typedef ac_int<23, false> uint23;
typedef ac_int<24, true> int24;
typedef ac_int<24, false> uint24;
typedef ac_int<25, true> int25;
typedef ac_int<25, false> uint25;
typedef ac_int<26, true> int26;
typedef ac_int<26, false> uint26;
typedef ac_int<27, true> int27;
typedef ac_int<27, false> uint27;
typedef ac_int<28, true> int28;
typedef ac_int<28, false> uint28;
typedef ac_int<29, true> int29;
typedef ac_int<29, false> uint29;
typedef ac_int<30, true> int30;
typedef ac_int<30, false> uint30;
typedef ac_int<31, true> int31;
typedef ac_int<31, false> uint31;
typedef ac_int<32, true> int32;
typedef ac_int<32, false> uint32;
typedef ac_int<33, true> int33;
typedef ac_int<33, false> uint33;
typedef ac_int<34, true> int34;
typedef ac_int<34, false> uint34;
typedef ac_int<35, true> int35;
typedef ac_int<35, false> uint35;
typedef ac_int<36, true> int36;
typedef ac_int<36, false> uint36;
typedef ac_int<37, true> int37;
typedef ac_int<37, false> uint37;
typedef ac_int<38, true> int38;
typedef ac_int<38, false> uint38;
typedef ac_int<39, true> int39;
typedef ac_int<39, false> uint39;
typedef ac_int<40, true> int40;
typedef ac_int<40, false> uint40;
typedef ac_int<41, true> int41;
typedef ac_int<41, false> uint41;
typedef ac_int<42, true> int42;
typedef ac_int<42, false> uint42;
typedef ac_int<43, true> int43;
typedef ac_int<43, false> uint43;
typedef ac_int<44, true> int44;
typedef ac_int<44, false> uint44;
typedef ac_int<45, true> int45;
typedef ac_int<45, false> uint45;
typedef ac_int<46, true> int46;
typedef ac_int<46, false> uint46;
typedef ac_int<47, true> int47;
typedef ac_int<47, false> uint47;
typedef ac_int<48, true> int48;
typedef ac_int<48, false> uint48;
typedef ac_int<49, true> int49;
typedef ac_int<49, false> uint49;
typedef ac_int<50, true> int50;
typedef ac_int<50, false> uint50;
typedef ac_int<51, true> int51;
typedef ac_int<51, false> uint51;
typedef ac_int<52, true> int52;
typedef ac_int<52, false> uint52;
typedef ac_int<53, true> int53;
typedef ac_int<53, false> uint53;
typedef ac_int<54, true> int54;
typedef ac_int<54, false> uint54;
typedef ac_int<55, true> int55;
typedef ac_int<55, false> uint55;
typedef ac_int<56, true> int56;
typedef ac_int<56, false> uint56;
typedef ac_int<57, true> int57;
typedef ac_int<57, false> uint57;
typedef ac_int<58, true> int58;
typedef ac_int<58, false> uint58;
typedef ac_int<59, true> int59;
typedef ac_int<59, false> uint59;
typedef ac_int<60, true> int60;
typedef ac_int<60, false> uint60;
typedef ac_int<61, true> int61;
typedef ac_int<61, false> uint61;
typedef ac_int<62, true> int62;
typedef ac_int<62, false> uint62;
typedef ac_int<63, true> int63;
typedef ac_int<63, false> uint63;
} // namespace ac_intN
#ifndef AC_NOT_USING_INTN
using namespace ac_intN;
#endif
///////////////////////////////////////////////////////////////////////////////
#if (defined(_MSC_VER) && !defined(__EDG__))
#pragma warning( disable: 4700 )
#endif
#if (defined(__GNUC__) && ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 || __GNUC__ > 4 ) && !defined(__EDG__))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
#endif
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wuninitialized"
#endif
// Global templatized functions for easy initialization to special values
template<ac_special_val V, int W, bool S>
inline ac_int<W,S> value(ac_int<W,S>) {
ac_int<W,S> r;
return r.template set_val<V>();
}
// forward declaration, otherwise GCC errors when calling init_array
template<ac_special_val V, int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
inline ac_fixed<W,I,S,Q,O> value(ac_fixed<W,I,S,Q,O>);
#define SPECIAL_VAL_FOR_INTS_DC(C_TYPE, WI, SI) \
template<> inline C_TYPE value<AC_VAL_DC>(C_TYPE) { C_TYPE x; return x; }
// -- C int types -----------------------------------------------------------------
#define SPECIAL_VAL_FOR_INTS(C_TYPE, WI, SI) \
template<ac_special_val val> inline C_TYPE value(C_TYPE); \
template<> inline C_TYPE value<AC_VAL_0>(C_TYPE) { return (C_TYPE)0; } \
SPECIAL_VAL_FOR_INTS_DC(C_TYPE, WI, SI) \
template<> inline C_TYPE value<AC_VAL_QUANTUM>(C_TYPE) { return (C_TYPE)1; } \
template<> inline C_TYPE value<AC_VAL_MAX>(C_TYPE) { return (C_TYPE)(SI ? ~(((C_TYPE) 1) << (WI-1)) : (C_TYPE) -1); } \
template<> inline C_TYPE value<AC_VAL_MIN>(C_TYPE) { return (C_TYPE)(SI ? ((C_TYPE) 1) << (WI-1) : (C_TYPE) 0); }
SPECIAL_VAL_FOR_INTS(bool, 1, false)
SPECIAL_VAL_FOR_INTS(char, 8, true)
SPECIAL_VAL_FOR_INTS(signed char, 8, true)
SPECIAL_VAL_FOR_INTS(unsigned char, 8, false)
SPECIAL_VAL_FOR_INTS(short, 16, true)
SPECIAL_VAL_FOR_INTS(unsigned short, 16, false)
SPECIAL_VAL_FOR_INTS(int, 32, true)
SPECIAL_VAL_FOR_INTS(unsigned int, 32, false)
SPECIAL_VAL_FOR_INTS(long, ac_private::long_w, true)
SPECIAL_VAL_FOR_INTS(unsigned long, ac_private::long_w, false)
SPECIAL_VAL_FOR_INTS(Slong, 64, true)
SPECIAL_VAL_FOR_INTS(Ulong, 64, false)
#define INIT_ARRAY_SPECIAL_VAL_FOR_INTS(C_TYPE) \
template<ac_special_val V> \
inline bool init_array(C_TYPE *a, int n) { \
C_TYPE t = value<V>(*a); \
for(int i=0; i < n; i++) \
a[i] = t; \
return true; \
}
namespace ac {
// PUBLIC FUNCTIONS
// function to initialize (or uninitialize) arrays
template<ac_special_val V, int W, bool S>
inline bool init_array(ac_int<W,S> *a, int n) {
ac_int<W,S> t = value<V>(*a);
for(int i=0; i < n; i++)
a[i] = t;
return true;
}
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(bool)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(char)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(signed char)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(unsigned char)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(signed short)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(unsigned short)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(signed int)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(unsigned int)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(signed long)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(unsigned long)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(signed long long)
INIT_ARRAY_SPECIAL_VAL_FOR_INTS(unsigned long long)
}
#if (defined(_MSC_VER) && !defined(__EDG__))
#pragma warning( pop )
#endif
#if (defined(__GNUC__) && ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 || __GNUC__ > 4 ) && !defined(__EDG__))
#pragma GCC diagnostic pop
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#ifdef __AC_NAMESPACE
}
#endif
#endif // __AC_INT_H
|
manageryzy/ac_types_plus
|
include/ac_sc.h
|
<reponame>manageryzy/ac_types_plus<filename>include/ac_sc.h
/**************************************************************************
* *
* Algorithmic C (tm) Datatypes *
* *
* Software Version: 3.7 *
* *
* Release Date : Tue May 30 14:25:58 PDT 2017 *
* Release Type : Production Release *
* Release Build : 3.7.2 *
* *
* Copyright 2004-2016, Mentor Graphics Corporation, *
* *
* All Rights Reserved. *
*
**************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
**************************************************************************
* *
* The most recent version of this package is available at github. *
* *
*************************************************************************/
#ifndef __AC_SC_H
#define __AC_SC_H
#ifndef __cplusplus
#error C++ is required to include this header file
#endif
#if !defined(IEEE_1666_SYSTEMC) && !defined(SYSTEMC_VERSION) && !defined(SC_API_VERSION_STRING)
#error SystemC header file needs to be included before the ac_sc is included
#endif
#include <ac_complex.h>
#ifdef __AC_NAMESPACE
namespace __AC_NAMESPACE {
#endif
// Explicit conversion functions from ac to sc and viceversa
template <int W>
ac_int<W, true> to_ac(const sc_dt::sc_bigint<W> &val){
enum {N = (W+31)/32 };
sc_dt::sc_bigint<N*32> v = val;
ac_int<N*32, true> r = 0;
#ifdef __SYNTHESIS__
#pragma UNROLL y
#endif
for(int i = 0; i < N; i++) {
r.set_slc(i*32, ac_int<32,true>(v.to_int()));
v >>= 32;
}
return ac_int<W,true>(r);
}
template <int W>
ac_int<W, false> to_ac(const sc_dt::sc_biguint<W> &val){
enum {N = (W+31)/32 };
sc_dt::sc_biguint<N*32> v = val;
ac_int<N*32, true> r = 0;
#ifdef __SYNTHESIS__
#pragma UNROLL y
#endif
for(int i = 0; i < N; i++) {
r.set_slc(i*32, ac_int<32,true>(v.to_int()));
v >>= 32;
}
return ac_int<W,false>(r);
}
template <int W>
sc_dt::sc_bigint<W> to_sc(const ac_int<W,true> &val) {
enum {N = (W+31)/32 };
ac_int<N*32, true> v = val;
sc_dt::sc_bigint<N*32> r;
#ifdef __SYNTHESIS__
#pragma UNROLL y
#endif
for(int i = N-1; i >= 0; i--) {
r <<= 32;
r.range(31, 0) = (v.template slc<32>(i*32)).to_int();
}
return sc_dt::sc_bigint<W>(r);
}
template <int W>
sc_dt::sc_biguint<W> to_sc(const ac_int<W,false> &val) {
enum {N = (W+31)/32 };
ac_int<N*32, true> v = val;
sc_dt::sc_biguint<N*32> r;
#ifdef __SYNTHESIS__
#pragma UNROLL y
#endif
for(int i = N-1; i >= 0; i--) {
r <<= 32;
r.range(31, 0) = (v.template slc<32>(i*32)).to_int();
}
return sc_dt::sc_biguint<W>(r);
}
#ifdef SC_INCLUDE_FX
template <int W, int I, sc_dt::sc_q_mode Q, sc_dt::sc_o_mode O, int nbits>
ac_fixed<W,I, true> to_ac(const sc_dt::sc_fixed<W,I,Q,O,nbits> &val){
ac_fixed<W,I,true> r = 0;
sc_dt::sc_fixed<W,W> fv;
fv.range(W-1,0) = val.range(W-1,0);
sc_dt::sc_bigint<W> v(fv);
r.set_slc(0, to_ac(v));
return r;
}
template <int W, int I, sc_dt::sc_q_mode Q, sc_dt::sc_o_mode O, int nbits>
ac_fixed<W,I, false> to_ac(const sc_dt::sc_ufixed<W,I,Q,O,nbits> &val){
ac_fixed<W,I,false> r = 0;
sc_dt::sc_ufixed<W,W> fv;
fv.range(W-1,0) = val.range(W-1,0);
sc_dt::sc_biguint<W> v(fv);
r.set_slc(0, to_ac(v));
return r;
}
template <int W, int I, ac_q_mode Q, ac_o_mode O>
sc_dt::sc_fixed<W,I> to_sc(const ac_fixed<W,I,true,Q,O> &val) {
ac_int<W,true> v = val.template slc<W>(0);
sc_dt::sc_bigint<W> i = to_sc(v);
sc_dt::sc_fixed<W,W> f(i);
sc_dt::sc_fixed<W,I> r;
r.range(W-1,0) = f.range(W-1,0);
return r;
}
template <int W, int I, ac_q_mode Q, ac_o_mode O>
sc_dt::sc_ufixed<W,I> to_sc(const ac_fixed<W,I,false,Q,O> &val) {
ac_int<W,false> v = val.template slc<W>(0);
sc_dt::sc_biguint<W> i = to_sc(v);
sc_dt::sc_ufixed<W,W> f(i);
sc_dt::sc_ufixed<W,I> r;
r.range(W-1,0) = f.range(W-1,0);
return r;
}
#endif
// Utility global functions for initialization
template<ac_special_val V, int W>
inline sc_dt::sc_int<W> value(sc_dt::sc_int<W>) {
sc_dt::sc_int<W> r;
if(V == AC_VAL_DC) {
int t;
r = t;
} else if(V == AC_VAL_0 || V == AC_VAL_MIN || V == AC_VAL_QUANTUM) {
r = 0;
if(V == AC_VAL_MIN)
r[W-1] = 1;
else if(V == AC_VAL_QUANTUM)
r[0] = 1;
} else if(AC_VAL_MAX) {
r = -1;
r[W-1] = 0;
}
return r;
}
template<ac_special_val V, int W>
inline sc_dt::sc_uint<W> value(sc_dt::sc_uint<W>) {
sc_dt::sc_uint<W> r;
if(V == AC_VAL_DC) {
int t;
r = t;
} else if(V == AC_VAL_0 || V == AC_VAL_MIN || V == AC_VAL_QUANTUM) {
r = 0;
if(V == AC_VAL_QUANTUM)
r[0] = 1;
} else if(AC_VAL_MAX)
r = -1;
return r;
}
template<ac_special_val V, int W>
inline sc_dt::sc_bigint<W> value(sc_dt::sc_bigint<W>) {
sc_dt::sc_bigint<W> r;
if(V == AC_VAL_DC) {
int t;
r = t;
} else if(V == AC_VAL_0 || V == AC_VAL_MIN || V == AC_VAL_QUANTUM) {
r = 0;
if(V == AC_VAL_MIN)
r[W-1] = 1;
else if(V == AC_VAL_QUANTUM)
r[0] = 1;
} else if(AC_VAL_MAX) {
r = -1;
r[W-1] = 0;
}
return r;
}
template<ac_special_val V, int W>
inline sc_dt::sc_biguint<W> value(sc_dt::sc_biguint<W>) {
sc_dt::sc_biguint<W> r;
if(V == AC_VAL_DC) {
int t;
r = t;
} else if(V == AC_VAL_0 || V == AC_VAL_MIN || V == AC_VAL_QUANTUM) {
r = 0;
if(V == AC_VAL_QUANTUM)
r[0] = 1;
} else if(AC_VAL_MAX)
r = -1;
return r;
}
#ifdef SC_INCLUDE_FX
template<ac_special_val V, int W, int I, sc_dt::sc_q_mode Q, sc_dt::sc_o_mode O, int nbits>
inline sc_dt::sc_fixed<W,I,Q,O,nbits> value(sc_dt::sc_fixed<W,I,Q,O,nbits>) {
sc_dt::sc_fixed<W,I> r;
if(V == AC_VAL_DC) {
int t;
r = t;
} else if(V == AC_VAL_0 || V == AC_VAL_MIN || V == AC_VAL_QUANTUM) {
r = 0;
if(V == AC_VAL_MIN)
r[W-1] = 1;
else if(V == AC_VAL_QUANTUM)
r[0] = 1;
} else if(AC_VAL_MAX) {
r = ~ (sc_dt::sc_fixed<W,I>) 0;
r[W-1] = 0;
}
return r;
}
template<ac_special_val V, int W, int I, sc_dt::sc_q_mode Q, sc_dt::sc_o_mode O, int nbits>
inline sc_dt::sc_ufixed<W,I,Q,O,nbits> value(sc_dt::sc_ufixed<W,I,Q,O,nbits>) {
sc_dt::sc_ufixed<W,I> r;
if(V == AC_VAL_DC) {
int t;
r = t;
} else if(V == AC_VAL_0 || V == AC_VAL_MIN || V == AC_VAL_QUANTUM) {
r = 0;
if(V == AC_VAL_QUANTUM)
r[0] = 1;
} else if(AC_VAL_MAX)
r = ~ (sc_dt::sc_ufixed<W,I>) 0;
return r;
}
#endif
namespace ac {
// PUBLIC FUNCTIONS
// function to initialize (or uninitialize) arrays
template<ac_special_val V, int W>
inline bool init_array(sc_dt::sc_int<W> *a, int n) {
sc_dt::sc_int<W> t = value<V>(*a);
for(int i=0; i < n; i++)
a[i] = t;
return true;
}
template<ac_special_val V, int W>
inline bool init_array(sc_dt::sc_uint<W> *a, int n) {
sc_dt::sc_uint<W> t = value<V>(*a);
for(int i=0; i < n; i++)
a[i] = t;
return true;
}
template<ac_special_val V, int W>
inline bool init_array(sc_dt::sc_bigint<W> *a, int n) {
sc_dt::sc_bigint<W> t = value<V>(*a);
for(int i=0; i < n; i++)
a[i] = t;
return true;
}
template<ac_special_val V, int W>
inline bool init_array(sc_dt::sc_biguint<W> *a, int n) {
sc_dt::sc_biguint<W> t = value<V>(*a);
for(int i=0; i < n; i++)
a[i] = t;
return true;
}
#ifdef SC_INCLUDE_FX
template<ac_special_val V, int W, int I, sc_dt::sc_q_mode Q, sc_dt::sc_o_mode O, int nbits>
inline bool init_array(sc_dt::sc_fixed<W,I,Q,O,nbits> *a, int n) {
sc_dt::sc_fixed<W,I> t = value<V>(*a);
for(int i=0; i < n; i++)
a[i] = t;
return true;
}
template<ac_special_val V, int W, int I, sc_dt::sc_q_mode Q, sc_dt::sc_o_mode O, int nbits>
inline bool init_array(sc_dt::sc_ufixed<W,I,Q,O,nbits> *a, int n) {
sc_dt::sc_ufixed<W,I> t = value<V>(*a);
for(int i=0; i < n; i++)
a[i] = t;
return true;
}
#endif
}
#ifdef __AC_NAMESPACE
}
#endif
// TRACE FUNCTIONS
// SystemC Versions - 2.2.0 20070314
// 2.3.0 20120701
// 2.3.1 20140417
#if (SYSTEMC_VERSION <= 20140417) && !defined(NCSC)
#if (SYSTEMC_VERSION > 20120701)
#include <sysc/tracing/sc_vcd_trace.h>
#endif
//==============================================================================
// The following block of code is copied from the file sc_vcd_trace.cpp in the
// SystemC 2.2.0 distribution. This code should have been placed in the file
// sc_vcd_trace.h to allow proper C++ derivation.
namespace sc_core {
class vcd_trace
{
public:
vcd_trace(const std::string& name_, const std::string& vcd_name_);
// Needs to be pure virtual as has to be defined by the particular
// type being traced
virtual void write(FILE* f) = 0;
virtual void set_width();
static const char* strip_leading_bits(const char* originalbuf);
// Comparison function needs to be pure virtual too
virtual bool changed() = 0;
// Make this virtual as some derived classes may overwrite
virtual void print_variable_declaration_line(FILE* f);
void compose_data_line(char* rawdata, char* compdata);
#if (SYSTEMC_VERSION > 20120701)
std::string compose_line(const std::string& data);
#else
std::string compose_line(const std::string data);
#endif
virtual ~vcd_trace();
const std::string name;
const std::string vcd_name;
const char* vcd_var_typ_name;
int bit_width;
};
}
static
void
remove_vcd_name_problems(std::string& name)
{
using namespace sc_core;
char message[4000];
static bool warned = false;
bool braces_removed = false;
for (unsigned int i = 0; i< name.length(); i++) {
if (name[i] == '[') {
name[i] = '(';
braces_removed = true;
}
else if (name[i] == ']') {
name[i] = ')';
braces_removed = true;
}
}
if(braces_removed && !warned){
std::sprintf(message,
"Traced objects found with name containing [], which may be\n"
"interpreted by the waveform viewer in unexpected ways.\n"
"So the [] is automatically replaced by ().");
#if (SYSTEMC_VERSION <= 20120701)
put_error_message(message, true);
#endif
warned = true;
}
}
//==============================================================================
#endif
#ifdef __AC_NAMESPACE
namespace __AC_NAMESPACE {
#endif
namespace ac_tracing {
//==============================================================================
// TRACING SUPPORT FOR AC_INT
template <int W, bool S>
class vcd_ac_int_trace : public sc_core::vcd_trace
{
public:
vcd_ac_int_trace(const ac_int<W,S> &object_, const std::string& name_, const std::string& vcd_name_) :
vcd_trace(name_, vcd_name_), object(object_)
{
vcd_var_typ_name = "wire"; // SystemC does not expose vcd_types[] in sc_vcd_trace.h
bit_width = W; // bit_width defined in base class 'vcd_trace'
}
virtual void print_variable_declaration_line(FILE* f) {
char buf[2000];
std::string namecopy = name;
#if !defined(NCSC)
remove_vcd_name_problems(namecopy);
#endif
std::sprintf(buf, "$var %s % 3d %s %s [%d:0] $end\n", vcd_var_typ_name,bit_width,vcd_name.c_str(),namecopy.c_str(),bit_width-1);
std::fputs(buf, f);
}
virtual void write(FILE* f) {
// The function to_string(AC_BIN) returns a string with the zero-radix prefix (i.e. "0b").
// Strip that prefix off because compose_line will add its own.
std::fprintf(f, "%s", compose_line(((ac_int<W,false>)object).to_string(AC_BIN,true).substr(3)).c_str());
old_value = object;
}
virtual void set_width() { bit_width = W; }
// Comparison function needs to be pure virtual too
virtual bool changed() { return !(object == old_value); }
virtual ~vcd_ac_int_trace() {}
protected:
const ac_int<W,S> &object;
ac_int<W,S> old_value;
};
template <int W, bool S>
inline void sc_trace(sc_core::sc_trace_file *tf, const ac_int<W,S> &a, const std::string &name)
{
using namespace sc_core;
if (tf) {
//--- SystemC 2.2.0 deficiency. The 'initialized' class member of sc_trace_file is
// declared as 'protected' and does not have a public access 'get_initialized()' method.
// Therefore, we cannot check for initialized so the following code is commented out.
//if( tf->initialized ) {
// put_error_message(
// "No traces can be added once simulation has started.\n"
// "To add traces, create a new vcd trace file.", false );
//}
vcd_trace *t = (vcd_trace*) new vcd_ac_int_trace<W,S>(a,name,((vcd_trace_file*)tf)->obtain_name());
((vcd_trace_file*)tf)->traces.push_back(t);
}
}
//==============================================================================
#if !defined(__AC_FIXED_MTI_H)
// The ac_fixed.h shipped with ModelSim/QuestaSim has a stub for sc_trace() for ac_fixed so
// this code is not used. The stub should be removed in a future release of the simulator.
#if defined(__AC_FIXED_H) && !defined(SC_TRACE_AC_FIXED)
#define SC_TRACE_AC_FIXED
//==============================================================================
// TRACING SUPPORT FOR AC_FIXED
template<int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
class vcd_ac_fixed_trace : public sc_core::vcd_trace
{
public:
vcd_ac_fixed_trace(const ac_fixed<W,I,S,Q,O> &object_, const std::string& name_, const std::string& vcd_name_) :
vcd_trace(name_, vcd_name_), object(object_)
{
vcd_var_typ_name = "wire"; // SystemC does not expose vcd_types[] in sc_vcd_trace.h
bit_width = W; // bit_width defined in base class 'vcd_trace'
}
virtual void print_variable_declaration_line(FILE* f) {
char buf[2000];
std::string namecopy = name;
#if !defined(NCSC)
remove_vcd_name_problems(namecopy);
#endif
std::sprintf(buf, "$var %s % 3d %s %s [%d:0] $end\n", vcd_var_typ_name,bit_width,vcd_name.c_str(),namecopy.c_str(),bit_width-1);
std::fputs(buf, f);
}
virtual void write(FILE* f) {
// The function to_string(AC_BIN) returns a string with the zero-radix prefix (i.e. "0b").
// Strip that prefix off because compose_line will add its own.
std::fprintf(f, "%s", compose_line(((ac_fixed<W,I,false>)object).to_string(AC_BIN,true).substr(3)).c_str());
old_value = object;
}
virtual void set_width() { bit_width = W; }
// Comparison function needs to be pure virtual too
virtual bool changed() { return !(object == old_value); }
virtual ~vcd_ac_fixed_trace() {}
protected:
const ac_fixed<W,I,S,Q,O> &object;
ac_fixed<W,I,S,Q,O> old_value;
};
template<int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
inline void sc_trace(sc_core::sc_trace_file *tf, const ac_fixed<W,I,S,Q,O> &a, const std::string &name)
{
using namespace sc_core;
if (tf) {
//--- SystemC 2.2.0 deficiency. The 'initialized' class member of sc_trace_file is
// declared as 'protected' and does not have a public access 'get_initialized()' method.
// Therefore, we cannot check for initialized so the following code is commented out.
//if( tf->initialized ) {
// put_error_message(
// "No traces can be added once simulation has started.\n"
// "To add traces, create a new vcd trace file.", false );
//}
vcd_trace *t = (vcd_trace*) new vcd_ac_fixed_trace<W,I,S,Q,O>(a,name,((vcd_trace_file*)tf)->obtain_name());
((vcd_trace_file*)tf)->traces.push_back(t);
}
}
//==============================================================================
#endif
#endif
#if defined(__AC_FLOAT_H) && !defined(SC_TRACE_AC_FLOAT)
#define SC_TRACE_AC_FLOAT
//==============================================================================
// TRACING SUPPORT FOR AC_FLOAT
template<int W, int I, int E, ac_q_mode Q>
class vcd_ac_float_trace : public sc_core::vcd_trace
{
public:
vcd_ac_float_trace(const ac_float<W,I,E,Q> &object_, const std::string& name_, const std::string& vcd_name_) :
vcd_trace(name_, vcd_name_), object(object_)
{
vcd_var_typ_name = "wire"; // SystemC does not expose vcd_types[] in sc_vcd_trace.h
bit_width = W; // bit_width defined in base class 'vcd_trace'
}
virtual void print_variable_declaration_line(FILE* f) {
char buf[2000];
std::string namecopy = name;
#if !defined(NCSC)
remove_vcd_name_problems(namecopy);
#endif
std::sprintf(buf, "$var %s % 3d %s %s [%d:0] $end\n", vcd_var_typ_name,bit_width,vcd_name.c_str(),namecopy.c_str(),bit_width-1);
std::fputs(buf, f);
}
virtual void write(FILE* f) {
// The function to_string(AC_BIN) returns a string with the zero-radix prefix (i.e. "0b").
// Strip that prefix off because compose_line will add its own.
std::fprintf(f, "%s", compose_line(object.to_string(AC_BIN).substr(2)).c_str());
old_value = object;
}
virtual void set_width() { bit_width = W; }
// Comparison function needs to be pure virtual too
virtual bool changed() { return !(object == old_value); }
virtual ~vcd_ac_float_trace() {}
protected:
const ac_float<W,I,E,Q> &object;
ac_float<W,I,E,Q> old_value;
};
template<int W, int I, int E, ac_q_mode Q>
inline void sc_trace(sc_core::sc_trace_file *tf, const ac_float<W,I,E,Q> &a, const std::string &name)
{
using namespace sc_core;
if (tf) {
//--- SystemC 2.2.0 deficiency. The 'initialized' class member of sc_trace_file is
// declared as 'protected' and does not have a public access 'get_initialized()' method.
// Therefore, we cannot check for initialized so the following code is commented out.
//if( tf->initialized ) {
// put_error_message(
// "No traces can be added once simulation has started.\n"
// "To add traces, create a new vcd trace file.", false );
//}
vcd_trace *t = (vcd_trace*) new vcd_ac_float_trace<W,I,E,Q>(a,name,((vcd_trace_file*)tf)->obtain_name());
((vcd_trace_file*)tf)->traces.push_back(t);
}
}
//==============================================================================
#endif
#if defined(__AC_COMPLEX_H) && !defined(SC_TRACE_AC_COMPLEX)
#define SC_TRACE_AC_COMPLEX
template<typename T>
inline void sc_trace(sc_core::sc_trace_file *tf, const ac_complex<T> &a, const std::string &name)
{
sc_trace(tf, a.real(), name + ".r");
sc_trace(tf, a.imag(), name + ".i");
}
#endif
} // namespace ac_tracing
#ifdef __AC_NAMESPACE
}
#endif
namespace sc_core {
#ifdef __AC_NAMESPACE
using __AC_NAMESPACE::ac_tracing::sc_trace;
#else
using ac_tracing::sc_trace;
#endif
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.