From bf4f123f9ec88128920660747c7f7555bac895bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matt=C3=A9o=20Delucchi?= Date: Mon, 3 Jun 2024 18:57:44 +0200 Subject: [PATCH] feat(server): ajoute les commandes LOCK et UNLOCK --- src/Server/Command.cs | 52 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/Server/Command.cs b/src/Server/Command.cs index d663dcf..d201d67 100644 --- a/src/Server/Command.cs +++ b/src/Server/Command.cs @@ -19,6 +19,8 @@ public static Command Create(string command, Database db) "SET" => new SetCommand(db), "GET" => new GetCommand(db), "DEL" => new DelCommand(db), + "LOCK" => new LockCommand(db), + "UNLOCK" => new UnlockCommand(db), _ => new UnknownCommand(db), }; } @@ -120,4 +122,54 @@ public override Item execute(params string[] args) _db.Del(args[0]); return new SimpleString("OK"); } +} + +public class LockCommand : Command +{ + public LockCommand(Database db) : base(db) { } + + public override Item execute(params string[] args) + { + if (args.Length != 1) + return new SimpleError("Expected 1 argument"); + + _db.Lock(); + var mut = _db.Get(args[0]); + if (mut == null || mut == "f") + _db.Set(args[0], "l"); + _db.Unlock(); + + switch (mut) + { + case null: + return new SimpleString("OK"); + case "f": + return new SimpleString("OK"); + case "l": + return new SimpleError("Key is already locked"); + default: + return new SimpleError("Key is already set"); + } + } +} + +public class UnlockCommand : Command +{ + public UnlockCommand(Database db) : base(db) { } + + public override Item execute(params string[] args) + { + if (args.Length != 1) + return new SimpleError("Expected 1 argument"); + + _db.Lock(); + var mut = _db.Get(args[0]); + if (mut == "l") _db.Set(args[0], "f"); + _db.Unlock(); + + if (mut != "l" && mut != "f") + return new SimpleError("Key is not a lock"); + + return new SimpleString("OK"); + } } \ No newline at end of file