Whitespace and pointer cleanup.

This commit is contained in:
jmsgrogan 2021-03-29 21:31:24 +01:00
parent 6fc0b8dca8
commit a03eb9599f
32 changed files with 441 additions and 468 deletions

View file

@ -10,73 +10,73 @@ const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
int main() int main()
{ {
CoInitialize(nullptr); CoInitialize(nullptr);
IMMDeviceEnumerator* pEnumerator = nullptr; IMMDeviceEnumerator* pEnumerator = nullptr;
IMMDeviceCollection* pDeviceCollection = nullptr; IMMDeviceCollection* pDeviceCollection = nullptr;
HRESULT hr = S_OK; HRESULT hr = S_OK;
hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL,
IID_IMMDeviceEnumerator, (void**)& pEnumerator); IID_IMMDeviceEnumerator, (void**)& pEnumerator);
if (!pEnumerator) if (!pEnumerator)
{ {
std::cout << "Failed to populate enumerator" << std::endl; std::cout << "Failed to populate enumerator" << std::endl;
return 0; return 0;
} }
hr = pEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pDeviceCollection); hr = pEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pDeviceCollection);
UINT count; UINT count;
hr = pDeviceCollection->GetCount(&count); hr = pDeviceCollection->GetCount(&count);
if (count == 0) if (count == 0)
{ {
std::cout << "No devices found\n"; std::cout << "No devices found\n";
} }
// Each loop prints the name of an endpoint device. // Each loop prints the name of an endpoint device.
IMMDevice* pEndpoint = nullptr; IMMDevice* pEndpoint = nullptr;
IPropertyStore* pProps = nullptr; IPropertyStore* pProps = nullptr;
LPWSTR pwszID = nullptr; LPWSTR pwszID = nullptr;
for (ULONG i = 0; i < count; i++) for (ULONG i = 0; i < count; i++)
{ {
// Get pointer to endpoint number i. // Get pointer to endpoint number i.
hr = pDeviceCollection->Item(i, &pEndpoint); hr = pDeviceCollection->Item(i, &pEndpoint);
// Get the endpoint ID string. // Get the endpoint ID string.
hr = pEndpoint->GetId(&pwszID); hr = pEndpoint->GetId(&pwszID);
hr = pEndpoint->OpenPropertyStore(STGM_READ, &pProps); hr = pEndpoint->OpenPropertyStore(STGM_READ, &pProps);
PROPVARIANT varName; PROPVARIANT varName;
// Initialize container for property value. // Initialize container for property value.
PropVariantInit(&varName); PropVariantInit(&varName);
// Get the endpoint's friendly-name property. // Get the endpoint's friendly-name property.
hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName); hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName);
// Print endpoint friendly name and endpoint ID. // Print endpoint friendly name and endpoint ID.
std::cout << "Endpoint: " << i << " " << varName.pwszVal << " " << pwszID << std::endl; std::cout << "Endpoint: " << i << " " << varName.pwszVal << " " << pwszID << std::endl;
CoTaskMemFree(pwszID); CoTaskMemFree(pwszID);
pwszID = nullptr; pwszID = nullptr;
PropVariantClear(&varName); PropVariantClear(&varName);
if (pProps) if (pProps)
{ {
pProps->Release(); pProps->Release();
pProps = nullptr; pProps = nullptr;
} }
if (pEndpoint) if (pEndpoint)
{ {
pEndpoint->Release(); pEndpoint->Release();
pEndpoint = nullptr; pEndpoint = nullptr;
} }
} }
if (pEnumerator) if (pEnumerator)
{ {
pEnumerator->Release(); pEnumerator->Release();
pEnumerator = nullptr; pEnumerator = nullptr;
} }
if (pDeviceCollection) if (pDeviceCollection)
{ {
pDeviceCollection->Release(); pDeviceCollection->Release();
pDeviceCollection = nullptr; pDeviceCollection = nullptr;
} }
return 0; return 0;
} }

View file

@ -6,33 +6,33 @@
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
CommandLineArgs command_line_args; CommandLineArgs command_line_args;
command_line_args.Process(argc, argv); command_line_args.Process(argc, argv);
if(command_line_args.GetNumberOfArgs() < 2) if(command_line_args.GetNumberOfArgs() < 2)
{ {
std::cerr << "Expected a filepath argument" << std::endl; std::cerr << "Expected a filepath argument" << std::endl;
return -1; return -1;
} }
XmlParser parser; XmlParser parser;
const auto filepath = command_line_args.GetArg(1); const auto filepath = command_line_args.GetArg(1);
if(!std::filesystem::exists(filepath)) if(!std::filesystem::exists(filepath))
{ {
std::cerr << "Couldn't find file: " << filepath << std::endl; std::cerr << "Couldn't find file: " << filepath << std::endl;
return -1; return -1;
} }
std::ifstream xml_file; std::ifstream xml_file;
xml_file.open(filepath, std::ifstream::in); xml_file.open(filepath, std::ifstream::in);
while(xml_file.good()) while(xml_file.good())
{ {
std::string line; std::string line;
std::getline(xml_file, line); std::getline(xml_file, line);
parser.ProcessLine(line); parser.ProcessLine(line);
} }
xml_file.close(); xml_file.close();
return 0; return 0;
} }

View file

@ -1,11 +1,11 @@
#include "AudioDevice.h" #include "AudioDevice.h"
AudioDevice::AudioDevice() AudioDevice::AudioDevice()
: mName("plughw:1,0"), : mName("plughw:1,0"),
mSampleRate(44100), mSampleRate(44100),
mNumChannels(2), mNumChannels(2),
mPeriod(2), mPeriod(2),
mBufferSize() mBufferSize()
{ {
} }
@ -15,57 +15,57 @@ AudioDevice::~AudioDevice()
} }
std::shared_ptr<AudioDevice> AudioDevice::Create() std::unique_ptr<AudioDevice> AudioDevice::Create()
{ {
return std::make_shared<AudioDevice>(); return std::make_unique<AudioDevice>();
} }
void AudioDevice::SetNumChannels(unsigned numChannels) void AudioDevice::SetNumChannels(unsigned numChannels)
{ {
mNumChannels = numChannels; mNumChannels = numChannels;
} }
void AudioDevice::SetPeriod(unsigned period) void AudioDevice::SetPeriod(unsigned period)
{ {
mPeriod = period; mPeriod = period;
} }
void AudioDevice::SetBufferSize(std::size_t bufferSize) void AudioDevice::SetBufferSize(std::size_t bufferSize)
{ {
mBufferSize = bufferSize; mBufferSize = bufferSize;
} }
unsigned AudioDevice::GetNumChannels() unsigned AudioDevice::GetNumChannels() const
{ {
return mNumChannels; return mNumChannels;
} }
unsigned AudioDevice::GetPeriod() unsigned AudioDevice::GetPeriod() const
{ {
return mPeriod; return mPeriod;
} }
std::size_t AudioDevice::GetBufferSize() std::size_t AudioDevice::GetBufferSize() const
{ {
return mBufferSize; return mBufferSize;
} }
void AudioDevice::SetSampleRate(unsigned rate) void AudioDevice::SetSampleRate(unsigned rate)
{ {
mSampleRate = rate; mSampleRate = rate;
} }
unsigned AudioDevice::GetSampleRate() unsigned AudioDevice::GetSampleRate() const
{ {
return mSampleRate; return mSampleRate;
} }
void AudioDevice::SetName(const std::string& name) void AudioDevice::SetName(const std::string& name)
{ {
mName = name; mName = name;
} }
std::string AudioDevice::GetName() std::string AudioDevice::GetName() const
{ {
return mName; return mName;
} }

View file

@ -8,39 +8,39 @@ class AudioDevice
private: private:
std::string mName; std::string mName;
unsigned mSampleRate; unsigned mSampleRate;
unsigned mNumChannels; unsigned mNumChannels;
unsigned mPeriod; unsigned mPeriod;
std::size_t mBufferSize; std::size_t mBufferSize;
public: public:
AudioDevice(); AudioDevice();
~AudioDevice(); ~AudioDevice();
void SetSampleRate(unsigned rate); void SetSampleRate(unsigned rate);
unsigned GetSampleRate(); unsigned GetSampleRate() const;
void SetName(const std::string& name); void SetName(const std::string& name);
void SetNumChannels(unsigned numChannels); void SetNumChannels(unsigned numChannels);
void SetPeriod(unsigned period); void SetPeriod(unsigned period);
void SetBufferSize(std::size_t bufferSize); void SetBufferSize(std::size_t bufferSize);
unsigned GetNumChannels(); unsigned GetNumChannels() const;
unsigned GetPeriod(); unsigned GetPeriod() const;
std::size_t GetBufferSize(); std::size_t GetBufferSize() const;
std::string GetName(); std::string GetName() const;
static std::shared_ptr<AudioDevice> Create(); static std::unique_ptr<AudioDevice> Create();
}; };
using AudioDevicePtr = std::shared_ptr<AudioDevice>; using AudioDevicePtr = std::unique_ptr<AudioDevice>;

View file

@ -1,10 +1,11 @@
#include "AudioManager.h" #include "AudioManager.h"
#include "AlsaInterface.h"
AudioManager::AudioManager() AudioManager::AudioManager()
: mAudioDevices(), : mAudioDevices(),
mAudioInterface() mAudioInterface()
{ {
mAudioInterface = AudioInterface::Create(); mAudioInterface = AlsaInterface::Create();
} }
AudioManager::~AudioManager() AudioManager::~AudioManager()
@ -22,7 +23,7 @@ void AudioManager::AddAudioDevice(AudioDevicePtr device)
mAudioDevices.push_back(device); mAudioDevices.push_back(device);
} }
AudioInterface* AudioManager::GetAudioInterface() IAudioInterface* AudioManager::GetAudioInterface()
{ {
return mAudioInterface.get(); return mAudioInterface.get();
} }

View file

@ -3,7 +3,7 @@
#include <memory> #include <memory>
#include <vector> #include <vector>
#include "AudioInterface.h" #include "audio_interfaces/IAudioInterface.h"
#include "AudioDevice.h" #include "AudioDevice.h"
class AudioManager class AudioManager
@ -12,7 +12,7 @@ class AudioManager
private: private:
std::vector<AudioDevicePtr> mAudioDevices; std::vector<AudioDevicePtr> mAudioDevices;
AudioInterfaceUPtr mAudioInterface; IAudioInterfaceUPtr mAudioInterface;
public: public:
@ -26,7 +26,7 @@ public:
std::vector<AudioDevicePtr> GetAudioDevices(); std::vector<AudioDevicePtr> GetAudioDevices();
AudioInterface* GetAudioInterface(); IAudioInterface* GetAudioInterface();
}; };
using AudioManagerUPtr = std::unique_ptr<AudioManager>; using AudioManagerUPtr = std::unique_ptr<AudioManager>;

View file

@ -5,7 +5,7 @@ list(APPEND linux_HEADERS
list(APPEND audio_HEADERS list(APPEND audio_HEADERS
AudioDevice.h AudioDevice.h
AudioManager.h AudioManager.h
audio_interfaces/AudioInterface.h audio_interfaces/IAudioInterface.h
midi/MidiReader.h midi/MidiReader.h
midi/MidiTrack.h midi/MidiTrack.h
midi/MidiDocument.h midi/MidiDocument.h
@ -20,7 +20,6 @@ list(APPEND linux_INCLUDES
list(APPEND audio_LIB_INCLUDES list(APPEND audio_LIB_INCLUDES
AudioDevice.cpp AudioDevice.cpp
AudioManager.cpp AudioManager.cpp
audio_interfaces/AudioInterface.cpp
midi/MidiReader.cpp midi/MidiReader.cpp
midi/MidiTrack.cpp midi/MidiTrack.cpp
midi/MidiDocument.cpp midi/MidiDocument.cpp
@ -28,7 +27,7 @@ list(APPEND audio_LIB_INCLUDES
midi/MetaMidiEvent.cpp midi/MetaMidiEvent.cpp
midi/MidiChannelEvent.cpp) midi/MidiChannelEvent.cpp)
add_library(audio SHARED ${audio_LIB_INCLUDES} ${audio_HEADERS}) add_library(audio SHARED ${audio_LIB_INCLUDES} ${linux_INCLUDES} ${audio_HEADERS} ${linux_HEADERS})
target_include_directories(audio PUBLIC target_include_directories(audio PUBLIC
"${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}"
"${PROJECT_SOURCE_DIR}/src/core/file_utilities" "${PROJECT_SOURCE_DIR}/src/core/file_utilities"
@ -41,6 +40,6 @@ list(APPEND linux_LIBS
asound asound
) )
target_link_libraries(audio PUBLIC core) target_link_libraries(audio PUBLIC core ${linux_LIBS})
set_target_properties( audio PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON ) set_target_properties( audio PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON )
set_property(TARGET audio PROPERTY FOLDER src) set_property(TARGET audio PROPERTY FOLDER src)

View file

@ -19,7 +19,7 @@ std::shared_ptr<AlsaInterface> AlsaInterface::Create()
return std::make_shared<AlsaInterface>(); return std::make_shared<AlsaInterface>();
} }
void AlsaInterface::OpenDevice(AudioDevicePtr device) void AlsaInterface::OpenDevice(const AudioDevicePtr& device)
{ {
MLOG_INFO("Opening Device"); MLOG_INFO("Opening Device");
snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK; snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
@ -115,7 +115,7 @@ void AlsaInterface::SetChannelNumber(AudioDevicePtr device)
} }
} }
void AlsaInterface::Play(AudioDevicePtr device) void AlsaInterface::Play(const AudioDevicePtr& device)
{ {
MLOG_INFO("Playing audio"); MLOG_INFO("Playing audio");
unsigned char *data = (unsigned char *)malloc(mPeriodSize); unsigned char *data = (unsigned char *)malloc(mPeriodSize);

View file

@ -3,37 +3,39 @@
#include <memory> #include <memory>
#include <alsa/asoundlib.h> #include <alsa/asoundlib.h>
#include "IAudioInterface.h"
#include "AudioDevice.h" #include "AudioDevice.h"
class AlsaInterface class AlsaInterface : public IAudioInterface
{ {
snd_pcm_t* mHandle; snd_pcm_t* mHandle;
snd_pcm_hw_params_t* mHardwareParams; snd_pcm_hw_params_t* mHardwareParams;
snd_pcm_uframes_t mPeriodSize; snd_pcm_uframes_t mPeriodSize;
public: public:
AlsaInterface(); AlsaInterface();
~AlsaInterface(); ~AlsaInterface();
static std::shared_ptr<AlsaInterface> Create(); static std::shared_ptr<AlsaInterface> Create();
void OpenDevice(AudioDevicePtr device); void OpenDevice(const AudioDevicePtr& device) override;
void SetAccessType(AudioDevicePtr device); void SetAccessType(AudioDevicePtr device);
void SetSampleFormat(AudioDevicePtr device); void SetSampleFormat(AudioDevicePtr device);
void SetSampleRate(AudioDevicePtr device); void SetSampleRate(AudioDevicePtr device);
void SetPeriod(AudioDevicePtr device); void SetPeriod(AudioDevicePtr device);
void SetBufferSize(AudioDevicePtr device); void SetBufferSize(AudioDevicePtr device);
void SetChannelNumber(AudioDevicePtr device); void SetChannelNumber(AudioDevicePtr device);
void Play(AudioDevicePtr device); void Play(const AudioDevicePtr& device) override;
}; };
using AlsaInterfacePtr = std::shared_ptr<AlsaInterface>; using AlsaInterfacePtr = std::shared_ptr<AlsaInterface>;

View file

@ -1,22 +0,0 @@
#include "AudioInterface.h"
#include "AudioDevice.h"
AudioInterface::AudioInterface()
{
}
std::unique_ptr<AudioInterface> AudioInterface::Create()
{
return std::make_unique<AudioInterface>();
}
void AudioInterface::OpenDevice(AudioDevicePtr device)
{
}
void AudioInterface::Play(AudioDevicePtr device)
{
}

View file

@ -3,19 +3,19 @@
#include <memory> #include <memory>
class AudioDevice; class AudioDevice;
using AudioDevicePtr = std::shared_ptr<AudioDevice>; using AudioDevicePtr = std::unique_ptr<AudioDevice>;
class AudioInterface class IAudioInterface
{ {
public: public:
AudioInterface(); IAudioInterface() = default;
static std::unique_ptr<AudioInterface> Create(); virtual ~IAudioInterface() = default;
void OpenDevice(AudioDevicePtr device); virtual void OpenDevice(const AudioDevicePtr& device) = 0;
void Play(AudioDevicePtr device); virtual void Play(const AudioDevicePtr& device) = 0;
}; };
using AudioInterfaceUPtr = std::unique_ptr<AudioInterface>; using IAudioInterfaceUPtr = std::unique_ptr<IAudioInterface>;

View file

@ -20,7 +20,7 @@ MainApplication::~MainApplication()
void MainApplication::Initialize(CommandLineArgsUPtr commandLineArgs) void MainApplication::Initialize(CommandLineArgsUPtr commandLineArgs)
{ {
mCommandLineArgs = std::move(commandLineArgs); mCommandLineArgs = std::move(commandLineArgs);
std::string launch_path = mCommandLineArgs->GetLaunchPath().string(); const auto launch_path = mCommandLineArgs->GetLaunchPath().string();
FileLogger::GetInstance().SetWorkDirectory(launch_path); FileLogger::GetInstance().SetWorkDirectory(launch_path);
FileLogger::GetInstance().Open(); FileLogger::GetInstance().Open();

View file

@ -4,78 +4,78 @@
class ByteUtils class ByteUtils
{ {
public: public:
using Word = int; using Word = int;
using DWord = int; using DWord = int;
static int GetWordFirstBit(const Word word) static int GetWordFirstBit(const Word word)
{ {
return word & ByteUtils::WORD_FIRST_BIT; return word & ByteUtils::WORD_FIRST_BIT;
}; };
static int GetWordLastByte(const Word word) static int GetWordLastByte(const Word word)
{ {
return word & ByteUtils::WORD_LAST_BYTE; return word & ByteUtils::WORD_LAST_BYTE;
} }
static void ReverseBuffer(char* buffer, char* reverse, unsigned size) static void ReverseBuffer(char* buffer, char* reverse, unsigned size)
{ {
for(unsigned idx=0; idx<size; idx++) for(unsigned idx=0; idx<size; idx++)
{ {
reverse[idx] = buffer[size - 1 -idx]; reverse[idx] = buffer[size - 1 -idx];
} }
} }
static int ToInt(char* buffer, const unsigned size, bool reverse = true) static int ToInt(char* buffer, const unsigned size, bool reverse = true)
{ {
int result; int result;
if(reverse) if(reverse)
{ {
std::string reversed; std::string reversed;
ReverseBuffer(buffer, reversed.data(), size); ReverseBuffer(buffer, reversed.data(), size);
std::memcpy(&result, reversed.data(), sizeof(int)); std::memcpy(&result, reversed.data(), sizeof(int));
} }
else else
{ {
std::memcpy(&result, buffer, sizeof(int)); std::memcpy(&result, buffer, sizeof(int));
} }
return result; return result;
} }
static Word ToWord(char* buffer, bool reverse = true) static Word ToWord(char* buffer, bool reverse = true)
{ {
return ToInt(buffer, BYTES_PER_WORD, reverse); return ToInt(buffer, BYTES_PER_WORD, reverse);
} }
static DWord ToDWord(char* buffer, bool reverse = true) static DWord ToDWord(char* buffer, bool reverse = true)
{ {
return ToInt(buffer, BYTES_PER_DWORD, reverse); return ToInt(buffer, BYTES_PER_DWORD, reverse);
} }
static bool Compare(char* buffer, const char* tag, unsigned size) static bool Compare(char* buffer, const char* tag, unsigned size)
{ {
for(unsigned idx=0; idx<size; idx++) for(unsigned idx=0; idx<size; idx++)
{ {
if(tag[idx] != buffer[idx]) if(tag[idx] != buffer[idx])
{ {
return false; return false;
} }
} }
return true; return true;
} }
static bool CompareDWords(char* buffer, const char* tag) static bool CompareDWords(char* buffer, const char* tag)
{ {
return Compare(buffer, tag, BYTES_PER_DWORD); return Compare(buffer, tag, BYTES_PER_DWORD);
} }
static bool CompareWords(char* buffer, const char* tag) static bool CompareWords(char* buffer, const char* tag)
{ {
return Compare(buffer, tag, BYTES_PER_WORD); return Compare(buffer, tag, BYTES_PER_WORD);
} }
static const int BYTES_PER_WORD = 2; static const int BYTES_PER_WORD = 2;
static const int BYTES_PER_DWORD = 4; static const int BYTES_PER_DWORD = 4;
static const int BYTE_FIRST_BIT = 0x40; // 1000 0000 static const int BYTE_FIRST_BIT = 0x40; // 1000 0000
static const int WORD_FIRST_BIT = 0x8000; // 1000 0000 - 0000 0000 static const int WORD_FIRST_BIT = 0x8000; // 1000 0000 - 0000 0000
static const int WORD_LAST_BYTE = 0x00FF; // 0000 0000 - 1111 1111 static const int WORD_LAST_BYTE = 0x00FF; // 0000 0000 - 1111 1111
}; };

View file

@ -4,14 +4,14 @@
bool StringUtils::IsAlphaNumeric(char c) bool StringUtils::IsAlphaNumeric(char c)
{ {
std::locale loc; std::locale loc;
return std::isalnum(c, loc); return std::isalnum(c, loc);
} }
bool StringUtils::IsSpace(char c) bool StringUtils::IsSpace(char c)
{ {
std::locale loc; std::locale loc;
return std::isspace(c, loc); return std::isspace(c, loc);
} }
std::string StringUtils::ToLower(const std::string& s) std::string StringUtils::ToLower(const std::string& s)

View file

@ -5,16 +5,16 @@
class StringUtils class StringUtils
{ {
public: public:
static constexpr char LEFT_BRACKET = '<'; static constexpr char LEFT_BRACKET = '<';
static constexpr char RIGHT_BRACKET = '>'; static constexpr char RIGHT_BRACKET = '>';
static constexpr char FORWARD_SLASH = '/'; static constexpr char FORWARD_SLASH = '/';
static constexpr char BACK_SLASH = '\\'; static constexpr char BACK_SLASH = '\\';
static constexpr char QUESTION_MARK = '?'; static constexpr char QUESTION_MARK = '?';
static constexpr char EQUALS = '='; static constexpr char EQUALS = '=';
static constexpr char DOUBLE_QUOTE = '"'; static constexpr char DOUBLE_QUOTE = '"';
static constexpr char SINGLE_QUOTE = '\''; static constexpr char SINGLE_QUOTE = '\'';
static bool IsAlphaNumeric(char c); static bool IsAlphaNumeric(char c);
static bool IsSpace(char c); static bool IsSpace(char c);
static std::string ToLower(const std::string& s); static std::string ToLower(const std::string& s);
}; };

View file

@ -1,10 +1,10 @@
#include "HttpResponse.h" #include "HttpResponse.h"
HttpResponse::HttpResponse() HttpResponse::HttpResponse()
:mHttpVersion("1.1"), :mHttpVersion("1.1"),
mResponseCode("200 OK"), mResponseCode("200 OK"),
mContentType("text/plain"), mContentType("text/plain"),
mBody() mBody()
{ {
} }
@ -16,23 +16,23 @@ HttpResponse::~HttpResponse()
void HttpResponse::SetBody(const std::string& body) void HttpResponse::SetBody(const std::string& body)
{ {
mBody = body; mBody = body;
} }
unsigned HttpResponse::GetBodyLength() unsigned HttpResponse::GetBodyLength() const
{ {
return unsigned(mBody.length()); return unsigned(mBody.length());
} }
std::string HttpResponse::GetHeaderString() std::string HttpResponse::GetHeaderString() const
{ {
std::string header = "HTTP/" + mHttpVersion + " " + mResponseCode + "\n"; std::string header = "HTTP/" + mHttpVersion + " " + mResponseCode + "\n";
header += "Content-Type: " + mContentType + "\n"; header += "Content-Type: " + mContentType + "\n";
header += "Content-Length: " + std::to_string(GetBodyLength()) + "\n"; header += "Content-Length: " + std::to_string(GetBodyLength()) + "\n";
return header; return header;
} }
std::string HttpResponse::ToString() std::string HttpResponse::ToString() const
{ {
return GetHeaderString() + "\n\n" + mBody; return GetHeaderString() + "\n\n" + mBody;
} }

View file

@ -5,22 +5,22 @@
class HttpResponse class HttpResponse
{ {
std::string mHttpVersion; std::string mHttpVersion;
std::string mResponseCode; std::string mResponseCode;
std::string mContentType; std::string mContentType;
std::string mBody; std::string mBody;
public: public:
HttpResponse(); HttpResponse();
~HttpResponse(); ~HttpResponse();
void SetBody(const std::string& body); void SetBody(const std::string& body);
unsigned GetBodyLength(); unsigned GetBodyLength() const;
std::string GetHeaderString(); std::string GetHeaderString() const;
std::string ToString(); std::string ToString() const;
}; };

View file

@ -1,7 +1,7 @@
#include "Database.h" #include "Database.h"
Database::Database() Database::Database()
: mPath() : mPath()
{ {
} }
@ -11,17 +11,17 @@ Database::~Database()
} }
std::shared_ptr<Database> Database::Create() std::unique_ptr<Database> Database::Create()
{ {
return std::make_shared<Database>(); return std::make_unique<Database>();
} }
void Database::SetPath(const std::string& path) void Database::SetPath(const std::string& path)
{ {
mPath = path; mPath = path;
} }
std::string Database::GetPath() std::string Database::GetPath() const
{ {
return mPath; return mPath;
} }

View file

@ -6,19 +6,19 @@
class Database class Database
{ {
std::string mPath; std::string mPath;
public: public:
Database(); Database();
~Database(); ~Database();
static std::shared_ptr<Database> Create(); static std::unique_ptr<Database> Create();
void SetPath(const std::string& path); void SetPath(const std::string& path);
std::string GetPath(); std::string GetPath() const;
}; };
using DatabasePtr = std::shared_ptr<Database>; using DatabasePtr = std::unique_ptr<Database>;

View file

@ -1,8 +1,8 @@
#include "DatabaseManager.h" #include "DatabaseManager.h"
DatabaseManager::DatabaseManager() DatabaseManager::DatabaseManager()
: mDatabase(), : mDatabase(),
mDatabaseInterface() mDatabaseInterface()
{ {
} }
@ -12,25 +12,25 @@ DatabaseManager::~DatabaseManager()
} }
std::shared_ptr<DatabaseManager> DatabaseManager::Create() std::unique_ptr<DatabaseManager> DatabaseManager::Create()
{ {
return std::make_shared<DatabaseManager>(); return std::make_unique<DatabaseManager>();
} }
void DatabaseManager::CreateDatabase(const std::string& path) void DatabaseManager::CreateDatabase(const std::string& path)
{ {
mDatabase = Database::Create(); mDatabase = Database::Create();
mDatabase->SetPath(path); mDatabase->SetPath(path);
mDatabaseInterface = SqliteInterface::Create(); mDatabaseInterface = SqliteInterface::Create();
mDatabaseInterface->Open(mDatabase); mDatabaseInterface->Open(mDatabase);
} }
void DatabaseManager::OnShutDown() void DatabaseManager::OnShutDown()
{ {
if(mDatabaseInterface) if(mDatabaseInterface)
{ {
mDatabaseInterface->Close(); mDatabaseInterface->Close();
} }
} }

View file

@ -8,20 +8,20 @@
class DatabaseManager class DatabaseManager
{ {
DatabasePtr mDatabase; DatabasePtr mDatabase;
SqliteInterfacePtr mDatabaseInterface; SqliteInterfacePtr mDatabaseInterface;
public: public:
DatabaseManager(); DatabaseManager();
~DatabaseManager(); ~DatabaseManager();
static std::shared_ptr<DatabaseManager> Create(); static std::unique_ptr<DatabaseManager> Create();
void CreateDatabase(const std::string& path); void CreateDatabase(const std::string& path);
void OnShutDown(); void OnShutDown();
}; };
using DatabaseManagerPtr = std::shared_ptr<DatabaseManager>; using DatabaseManagerPtr = std::unique_ptr<DatabaseManager>;

View file

@ -3,7 +3,7 @@
#include <iostream> #include <iostream>
SqliteInterface::SqliteInterface() SqliteInterface::SqliteInterface()
: mSqliteDb(nullptr) : mSqliteDb(nullptr)
{ {
} }
@ -13,44 +13,44 @@ SqliteInterface::~SqliteInterface()
} }
std::shared_ptr<SqliteInterface> SqliteInterface::Create() std::unique_ptr<SqliteInterface> SqliteInterface::Create()
{ {
return std::make_shared<SqliteInterface>(); return std::make_unique<SqliteInterface>();
} }
void SqliteInterface::Open(DatabasePtr db) void SqliteInterface::Open(const DatabasePtr& db)
{ {
int rc = sqlite3_open(db->GetPath().c_str(), &mSqliteDb); int rc = sqlite3_open(db->GetPath().c_str(), &mSqliteDb);
if( rc ) if( rc )
{ {
std::cout << "Can't open database: %s\n" << sqlite3_errmsg(mSqliteDb) << std::endl; std::cout << "Can't open database: %s\n" << sqlite3_errmsg(mSqliteDb) << std::endl;
sqlite3_close(mSqliteDb); sqlite3_close(mSqliteDb);
} }
} }
static int callback(void *NotUsed, int argc, char **argv, char **azColName) static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{ {
for(int i=0; i<argc; i++) for(int i=0; i<argc; i++)
{ {
//std::cout << "%s = %s\n" << azColName[i] << argv[i] ? argv[i] : "NULL" << std::endl; //std::cout << "%s = %s\n" << azColName[i] << argv[i] ? argv[i] : "NULL" << std::endl;
std::cout << "NULL" << std::endl; std::cout << "NULL" << std::endl;
} }
return 0; return 0;
} }
void SqliteInterface::Run(const std::string& statement) void SqliteInterface::Run(const std::string& statement)
{ {
char *zErrMsg = 0; char *zErrMsg = 0;
int rc = sqlite3_exec(mSqliteDb, statement.c_str(), callback, 0, &zErrMsg); int rc = sqlite3_exec(mSqliteDb, statement.c_str(), callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ) if (rc != SQLITE_OK)
{ {
std::cout << "SQL error: %s\n" << zErrMsg << std::endl; std::cout << "SQL error: %s\n" << zErrMsg << std::endl;
sqlite3_free(zErrMsg); sqlite3_free(zErrMsg);
} }
} }
void SqliteInterface::Close() void SqliteInterface::Close()
{ {
sqlite3_close(mSqliteDb); sqlite3_close(mSqliteDb);
} }

View file

@ -6,21 +6,21 @@
class SqliteInterface class SqliteInterface
{ {
sqlite3* mSqliteDb; sqlite3* mSqliteDb;
public: public:
SqliteInterface(); SqliteInterface();
~SqliteInterface(); ~SqliteInterface();
static std::shared_ptr<SqliteInterface> Create(); static std::unique_ptr<SqliteInterface> Create();
void Open(DatabasePtr db); void Open(const DatabasePtr& db);
void Close(); void Close();
void Run(const std::string& statement); void Run(const std::string& statement);
}; };
using SqliteInterfacePtr = std::shared_ptr<SqliteInterface>; using SqliteInterfacePtr = std::unique_ptr<SqliteInterface>;

View file

@ -10,10 +10,9 @@ list(APPEND network_HEADERS
list(APPEND network_LIB_INCLUDES list(APPEND network_LIB_INCLUDES
NetworkManager.cpp NetworkManager.cpp
sockets/Socket.cpp sockets/Socket.cpp
sockets/SocketInterface.cpp
) )
add_library(network SHARED ${network_LIB_INCLUDES} ${network_HEADERS}) add_library(network SHARED ${network_LIB_INCLUDES} ${linux_INCLUDES} ${network_HEADERS})
target_include_directories(network PUBLIC target_include_directories(network PUBLIC
"${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}"

View file

@ -1,8 +1,11 @@
#include "NetworkManager.h" #include "NetworkManager.h"
#ifdef __linux__
#include "UnixSocketInterface.h"
#endif
NetworkManager::NetworkManager() NetworkManager::NetworkManager()
: mActiveSockets(), : mActiveSockets(),
mSocketInterface() mSocketInterface()
{ {
} }
@ -19,13 +22,18 @@ std::unique_ptr<NetworkManager> NetworkManager::Create()
void NetworkManager::Initialize() void NetworkManager::Initialize()
{ {
mSocketInterface = SocketInterface::Create(); mSocketInterface = UnixSocketInterface::Create();
} }
void NetworkManager::RunHttpServer() void NetworkManager::RunHttpServer()
{ {
if (!mSocketInterface)
{
Initialize();
}
auto socket = Socket::Create(); auto socket = Socket::Create();
mSocketInterface->CreateSocket(socket); mSocketInterface->InitializeSocket(socket);
mSocketInterface->Listen(socket); mSocketInterface->Listen(socket);
mSocketInterface->Run(socket); mSocketInterface->Run(socket);
} }

View file

@ -1,15 +1,15 @@
#pragma once #pragma once
#include <memory>
#include <vector>
#include "Socket.h" #include "Socket.h"
#include "SocketInterface.h" #include "SocketInterface.h"
#include <memory>
#include <vector>
class NetworkManager class NetworkManager
{ {
std::vector<SocketPtr> mActiveSockets; std::vector<SocketPtr> mActiveSockets;
SocketInterfaceUPtr mSocketInterface; ISocketInterfaceUPtr mSocketInterface;
public: public:
@ -21,10 +21,6 @@ public:
void Initialize(); void Initialize();
void OpenSocket(SocketPtr socket);
void CloseSocket(SocketPtr socket);
void RunHttpServer(); void RunHttpServer();
void ShutDown(); void ShutDown();

View file

@ -1,8 +1,9 @@
#include "Socket.h" #include "Socket.h"
Socket::Socket() Socket::Socket()
: mPort(8888), : mPort(8888),
mMessage() mMessage(),
mHandle(-1)
{ {
} }
@ -12,27 +13,37 @@ Socket::~Socket()
} }
std::shared_ptr<Socket> Socket::Create() void Socket::SetHandle(SocketHandle handle)
{ {
return std::make_shared<Socket>(); mHandle = handle;
} }
std::string Socket::GetMessage() Socket::SocketHandle Socket::GetHandle() const
{ {
return mMessage; return mHandle;
}
std::unique_ptr<Socket> Socket::Create()
{
return std::make_unique<Socket>();
}
std::string Socket::GetMessage() const
{
return mMessage;
} }
void Socket::SetMessage(const std::string& message) void Socket::SetMessage(const std::string& message)
{ {
mMessage = message; mMessage = message;
} }
void Socket::SetPort(unsigned port) void Socket::SetPort(unsigned port)
{ {
mPort = port; mPort = port;
} }
unsigned Socket::GetPort() unsigned Socket::GetPort() const
{ {
return mPort; return mPort;
} }

View file

@ -5,24 +5,32 @@
class Socket class Socket
{ {
unsigned mPort; using SocketHandle = int;
std::string mMessage;
public: public:
Socket(); Socket();
~Socket(); ~Socket();
static std::shared_ptr<Socket> Create(); static std::unique_ptr<Socket> Create();
void SetPort(unsigned port); void SetPort(unsigned port);
unsigned GetPort(); void SetHandle(SocketHandle handle);
std::string GetMessage(); SocketHandle GetHandle() const;
void SetMessage(const std::string& message); unsigned GetPort() const;
std::string GetMessage() const;
void SetMessage(const std::string& message);
private:
SocketHandle mHandle;
unsigned mPort;
std::string mMessage;
}; };
using SocketPtr = std::shared_ptr<Socket>; using SocketPtr = std::unique_ptr<Socket>;

View file

@ -1,27 +0,0 @@
#include "SocketInterface.h"
#include "Socket.h"
SocketInterface::SocketInterface()
{
}
std::unique_ptr<SocketInterface> SocketInterface::Create()
{
return std::make_unique<SocketInterface>();
}
void SocketInterface::CreateSocket(SocketPtr socket)
{
}
void SocketInterface::Listen(SocketPtr socket)
{
}
void SocketInterface::Run(SocketPtr socket)
{
}

View file

@ -1,20 +1,21 @@
#pragma #pragma once
#include <memory> #include <memory>
class Socket; class Socket;
using SocketPtr = std::shared_ptr<Socket>; using SocketPtr = std::unique_ptr<Socket>;
class SocketInterface class ISocketInterface
{ {
public: public:
SocketInterface(); ISocketInterface() = default;
static std::unique_ptr<SocketInterface> Create(); virtual ~ISocketInterface() = default;
void CreateSocket(SocketPtr socket);
void Listen(SocketPtr socket); virtual void InitializeSocket(const SocketPtr& socket) = 0;
void Run(SocketPtr socket); virtual void Listen(const SocketPtr& socket) = 0;
virtual void Run(const SocketPtr& socket) = 0;
}; };
using SocketInterfaceUPtr = std::unique_ptr<SocketInterface>; using ISocketInterfaceUPtr = std::unique_ptr<ISocketInterface>;

View file

@ -1,86 +1,82 @@
#include "UnixSocketInterface.h" #include "UnixSocketInterface.h"
#include "HttpResponse.h"
#include <iostream> #include <iostream>
#include <unistd.h> #include <unistd.h>
#include <string.h> #include <string.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <netinet/in.h> #include <netinet/in.h>
#include "HttpResponse.h"
UnixSocketInterface::UnixSocketInterface() UnixSocketInterface::UnixSocketInterface()
: mOpeningHandles(), : mBufferSize(1024)
mBufferSize(1024)
{ {
} }
UnixSocketInterface::~UnixSocketInterface() std::unique_ptr<UnixSocketInterface> UnixSocketInterface::Create()
{ {
return std::make_unique<UnixSocketInterface>();
} }
std::shared_ptr<UnixSocketInterface> UnixSocketInterface::Create() void UnixSocketInterface::InitializeSocket(const SocketPtr& socketPtr)
{ {
return std::make_shared<UnixSocketInterface>(); auto handle = socket(AF_INET, SOCK_STREAM, 0);
socketPtr->SetHandle(handle);
} }
void UnixSocketInterface::CreateSocket(SocketPtr socketPtr) void UnixSocketInterface::Listen(const SocketPtr& socket)
{ {
mOpeningHandles[socketPtr] = socket(AF_INET, SOCK_STREAM, 0); if(socket->GetHandle() < 0)
}
void UnixSocketInterface::Listen(SocketPtr socket)
{
if(mOpeningHandles[socket] < 0)
{ {
std::cerr << "Error opening socket" << std::endl; std::cerr << "Error opening socket" << std::endl;
return; return;
} }
int port = static_cast<int>(socket->GetPort()); int port = static_cast<int>(socket->GetPort());
struct sockaddr_in serv_addr; struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr)); memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET; serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port); serv_addr.sin_port = htons(port);
int result = bind(mOpeningHandles[socket], (struct sockaddr *)&serv_addr, sizeof(serv_addr)); int result = bind(socket->GetHandle(), (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if(result< 0) if(result< 0)
{ {
std::cerr << "Error binding socket" << std::endl; std::cerr << "Error binding socket" << std::endl;
return; return;
} }
listen(mOpeningHandles[socket], 5); listen(socket->GetHandle(), 5);
} }
void UnixSocketInterface::Run(SocketPtr socket) void UnixSocketInterface::Run(const SocketPtr& socket)
{ {
if(mOpeningHandles[socket] < 0) if(socket->GetHandle() < 0)
{ {
std::cerr << "Error opening socket" << std::endl; std::cerr << "Error opening socket" << std::endl;
return; return;
} }
struct sockaddr_in cli_addr; struct sockaddr_in cli_addr;
socklen_t clilen = sizeof(cli_addr); socklen_t clilen = sizeof(cli_addr);
while(true) while(true)
{ {
SocketHandle new_socket_handle = accept(mOpeningHandles[socket], auto new_socket_handle = accept(socket->GetHandle(),
(struct sockaddr *) &cli_addr, &clilen); (struct sockaddr *) &cli_addr, &clilen);
if (new_socket_handle < 0) if (new_socket_handle < 0)
{ {
std::cerr << "Error on accept" << std::endl; std::cerr << "Error on accept" << std::endl;
return; return;
} }
char buffer[mBufferSize] = {0}; char buffer[mBufferSize] = {0};
int n = read(new_socket_handle, buffer, mBufferSize); int n = read(new_socket_handle, buffer, mBufferSize);
if (n < 0) if (n < 0)
{ {
std::cerr << "Error on read" << std::endl; std::cerr << "Error on read" << std::endl;
return; return;
} }
socket->SetMessage(buffer); socket->SetMessage(buffer);
std::cout << "Here is the message: " << buffer << std::endl; std::cout << "Here is the message: " << buffer << std::endl;
@ -88,12 +84,12 @@ void UnixSocketInterface::Run(SocketPtr socket)
HttpResponse response; HttpResponse response;
response.SetBody("Hello world!"); response.SetBody("Hello world!");
std::string response_message = response.ToString(); auto response_message = response.ToString();
n = write(new_socket_handle, response_message.c_str(), response_message.length()); n = write(new_socket_handle, response_message.c_str(), response_message.length());
if (n < 0) if (n < 0)
{ {
std::cerr << "Error on write" << std::endl; std::cerr << "Error on write" << std::endl;
return; return;
} }
close(new_socket_handle); close(new_socket_handle);
} }

View file

@ -1,30 +1,31 @@
#pragma once #pragma once
#include "Socket.h"
#include "SocketInterface.h"
#include <memory> #include <memory>
#include <map> #include <map>
#include <cstddef>
#include "Socket.h" class UnixSocketInterface : public ISocketInterface
class UnixSocketInterface
{ {
using SocketHandle = int;
std::map<SocketPtr, SocketHandle> mOpeningHandles;
std::size_t mBufferSize;
public: public:
UnixSocketInterface(); UnixSocketInterface();
~UnixSocketInterface(); virtual ~UnixSocketInterface() = default;
static std::shared_ptr<UnixSocketInterface> Create(); static std::unique_ptr<UnixSocketInterface> Create();
void CreateSocket(SocketPtr socket); void InitializeSocket(const SocketPtr& socket) override;
void Listen(SocketPtr socket); void Listen(const SocketPtr& socket) override;
void Run(SocketPtr socket); void Run(const SocketPtr& socket) override;
private:
std::size_t mBufferSize { 0 };
}; };
using UnixSocketInterfacePtr = std::shared_ptr<UnixSocketInterface>; using UnixSocketInterfacePtr = std::unique_ptr<UnixSocketInterface>;