Skip to content

Commit

Permalink
Merge pull request #16 from MattEstHaut/feature/lock-unlock
Browse files Browse the repository at this point in the history
Ajoute LOCK et UNLOCK
  • Loading branch information
MattEstHaut authored Jun 3, 2024
2 parents 0016504 + bf4f123 commit 7cc0855
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/Server/Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
}
Expand Down Expand Up @@ -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");
}
}

0 comments on commit 7cc0855

Please sign in to comment.