|
| 1 | +package cmd.set; |
| 2 | + |
| 3 | +import cmd.AbstractRedisCommand; |
| 4 | +import cmd.Command; |
| 5 | +import common.Attributes; |
| 6 | +import common.Constants; |
| 7 | +import core.Client; |
| 8 | +import core.Server; |
| 9 | +import db.Database; |
| 10 | +import io.netty.channel.ChannelHandlerContext; |
| 11 | +import object.HashObject; |
| 12 | +import object.ObjectType; |
| 13 | +import object.SetObject; |
| 14 | +import protocol.Arrays; |
| 15 | +import protocol.Integers; |
| 16 | +import protocol.Resp2; |
| 17 | +import protocol.Validates; |
| 18 | + |
| 19 | +import java.util.List; |
| 20 | + |
| 21 | +import static object.None.NONE; |
| 22 | + |
| 23 | +/** |
| 24 | + * @author: junjiexun |
| 25 | + * @date: 2020/10/16 10:41 上午 |
| 26 | + * @description: |
| 27 | + */ |
| 28 | +@SuppressWarnings("all") |
| 29 | +@Command(name = "sadd") |
| 30 | +public class SAdd extends AbstractRedisCommand<SAddArg> { |
| 31 | + @Override |
| 32 | + protected SAddArg createArg(Arrays arrays) { |
| 33 | + List<String> argList = arrays.map2String(true); |
| 34 | + return new SAddArg( |
| 35 | + argList.remove(0), |
| 36 | + argList.toArray(Constants.STR_EMPTY_ARRAY) |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + protected void validate(String commandName, Arrays arrays) { |
| 42 | + Validates.validateArraysSize(commandName, arrays, 3, null); |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + protected Resp2 doCommand0(SAddArg arg, ChannelHandlerContext ctx) { |
| 47 | + Client client = Attributes.getClient(ctx); |
| 48 | + Database database = Server.INSTANCE.getDb().getDatabase(client.getDb()); |
| 49 | + SetObject setObject = Validates.validateType(database.get(arg.getKey()), ObjectType.SET); |
| 50 | + if (setObject == null) { |
| 51 | + return Integers.ZERO; |
| 52 | + } |
| 53 | + int added = 0; |
| 54 | + for (String member : arg.getMembers()) { |
| 55 | + if (!setObject.getOriginal().containsKey(member)) { |
| 56 | + added++; |
| 57 | + } |
| 58 | + setObject.getOriginal().put(member, NONE); |
| 59 | + } |
| 60 | + return Integers.create(added); |
| 61 | + } |
| 62 | +} |
0 commit comments