aboutsummaryrefslogtreecommitdiff
path: root/week13/Exercise3/Thread.cpp
diff options
context:
space:
mode:
authorSyndamia <kamen@syndamia.com>2024-05-25 16:08:17 +0300
committerSyndamia <kamen@syndamia.com>2024-05-25 16:08:17 +0300
commit9c11fababb9b6b194e646fbeb62d141aacf74c43 (patch)
treef1a294fcd66b22463b9424c838ff171db8539a15 /week13/Exercise3/Thread.cpp
parentc6fae5f1a0cc8394b1de3b671f07de7b3d677c59 (diff)
downloadoop-2023-solutions-9c11fababb9b6b194e646fbeb62d141aacf74c43.tar
oop-2023-solutions-9c11fababb9b6b194e646fbeb62d141aacf74c43.tar.gz
oop-2023-solutions-9c11fababb9b6b194e646fbeb62d141aacf74c43.zip
[w13] Added solutions
Diffstat (limited to 'week13/Exercise3/Thread.cpp')
-rw-r--r--week13/Exercise3/Thread.cpp85
1 files changed, 85 insertions, 0 deletions
diff --git a/week13/Exercise3/Thread.cpp b/week13/Exercise3/Thread.cpp
new file mode 100644
index 0000000..6cd13ba
--- /dev/null
+++ b/week13/Exercise3/Thread.cpp
@@ -0,0 +1,85 @@
+#include "Thread.h"
+#include <cstring>
+
+void Thread::resize() {
+ this->allocated *= 2;
+ char** moreMessages = new char*[this->allocated];
+ for (int i = 0; i < this->size; i++) {
+ moreMessages[i] = this->messages[i];
+ }
+ delete[] this->messages;
+ this->messages = moreMessages;
+}
+
+void Thread::free() {
+ for (int i = 0; i < size; i++) {
+ delete[] messages[i];
+ }
+ delete[] messages;
+}
+
+void Thread::copyFrom(const Thread& other) {
+ this->size = other.size;
+ this->allocated = other.allocated;
+ this->messages = new char*[allocated];
+ for (int i = 0; i < size; i++) {
+ this->messages[i] = new char[strlen(other.messages[i] + 1)];
+ strcpy(this->messages[i], other.messages[i]);
+ }
+}
+
+Thread::Thread() {
+ this->messages = nullptr;
+ this->size = this->allocated = 0;
+}
+
+Thread::~Thread() {
+ free();
+}
+
+Thread::Thread(const Thread& other) {
+ copyFrom(other);
+}
+
+Thread& Thread::operator=(const Thread& other) {
+ if (this != &other) {
+ free();
+ copyFrom(other);
+ }
+ return *this;
+}
+
+Thread::Thread(Thread&& other) {
+ this->size = other.size;
+ this->allocated = other.allocated;
+ this->messages = other.messages;
+ other.messages = nullptr;
+}
+
+Thread& Thread::operator=(Thread&& other) {
+ if (this != &other) {
+ free();
+
+ this->size = other.size;
+ this->allocated = other.allocated;
+ this->messages = other.messages;
+ other.messages = nullptr;
+ }
+ return *this;
+}
+
+void Thread::PostMessage(const User& poster, const char* message) {
+ if (poster.IsBanned()) {
+ throw "User cannot post!";
+ }
+ if (this->size == this->allocated) {
+ resize();
+ }
+
+ char* newMessage = new char[strlen(poster.GetUsername()) + 1 + strlen(message) + 1];
+ strcpy(newMessage, poster.GetUsername());
+ strcat(newMessage, " "); // За да знаем къде свършва потребителското име
+ strcat(newMessage, message);
+
+ this->messages[this->size++] = newMessage;
+}