diff --git a/benchmark/BDN.benchmark/Cluster/ClusterContext.cs b/benchmark/BDN.benchmark/Cluster/ClusterContext.cs index c6a375ff5c..631a7dda90 100644 --- a/benchmark/BDN.benchmark/Cluster/ClusterContext.cs +++ b/benchmark/BDN.benchmark/Cluster/ClusterContext.cs @@ -49,8 +49,8 @@ public void AddSlotRange(List<(int, int)> slotRanges) foreach (var slotRange in slotRanges) { var clusterAddSlotsRange = Encoding.ASCII.GetBytes($"*4\r\n$7\r\nCLUSTER\r\n$13\r\nADDSLOTSRANGE\r\n" + - $"${NumUtils.NumDigits(slotRange.Item1)}\r\n{slotRange.Item1}\r\n" + - $"${NumUtils.NumDigits(slotRange.Item2)}\r\n{slotRange.Item2}\r\n"); + $"${NumUtils.CountDigits(slotRange.Item1)}\r\n{slotRange.Item1}\r\n" + + $"${NumUtils.CountDigits(slotRange.Item2)}\r\n{slotRange.Item2}\r\n"); fixed (byte* req = clusterAddSlotsRange) _ = session.TryConsumeMessages(req, clusterAddSlotsRange.Length); } @@ -68,27 +68,27 @@ public void CreateGetSet(int keySize = 8, int valueSize = 32, int batchSize = 10 benchUtils.RandomBytes(ref pairs[i].Item2); } - var setByteCount = batchSize * ("*2\r\n$3\r\nSET\r\n"u8.Length + 1 + NumUtils.NumDigits(keySize) + 2 + keySize + 2 + 1 + NumUtils.NumDigits(valueSize) + 2 + valueSize + 2); + var setByteCount = batchSize * ("*2\r\n$3\r\nSET\r\n"u8.Length + 1 + NumUtils.CountDigits(keySize) + 2 + keySize + 2 + 1 + NumUtils.CountDigits(valueSize) + 2 + valueSize + 2); var setReq = new Request(setByteCount); var curr = setReq.ptr; var end = curr + setReq.buffer.Length; for (var i = 0; i < batchSize; i++) { - _ = RespWriteUtils.WriteArrayLength(3, ref curr, end); - _ = RespWriteUtils.WriteBulkString("SET"u8, ref curr, end); - _ = RespWriteUtils.WriteBulkString(pairs[i].Item1, ref curr, end); - _ = RespWriteUtils.WriteBulkString(pairs[i].Item2, ref curr, end); + _ = RespWriteUtils.TryWriteArrayLength(3, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString("SET"u8, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(pairs[i].Item1, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(pairs[i].Item2, ref curr, end); } - var getByteCount = batchSize * ("*2\r\n$3\r\nGET\r\n"u8.Length + 1 + NumUtils.NumDigits(keySize) + 2 + keySize + 2); + var getByteCount = batchSize * ("*2\r\n$3\r\nGET\r\n"u8.Length + 1 + NumUtils.CountDigits(keySize) + 2 + keySize + 2); var getReq = new Request(getByteCount); curr = getReq.ptr; end = curr + getReq.buffer.Length; for (var i = 0; i < batchSize; i++) { - _ = RespWriteUtils.WriteArrayLength(2, ref curr, end); - _ = RespWriteUtils.WriteBulkString("GET"u8, ref curr, end); - _ = RespWriteUtils.WriteBulkString(pairs[i].Item1, ref curr, end); + _ = RespWriteUtils.TryWriteArrayLength(2, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString("GET"u8, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(pairs[i].Item1, ref curr, end); } singleGetSet = [getReq, setReq]; } @@ -105,31 +105,31 @@ public void CreateMGetMSet(int keySize = 8, int valueSize = 32, int batchSize = benchUtils.RandomBytes(ref pairs[i].Item2); } - var mGetHeaderSize = 1 + NumUtils.NumDigits(1 + batchSize) + 2 + "$4\r\nMGET\r\n"u8.Length; - var getRespSize = 1 + NumUtils.NumDigits(keySize) + 2 + keySize + 2; + var mGetHeaderSize = 1 + NumUtils.CountDigits(1 + batchSize) + 2 + "$4\r\nMGET\r\n"u8.Length; + var getRespSize = 1 + NumUtils.CountDigits(keySize) + 2 + keySize + 2; var mGetByteCount = mGetHeaderSize + (batchSize * getRespSize); var mGetReq = new Request(mGetByteCount); var curr = mGetReq.ptr; var end = curr + mGetReq.buffer.Length; - _ = RespWriteUtils.WriteArrayLength(1 + batchSize, ref curr, end); - _ = RespWriteUtils.WriteBulkString("MGET"u8, ref curr, end); + _ = RespWriteUtils.TryWriteArrayLength(1 + batchSize, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString("MGET"u8, ref curr, end); for (var i = 0; i < batchSize; i++) - _ = RespWriteUtils.WriteBulkString(pairs[i].Item1, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(pairs[i].Item1, ref curr, end); - var mSetHeaderSize = 1 + NumUtils.NumDigits(1 + (batchSize * 2)) + 2 + "$4\r\nMSET\r\n"u8.Length; - var setRespSize = 1 + NumUtils.NumDigits(keySize) + 2 + keySize + 2 + 1 + NumUtils.NumDigits(valueSize) + 2 + valueSize + 2; + var mSetHeaderSize = 1 + NumUtils.CountDigits(1 + (batchSize * 2)) + 2 + "$4\r\nMSET\r\n"u8.Length; + var setRespSize = 1 + NumUtils.CountDigits(keySize) + 2 + keySize + 2 + 1 + NumUtils.CountDigits(valueSize) + 2 + valueSize + 2; var mSetByteCount = mSetHeaderSize + (batchSize * setRespSize); var mSetReq = new Request(mSetByteCount); curr = mSetReq.ptr; end = curr + mSetReq.buffer.Length; - _ = RespWriteUtils.WriteArrayLength(1 + (batchSize * 2), ref curr, end); - _ = RespWriteUtils.WriteBulkString("MSET"u8, ref curr, end); + _ = RespWriteUtils.TryWriteArrayLength(1 + (batchSize * 2), ref curr, end); + _ = RespWriteUtils.TryWriteBulkString("MSET"u8, ref curr, end); for (var i = 0; i < batchSize; i++) { - _ = RespWriteUtils.WriteBulkString(pairs[i].Item1, ref curr, end); - _ = RespWriteUtils.WriteBulkString(pairs[i].Item2, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(pairs[i].Item1, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(pairs[i].Item2, ref curr, end); } singleMGetMSet = [mGetReq, mSetReq]; } @@ -145,18 +145,18 @@ public void CreateCTXNSET(int keySize = 8, int batchSize = 100) benchUtils.RandomBytes(ref keys[i], startOffset: keyTag.Length); } - var ctxnsetByteCount = "*9\r\n$7\r\nCTXNSET\r\n"u8.Length + (8 * (1 + NumUtils.NumDigits(keySize) + 2 + keySize + 2)); + var ctxnsetByteCount = "*9\r\n$7\r\nCTXNSET\r\n"u8.Length + (8 * (1 + NumUtils.CountDigits(keySize) + 2 + keySize + 2)); var ctxnsetReq = new Request(batchSize * ctxnsetByteCount); var curr = ctxnsetReq.ptr; var end = curr + ctxnsetReq.buffer.Length; for (var i = 0; i < batchSize; i++) { - _ = RespWriteUtils.WriteArrayLength(9, ref curr, end); - _ = RespWriteUtils.WriteBulkString("CTXNSET"u8, ref curr, end); + _ = RespWriteUtils.TryWriteArrayLength(9, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString("CTXNSET"u8, ref curr, end); for (var j = 0; j < 8; j++) { - _ = RespWriteUtils.WriteBulkString(keys[j], ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(keys[j], ref curr, end); } } diff --git a/benchmark/BDN.benchmark/Cluster/ClusterMigrate.cs b/benchmark/BDN.benchmark/Cluster/ClusterMigrate.cs index 2ac26470f5..532989937c 100644 --- a/benchmark/BDN.benchmark/Cluster/ClusterMigrate.cs +++ b/benchmark/BDN.benchmark/Cluster/ClusterMigrate.cs @@ -69,19 +69,19 @@ public void GlobalSetup() private void SetSlot(int slot, string state, string nodeId) { var reqBytes = "*5\r\n"u8.Length + 4 + "CLUSTER\r\n"u8.Length + 4 + "SETSLOT\r\n"u8.Length + - 1 + NumUtils.NumDigits(slot.ToString().Length) + 2 + slot.ToString().Length + 2 + - 1 + NumUtils.NumDigits(state.Length) + 2 + state.Length + 2 + - 1 + NumUtils.NumDigits(nodeId.Length) + 2 + nodeId.Length + 2; + 1 + NumUtils.CountDigits(slot.ToString().Length) + 2 + slot.ToString().Length + 2 + + 1 + NumUtils.CountDigits(state.Length) + 2 + state.Length + 2 + + 1 + NumUtils.CountDigits(nodeId.Length) + 2 + nodeId.Length + 2; var setSlotReq = new Request(reqBytes); var curr = setSlotReq.ptr; var end = curr + setSlotReq.buffer.Length; - _ = RespWriteUtils.WriteArrayLength(5, ref curr, end); - _ = RespWriteUtils.WriteBulkString("CLUSTER"u8, ref curr, end); - _ = RespWriteUtils.WriteBulkString("SETSLOT"u8, ref curr, end); - _ = RespWriteUtils.WriteIntegerAsBulkString(slot, ref curr, end); - _ = RespWriteUtils.WriteBulkString(Encoding.ASCII.GetBytes(state), ref curr, end); - _ = RespWriteUtils.WriteBulkString(Encoding.ASCII.GetBytes(nodeId), ref curr, end); + _ = RespWriteUtils.TryWriteArrayLength(5, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString("CLUSTER"u8, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString("SETSLOT"u8, ref curr, end); + _ = RespWriteUtils.TryWriteInt32AsBulkString(slot, ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(Encoding.ASCII.GetBytes(state), ref curr, end); + _ = RespWriteUtils.TryWriteBulkString(Encoding.ASCII.GetBytes(nodeId), ref curr, end); cc.Consume(setSlotReq.ptr, setSlotReq.buffer.Length); } diff --git a/benchmark/BDN.benchmark/Parsing/DoubleToResp.cs b/benchmark/BDN.benchmark/Parsing/DoubleToResp.cs index 2b14c1a759..1237621b2f 100644 --- a/benchmark/BDN.benchmark/Parsing/DoubleToResp.cs +++ b/benchmark/BDN.benchmark/Parsing/DoubleToResp.cs @@ -44,7 +44,7 @@ public bool WriteDoubleAsBulkString(double value) public bool WriteDoubleAsBulkStringByTranscoding(double value) { var startPtr = _bufferPtr; - return RespWriteUtils.WriteAsciiBulkString(value.ToString(CultureInfo.InvariantCulture), ref startPtr, _bufferPtr + _buffer.Length); + return RespWriteUtils.TryWriteAsciiBulkString(value.ToString(CultureInfo.InvariantCulture), ref startPtr, _bufferPtr + _buffer.Length); } public static double[] TestDoubles => [ diff --git a/benchmark/BDN.benchmark/Parsing/IntegerToResp.cs b/benchmark/BDN.benchmark/Parsing/IntegerToResp.cs index 5e9df56387..380fedb2f3 100644 --- a/benchmark/BDN.benchmark/Parsing/IntegerToResp.cs +++ b/benchmark/BDN.benchmark/Parsing/IntegerToResp.cs @@ -35,7 +35,7 @@ public void GlobalSetup() public bool WriteInt32(int value) { var startPtr = _bufferPtr; - return RespWriteUtils.WriteInteger(value, ref startPtr, _bufferPtr + _buffer.Length); + return RespWriteUtils.TryWriteInt32(value, ref startPtr, _bufferPtr + _buffer.Length); } [Benchmark] @@ -43,7 +43,7 @@ public bool WriteInt32(int value) public bool WriteInt64(long value) { var startPtr = _bufferPtr; - return RespWriteUtils.WriteInteger(value, ref startPtr, _bufferPtr + _buffer.Length); + return RespWriteUtils.TryWriteInt64(value, ref startPtr, _bufferPtr + _buffer.Length); } [Benchmark] @@ -51,7 +51,7 @@ public bool WriteInt64(long value) public bool WriteInt32AsBulkString(int value) { var startPtr = _bufferPtr; - return RespWriteUtils.WriteIntegerAsBulkString(value, ref startPtr, _bufferPtr + _buffer.Length); + return RespWriteUtils.TryWriteInt32AsBulkString(value, ref startPtr, _bufferPtr + _buffer.Length); } [Benchmark] @@ -60,7 +60,7 @@ public void WriteInt32_AllAsciiLengths() for (int i = 0; i < SignedInt32MultiplesOfTen.Length; i++) { var startPtr = _bufferPtr; - RespWriteUtils.WriteInteger(SignedInt32MultiplesOfTen[i], ref startPtr, _bufferPtr + _buffer.Length); + RespWriteUtils.TryWriteInt32(SignedInt32MultiplesOfTen[i], ref startPtr, _bufferPtr + _buffer.Length); } } @@ -70,7 +70,7 @@ public void WriteInt64_AllAsciiLengths() for (int i = 0; i < SignedInt64MultiplesOfTen.Length; i++) { var startPtr = _bufferPtr; - RespWriteUtils.WriteInteger(SignedInt64MultiplesOfTen[i], ref startPtr, _bufferPtr + _buffer.Length); + RespWriteUtils.TryWriteInt64(SignedInt64MultiplesOfTen[i], ref startPtr, _bufferPtr + _buffer.Length); } } @@ -80,7 +80,7 @@ public void WriteInt32BulkString_AllAsciiLengths() for (int i = 0; i < SignedInt32MultiplesOfTen.Length; i++) { var startPtr = _bufferPtr; - RespWriteUtils.WriteIntegerAsBulkString(SignedInt32MultiplesOfTen[i], ref startPtr, _bufferPtr + _buffer.Length); + RespWriteUtils.TryWriteInt32AsBulkString(SignedInt32MultiplesOfTen[i], ref startPtr, _bufferPtr + _buffer.Length); } } diff --git a/benchmark/BDN.benchmark/Parsing/RespToInteger.cs b/benchmark/BDN.benchmark/Parsing/RespToInteger.cs index 8df44ff123..1eb38ec411 100644 --- a/benchmark/BDN.benchmark/Parsing/RespToInteger.cs +++ b/benchmark/BDN.benchmark/Parsing/RespToInteger.cs @@ -20,7 +20,7 @@ public int ReadLengthHeader(AsciiTestCase testCase) fixed (byte* inputPtr = testCase.Bytes) { var start = inputPtr; - RespReadUtils.ReadSignedLengthHeader(out var value, ref start, start + testCase.Bytes.Length); + RespReadUtils.TryReadSignedLengthHeader(out var value, ref start, start + testCase.Bytes.Length); return value; } } @@ -32,7 +32,7 @@ public long ReadInt64(AsciiTestCase testCase) fixed (byte* inputPtr = testCase.Bytes) { var start = inputPtr; - RespReadUtils.Read64Int(out var value, ref start, start + testCase.Bytes.Length); + RespReadUtils.TryReadInt64(out var value, ref start, start + testCase.Bytes.Length); return value; } } @@ -44,7 +44,7 @@ public int ReadIntWithLengthHeader(AsciiTestCase testCase) fixed (byte* inputPtr = testCase.Bytes) { var start = inputPtr; - RespReadUtils.ReadIntWithLengthHeader(out var value, ref start, start + testCase.Bytes.Length); + RespReadUtils.TryReadInt32WithLengthHeader(out var value, ref start, start + testCase.Bytes.Length); return value; } } @@ -56,7 +56,7 @@ public long ReadLongWithLengthHeader(AsciiTestCase testCase) fixed (byte* inputPtr = testCase.Bytes) { var start = inputPtr; - RespReadUtils.ReadLongWithLengthHeader(out var value, ref start, start + testCase.Bytes.Length); + RespReadUtils.TryReadInt64WithLengthHeader(out var value, ref start, start + testCase.Bytes.Length); return value; } } @@ -68,7 +68,7 @@ public ulong ReadULongWithLengthHeader(AsciiTestCase testCase) fixed (byte* inputPtr = testCase.Bytes) { var start = inputPtr; - RespReadUtils.ReadULongWithLengthHeader(out var value, ref start, start + testCase.Bytes.Length); + RespReadUtils.TryReadUInt64WithLengthHeader(out var value, ref start, start + testCase.Bytes.Length); return value; } } diff --git a/benchmark/Resp.benchmark/ReqGen.cs b/benchmark/Resp.benchmark/ReqGen.cs index feb83b6fca..e7995d69c3 100644 --- a/benchmark/Resp.benchmark/ReqGen.cs +++ b/benchmark/Resp.benchmark/ReqGen.cs @@ -169,12 +169,12 @@ private void ProcessArgs(int i, byte[] buffer) fixed (byte* buf = buffer) { byte* ptr = buf; - RespReadUtils.ReadUnsignedArrayLength(out int count, ref ptr, buf + buffer.Length); - RespReadUtils.ReadStringWithLengthHeader(out var cmd, ref ptr, buf + buffer.Length); + RespReadUtils.TryReadUnsignedArrayLength(out int count, ref ptr, buf + buffer.Length); + RespReadUtils.TryReadStringWithLengthHeader(out var cmd, ref ptr, buf + buffer.Length); for (int j = 0; j < count - 1; j++) { - RespReadUtils.ReadStringWithLengthHeader(out var arg, ref ptr, buf + buffer.Length); + RespReadUtils.TryReadStringWithLengthHeader(out var arg, ref ptr, buf + buffer.Length); flatRequestBuffer[i].Add(arg); } } diff --git a/benchmark/Resp.benchmark/RespOnlineBench.cs b/benchmark/Resp.benchmark/RespOnlineBench.cs index c7813ca3cc..15102a458c 100644 --- a/benchmark/Resp.benchmark/RespOnlineBench.cs +++ b/benchmark/Resp.benchmark/RespOnlineBench.cs @@ -495,58 +495,58 @@ public unsafe void OpRunnerLightClient(int thread_id) break; case OpType.GET: var getCurr = getBuffer + 13; - RespWriteUtils.WriteAsciiBulkString(req.GenerateKey(), ref getCurr, getEnd); + RespWriteUtils.TryWriteAsciiBulkString(req.GenerateKey(), ref getCurr, getEnd); client.Send(getBuffer, (int)(getCurr - getBuffer), 1); client.CompletePendingRequests(); break; case OpType.SET: var setCurr = setBuffer + 13; - RespWriteUtils.WriteAsciiBulkString(req.GenerateKey(), ref setCurr, setEnd); - RespWriteUtils.WriteBulkString(req.GenerateValueBytes().Span, ref setCurr, setEnd); + RespWriteUtils.TryWriteAsciiBulkString(req.GenerateKey(), ref setCurr, setEnd); + RespWriteUtils.TryWriteBulkString(req.GenerateValueBytes().Span, ref setCurr, setEnd); client.Send(setBuffer, (int)(setCurr - setBuffer), 1); client.CompletePendingRequests(); break; case OpType.SETEX: var setexCurr = setexBuffer + 15; - RespWriteUtils.WriteAsciiBulkString(req.GenerateKey(), ref setexCurr, setexEnd); - RespWriteUtils.WriteIntegerAsBulkString(opts.Ttl, ref setexCurr, setexEnd); - RespWriteUtils.WriteBulkString(req.GenerateValueBytes().Span, ref setexCurr, setexEnd); + RespWriteUtils.TryWriteAsciiBulkString(req.GenerateKey(), ref setexCurr, setexEnd); + RespWriteUtils.TryWriteInt32AsBulkString(opts.Ttl, ref setexCurr, setexEnd); + RespWriteUtils.TryWriteBulkString(req.GenerateValueBytes().Span, ref setexCurr, setexEnd); client.Send(setexBuffer, (int)(setexCurr - setexBuffer), 1); client.CompletePendingRequests(); break; case OpType.DEL: var delCurr = delBuffer + 13; - RespWriteUtils.WriteAsciiBulkString(req.GenerateKey(), ref delCurr, delEnd); + RespWriteUtils.TryWriteAsciiBulkString(req.GenerateKey(), ref delCurr, delEnd); client.Send(delBuffer, (int)(delCurr - delBuffer), 1); client.CompletePendingRequests(); break; case OpType.ZADD: var zaddCurr = zaddBuffer + 14; - RespWriteUtils.WriteAsciiBulkString(sskey, ref zaddCurr, zaddEnd); - RespWriteUtils.WriteIntegerAsBulkString(1, ref zaddCurr, zaddEnd); - RespWriteUtils.WriteAsciiBulkString(req.GenerateKey(), ref zaddCurr, zaddEnd); + RespWriteUtils.TryWriteAsciiBulkString(sskey, ref zaddCurr, zaddEnd); + RespWriteUtils.TryWriteInt32AsBulkString(1, ref zaddCurr, zaddEnd); + RespWriteUtils.TryWriteAsciiBulkString(req.GenerateKey(), ref zaddCurr, zaddEnd); client.Send(zaddBuffer, (int)(zaddCurr - zaddBuffer), 1); if (opts.Ttl > 0) { // NOTE: Here we are not resetting opType. This only works for online bench var expireCurr = expireBuffer + 16; - RespWriteUtils.WriteAsciiBulkString(sskey, ref expireCurr, expireEnd); - RespWriteUtils.WriteIntegerAsBulkString(opts.Ttl, ref expireCurr, expireEnd); + RespWriteUtils.TryWriteAsciiBulkString(sskey, ref expireCurr, expireEnd); + RespWriteUtils.TryWriteInt32AsBulkString(opts.Ttl, ref expireCurr, expireEnd); client.Send(expireBuffer, (int)(expireCurr - expireBuffer), 1); } client.CompletePendingRequests(); break; case OpType.ZREM: var zremCurr = zremBuffer + 14; - RespWriteUtils.WriteAsciiBulkString(sskey, ref zremCurr, zremEnd); - RespWriteUtils.WriteIntegerAsBulkString(1, ref zremCurr, zremEnd); - RespWriteUtils.WriteAsciiBulkString(req.GenerateKey(), ref zremCurr, zremEnd); + RespWriteUtils.TryWriteAsciiBulkString(sskey, ref zremCurr, zremEnd); + RespWriteUtils.TryWriteInt32AsBulkString(1, ref zremCurr, zremEnd); + RespWriteUtils.TryWriteAsciiBulkString(req.GenerateKey(), ref zremCurr, zremEnd); client.Send(zremBuffer, (int)(zremCurr - zremBuffer), 1); client.CompletePendingRequests(); break; case OpType.ZCARD: var zcardCurr = zcardBuffer + 15; - RespWriteUtils.WriteAsciiBulkString(sskey, ref zcardCurr, zcardEnd); + RespWriteUtils.TryWriteAsciiBulkString(sskey, ref zcardCurr, zcardEnd); client.Send(zcardBuffer, (int)(zcardCurr - zcardEnd), 1); client.CompletePendingRequests(); break; diff --git a/benchmark/Resp.benchmark/RespPerfBench.cs b/benchmark/Resp.benchmark/RespPerfBench.cs index 74c535104a..6de8506fc5 100644 --- a/benchmark/Resp.benchmark/RespPerfBench.cs +++ b/benchmark/Resp.benchmark/RespPerfBench.cs @@ -96,7 +96,7 @@ private unsafe void GetDBSIZE(int loadDbThreads) fixed (byte* buf = client.ResponseBuffer) { byte* ptr = buf; - RespReadResponseUtils.ReadIntegerAsString(out dbSize, ref ptr, ptr + client.ResponseBuffer.Length); + RespReadResponseUtils.TryReadIntegerAsString(out dbSize, ref ptr, ptr + client.ResponseBuffer.Length); } } else diff --git a/libs/client/ClientSession/GarnetClientSession.cs b/libs/client/ClientSession/GarnetClientSession.cs index 92aa7951fc..6c76d77c02 100644 --- a/libs/client/ClientSession/GarnetClientSession.cs +++ b/libs/client/ClientSession/GarnetClientSession.cs @@ -114,7 +114,7 @@ public GarnetClientSession( this.usingManagedNetworkPool = networkPool != null; this.networkBufferSettings = networkBufferSettings; this.networkPool = networkPool ?? networkBufferSettings.CreateBufferPool(); - this.bufferSizeDigits = NumUtils.NumDigits(this.networkBufferSettings.sendBufferSize); + this.bufferSizeDigits = NumUtils.CountDigits(this.networkBufferSettings.sendBufferSize); this.logger = logger; this.sslOptions = tlsOptions; @@ -243,49 +243,49 @@ public void ExecuteClusterAppendLog(string nodeId, long previousAddress, long cu byte* curr = offset; int arraySize = 7; - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; } offset = curr; - while (!RespWriteUtils.WriteDirect(CLUSTER, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CLUSTER, ref curr, end)) { Flush(); curr = offset; } offset = curr; - while (!RespWriteUtils.WriteBulkString(appendLog, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(appendLog, ref curr, end)) { Flush(); curr = offset; } offset = curr; - while (!RespWriteUtils.WriteAsciiBulkString(nodeId, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(nodeId, ref curr, end)) { Flush(); curr = offset; } offset = curr; - while (!RespWriteUtils.WriteArrayItem(previousAddress, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(previousAddress, ref curr, end)) { Flush(); curr = offset; } offset = curr; - while (!RespWriteUtils.WriteArrayItem(currentAddress, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(currentAddress, ref curr, end)) { Flush(); curr = offset; } offset = curr; - while (!RespWriteUtils.WriteArrayItem(nextAddress, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(nextAddress, ref curr, end)) { Flush(); curr = offset; @@ -295,7 +295,7 @@ public void ExecuteClusterAppendLog(string nodeId, long previousAddress, long cu if (payloadLength > networkBufferSettings.sendBufferSize) throw new Exception($"Payload length {payloadLength} is larger than bufferSize {networkBufferSettings.sendBufferSize} bytes"); - while (!RespWriteUtils.WriteBulkString(new Span((void*)payloadPtr, payloadLength), ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(new Span((void*)payloadPtr, payloadLength), ref curr, end)) { Flush(); curr = offset; @@ -337,7 +337,7 @@ public void Wait() private void InternalExecute(params string[] command) { byte* curr = offset; - while (!RespWriteUtils.WriteArrayLength(command.Length, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(command.Length, ref curr, end)) { Flush(); curr = offset; @@ -346,7 +346,7 @@ private void InternalExecute(params string[] command) foreach (var cmd in command) { - while (!RespWriteUtils.WriteAsciiBulkString(cmd, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(cmd, ref curr, end)) { Flush(); curr = offset; @@ -375,28 +375,28 @@ private int ProcessReplies(byte* recvBufferPtr, int bytesRead) switch (*ptr) { case (byte)'+': - if (!RespReadResponseUtils.ReadSimpleString(out result, ref ptr, recvBufferPtr + bytesRead)) + if (!RespReadResponseUtils.TryReadSimpleString(out result, ref ptr, recvBufferPtr + bytesRead)) success = false; break; case (byte)':': - if (!RespReadResponseUtils.ReadIntegerAsString(out result, ref ptr, recvBufferPtr + bytesRead)) + if (!RespReadResponseUtils.TryReadIntegerAsString(out result, ref ptr, recvBufferPtr + bytesRead)) success = false; break; case (byte)'-': error = true; - if (!RespReadResponseUtils.ReadErrorAsString(out result, ref ptr, recvBufferPtr + bytesRead)) + if (!RespReadResponseUtils.TryReadErrorAsString(out result, ref ptr, recvBufferPtr + bytesRead)) success = false; break; case (byte)'$': - if (!RespReadResponseUtils.ReadStringWithLengthHeader(out result, ref ptr, recvBufferPtr + bytesRead)) + if (!RespReadResponseUtils.TryReadStringWithLengthHeader(out result, ref ptr, recvBufferPtr + bytesRead)) success = false; break; case (byte)'*': isArray = true; - if (!RespReadResponseUtils.ReadStringArrayWithLengthHeader(out resultArray, ref ptr, recvBufferPtr + bytesRead)) + if (!RespReadResponseUtils.TryReadStringArrayWithLengthHeader(out resultArray, ref ptr, recvBufferPtr + bytesRead)) success = false; break; diff --git a/libs/client/ClientSession/GarnetClientSessionClusterExtensions.cs b/libs/client/ClientSession/GarnetClientSessionClusterExtensions.cs index 9a1f63a577..0b64944783 100644 --- a/libs/client/ClientSession/GarnetClientSessionClusterExtensions.cs +++ b/libs/client/ClientSession/GarnetClientSessionClusterExtensions.cs @@ -30,7 +30,7 @@ public Task ExecuteGossip(Memory byteArray) byte* next = offset; int arraySize = 3; - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; @@ -38,7 +38,7 @@ public Task ExecuteGossip(Memory byteArray) offset = curr; //1 - while (!RespWriteUtils.WriteDirect(CLUSTER, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CLUSTER, ref curr, end)) { Flush(); curr = offset; @@ -46,7 +46,7 @@ public Task ExecuteGossip(Memory byteArray) offset = curr; //2 - while (!RespWriteUtils.WriteBulkString(GOSSIP, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(GOSSIP, ref curr, end)) { Flush(); curr = offset; @@ -54,7 +54,7 @@ public Task ExecuteGossip(Memory byteArray) offset = curr; //3 - while (!RespWriteUtils.WriteBulkString(byteArray.Span, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(byteArray.Span, ref curr, end)) { Flush(); curr = offset; diff --git a/libs/client/ClientSession/GarnetClientSessionMigrationExtensions.cs b/libs/client/ClientSession/GarnetClientSessionMigrationExtensions.cs index 90d51d83cd..d508fe25f9 100644 --- a/libs/client/ClientSession/GarnetClientSessionMigrationExtensions.cs +++ b/libs/client/ClientSession/GarnetClientSessionMigrationExtensions.cs @@ -43,7 +43,7 @@ public Task Authenticate(string username, string password) byte* curr = offset; int arraySize = username == null ? 2 : 3; - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; @@ -51,7 +51,7 @@ public Task Authenticate(string username, string password) offset = curr; //1 - while (!RespWriteUtils.WriteBulkString(AUTH, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(AUTH, ref curr, end)) { Flush(); curr = offset; @@ -61,7 +61,7 @@ public Task Authenticate(string username, string password) if (username != null) { //2 - while (!RespWriteUtils.WriteAsciiBulkString(username, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(username, ref curr, end)) { Flush(); curr = offset; @@ -70,7 +70,7 @@ public Task Authenticate(string username, string password) } //3 - while (!RespWriteUtils.WriteAsciiBulkString(password, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(password, ref curr, end)) { Flush(); curr = offset; @@ -101,7 +101,7 @@ public Task SetSlotRange(Memory state, string nodeid, List<(int, i //CLUSTER SETSLOTRANGE NODE [slot-start slot-end] //CLUSTER SETSLOTRANGE STABLE [slot-start slot-end] - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; @@ -109,7 +109,7 @@ public Task SetSlotRange(Memory state, string nodeid, List<(int, i offset = curr; //1 - while (!RespWriteUtils.WriteDirect(CLUSTER, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CLUSTER, ref curr, end)) { Flush(); curr = offset; @@ -117,7 +117,7 @@ public Task SetSlotRange(Memory state, string nodeid, List<(int, i offset = curr; //2 - while (!RespWriteUtils.WriteBulkString(SETSLOTSRANGE, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(SETSLOTSRANGE, ref curr, end)) { Flush(); curr = offset; @@ -125,7 +125,7 @@ public Task SetSlotRange(Memory state, string nodeid, List<(int, i offset = curr; //3 - while (!RespWriteUtils.WriteBulkString(state.Span, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(state.Span, ref curr, end)) { Flush(); curr = offset; @@ -135,7 +135,7 @@ public Task SetSlotRange(Memory state, string nodeid, List<(int, i if (nodeid != null) { //4 - while (!RespWriteUtils.WriteAsciiBulkString(nodeid, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(nodeid, ref curr, end)) { Flush(); curr = offset; @@ -146,14 +146,14 @@ public Task SetSlotRange(Memory state, string nodeid, List<(int, i //5+ foreach (var slotRange in slotRanges) { - while (!RespWriteUtils.WriteIntegerAsBulkString(slotRange.Item1, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32AsBulkString(slotRange.Item1, ref curr, end)) { Flush(); curr = offset; } offset = curr; - while (!RespWriteUtils.WriteIntegerAsBulkString(slotRange.Item2, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32AsBulkString(slotRange.Item2, ref curr, end)) { Flush(); curr = offset; @@ -216,7 +216,7 @@ public void SetClusterMigrate(string sourceNodeId, bool replace, bool isMainStor var arraySize = 6; - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; @@ -224,7 +224,7 @@ public void SetClusterMigrate(string sourceNodeId, bool replace, bool isMainStor offset = curr; // 1 - while (!RespWriteUtils.WriteDirect(CLUSTER, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CLUSTER, ref curr, end)) { Flush(); curr = offset; @@ -232,7 +232,7 @@ public void SetClusterMigrate(string sourceNodeId, bool replace, bool isMainStor offset = curr; // 2 - while (!RespWriteUtils.WriteBulkString(MIGRATE, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(MIGRATE, ref curr, end)) { Flush(); curr = offset; @@ -240,7 +240,7 @@ public void SetClusterMigrate(string sourceNodeId, bool replace, bool isMainStor offset = curr; // 3 - while (!RespWriteUtils.WriteAsciiBulkString(sourceNodeId, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(sourceNodeId, ref curr, end)) { Flush(); curr = offset; @@ -248,7 +248,7 @@ public void SetClusterMigrate(string sourceNodeId, bool replace, bool isMainStor offset = curr; // 4 - while (!RespWriteUtils.WriteBulkString(replaceOption, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(replaceOption, ref curr, end)) { Flush(); curr = offset; @@ -256,7 +256,7 @@ public void SetClusterMigrate(string sourceNodeId, bool replace, bool isMainStor offset = curr; // 5 - while (!RespWriteUtils.WriteBulkString(storeType, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(storeType, ref curr, end)) { Flush(); curr = offset; @@ -288,7 +288,7 @@ public Task SendAndResetMigrate() // Payload format = [$length\r\n][number of keys (4 bytes)][raw key value pairs]\r\n var size = (int)(curr - 2 - head - (ExtraSpace - 4)); TrackMigrateProgress(keyCount, size); - var success = RespWriteUtils.WritePaddedBulkStringLength(size, ExtraSpace - 4, ref head, end); + var success = RespWriteUtils.TryWritePaddedBulkStringLength(size, ExtraSpace - 4, ref head, end); Debug.Assert(success); // Number of key value pairs in payload @@ -325,7 +325,7 @@ public Task CompleteMigrate(string sourceNodeId, bool replace, bool isMa // Payload format = [$length\r\n][number of keys (4 bytes)][raw key value pairs]\r\n var size = (int)(curr - 2 - head - (ExtraSpace - 4)); TrackMigrateProgress(keyCount, size, completed: true); - var success = RespWriteUtils.WritePaddedBulkStringLength(size, ExtraSpace - 4, ref head, end); + var success = RespWriteUtils.TryWritePaddedBulkStringLength(size, ExtraSpace - 4, ref head, end); Debug.Assert(success); // Number of key value pairs in payload diff --git a/libs/client/ClientSession/GarnetClientSessionReplicationExtensions.cs b/libs/client/ClientSession/GarnetClientSessionReplicationExtensions.cs index 405a1be816..6e7b8a748c 100644 --- a/libs/client/ClientSession/GarnetClientSessionReplicationExtensions.cs +++ b/libs/client/ClientSession/GarnetClientSessionReplicationExtensions.cs @@ -36,7 +36,7 @@ public Task ExecuteReplicaSync(string nodeId, string primary_replid, byt byte* curr = offset; int arraySize = 7; - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; @@ -44,7 +44,7 @@ public Task ExecuteReplicaSync(string nodeId, string primary_replid, byt offset = curr; //1 - while (!RespWriteUtils.WriteDirect(CLUSTER, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CLUSTER, ref curr, end)) { Flush(); curr = offset; @@ -52,7 +52,7 @@ public Task ExecuteReplicaSync(string nodeId, string primary_replid, byt offset = curr; //2 - while (!RespWriteUtils.WriteBulkString(initiate_replica_sync, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(initiate_replica_sync, ref curr, end)) { Flush(); curr = offset; @@ -60,7 +60,7 @@ public Task ExecuteReplicaSync(string nodeId, string primary_replid, byt offset = curr; //3 - while (!RespWriteUtils.WriteAsciiBulkString(nodeId, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(nodeId, ref curr, end)) { Flush(); curr = offset; @@ -68,7 +68,7 @@ public Task ExecuteReplicaSync(string nodeId, string primary_replid, byt offset = curr; //4 - while (!RespWriteUtils.WriteAsciiBulkString(primary_replid, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(primary_replid, ref curr, end)) { Flush(); curr = offset; @@ -76,7 +76,7 @@ public Task ExecuteReplicaSync(string nodeId, string primary_replid, byt offset = curr; //5 - while (!RespWriteUtils.WriteBulkString(checkpointEntryData, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(checkpointEntryData, ref curr, end)) { Flush(); curr = offset; @@ -84,7 +84,7 @@ public Task ExecuteReplicaSync(string nodeId, string primary_replid, byt offset = curr; //6 - while (!RespWriteUtils.WriteArrayItem(aofBeginAddress, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(aofBeginAddress, ref curr, end)) { Flush(); curr = offset; @@ -92,7 +92,7 @@ public Task ExecuteReplicaSync(string nodeId, string primary_replid, byt offset = curr; //7 - while (!RespWriteUtils.WriteArrayItem(aofTailAddress, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(aofTailAddress, ref curr, end)) { Flush(); curr = offset; @@ -117,7 +117,7 @@ public Task ExecuteSendCkptMetadata(Memory fileTokenBytes, int fil byte* curr = offset; int arraySize = 5; - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; @@ -125,7 +125,7 @@ public Task ExecuteSendCkptMetadata(Memory fileTokenBytes, int fil offset = curr; //1 - while (!RespWriteUtils.WriteDirect(CLUSTER, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CLUSTER, ref curr, end)) { Flush(); curr = offset; @@ -133,7 +133,7 @@ public Task ExecuteSendCkptMetadata(Memory fileTokenBytes, int fil offset = curr; //2 - while (!RespWriteUtils.WriteBulkString(send_ckpt_metadata, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(send_ckpt_metadata, ref curr, end)) { Flush(); curr = offset; @@ -141,7 +141,7 @@ public Task ExecuteSendCkptMetadata(Memory fileTokenBytes, int fil offset = curr; //3 - while (!RespWriteUtils.WriteBulkString(fileTokenBytes.Span, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(fileTokenBytes.Span, ref curr, end)) { Flush(); curr = offset; @@ -149,7 +149,7 @@ public Task ExecuteSendCkptMetadata(Memory fileTokenBytes, int fil offset = curr; //4 - while (!RespWriteUtils.WriteArrayItem(fileType, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(fileType, ref curr, end)) { Flush(); curr = offset; @@ -157,7 +157,7 @@ public Task ExecuteSendCkptMetadata(Memory fileTokenBytes, int fil offset = curr; //5 - while (!RespWriteUtils.WriteBulkString(data.Span, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(data.Span, ref curr, end)) { Flush(); curr = offset; @@ -183,7 +183,7 @@ public Task ExecuteSendFileSegments(Memory fileTokenBytes, int fil byte* curr = offset; int arraySize = 7; - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; @@ -191,7 +191,7 @@ public Task ExecuteSendFileSegments(Memory fileTokenBytes, int fil offset = curr; //1 - while (!RespWriteUtils.WriteDirect(CLUSTER, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CLUSTER, ref curr, end)) { Flush(); curr = offset; @@ -199,7 +199,7 @@ public Task ExecuteSendFileSegments(Memory fileTokenBytes, int fil offset = curr; //2 - while (!RespWriteUtils.WriteBulkString(send_ckpt_file_segment, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(send_ckpt_file_segment, ref curr, end)) { Flush(); curr = offset; @@ -207,7 +207,7 @@ public Task ExecuteSendFileSegments(Memory fileTokenBytes, int fil offset = curr; //3 - while (!RespWriteUtils.WriteBulkString(fileTokenBytes.Span, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(fileTokenBytes.Span, ref curr, end)) { Flush(); curr = offset; @@ -215,7 +215,7 @@ public Task ExecuteSendFileSegments(Memory fileTokenBytes, int fil offset = curr; //4 - while (!RespWriteUtils.WriteArrayItem(fileType, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(fileType, ref curr, end)) { Flush(); curr = offset; @@ -223,7 +223,7 @@ public Task ExecuteSendFileSegments(Memory fileTokenBytes, int fil offset = curr; //5 - while (!RespWriteUtils.WriteArrayItem(startAddress, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(startAddress, ref curr, end)) { Flush(); curr = offset; @@ -231,7 +231,7 @@ public Task ExecuteSendFileSegments(Memory fileTokenBytes, int fil offset = curr; //6 - while (!RespWriteUtils.WriteBulkString(data, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(data, ref curr, end)) { Flush(); curr = offset; @@ -239,7 +239,7 @@ public Task ExecuteSendFileSegments(Memory fileTokenBytes, int fil offset = curr; //7 - while (!RespWriteUtils.WriteArrayItem(segmentId, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(segmentId, ref curr, end)) { Flush(); curr = offset; @@ -269,7 +269,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se byte* curr = offset; int arraySize = 9; - while (!RespWriteUtils.WriteArrayLength(arraySize, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end)) { Flush(); curr = offset; @@ -277,7 +277,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //1 - while (!RespWriteUtils.WriteDirect(CLUSTER, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CLUSTER, ref curr, end)) { Flush(); curr = offset; @@ -285,7 +285,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //2 - while (!RespWriteUtils.WriteBulkString(begin_replica_recover, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(begin_replica_recover, ref curr, end)) { Flush(); curr = offset; @@ -293,7 +293,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //3 - while (!RespWriteUtils.WriteBulkString(sendStoreCheckpoint ? "1"u8 : "0"u8, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(sendStoreCheckpoint ? "1"u8 : "0"u8, ref curr, end)) { Flush(); curr = offset; @@ -301,7 +301,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //4 - while (!RespWriteUtils.WriteBulkString(sendObjectStoreCheckpoint ? "1"u8 : "0"u8, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(sendObjectStoreCheckpoint ? "1"u8 : "0"u8, ref curr, end)) { Flush(); curr = offset; @@ -309,7 +309,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //5 - while (!RespWriteUtils.WriteBulkString(replayAOF ? "1"u8 : "0"u8, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(replayAOF ? "1"u8 : "0"u8, ref curr, end)) { Flush(); curr = offset; @@ -317,7 +317,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //6 - while (!RespWriteUtils.WriteAsciiBulkString(primary_replid, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(primary_replid, ref curr, end)) { Flush(); curr = offset; @@ -325,7 +325,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //7 - while (!RespWriteUtils.WriteBulkString(checkpointEntryData, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(checkpointEntryData, ref curr, end)) { Flush(); curr = offset; @@ -333,7 +333,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //8 - while (!RespWriteUtils.WriteArrayItem(beginAddress, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(beginAddress, ref curr, end)) { Flush(); curr = offset; @@ -341,7 +341,7 @@ public Task ExecuteBeginReplicaRecover(bool sendStoreCheckpoint, bool se offset = curr; //9 - while (!RespWriteUtils.WriteArrayItem(tailAddress, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayItem(tailAddress, ref curr, end)) { Flush(); curr = offset; diff --git a/libs/client/GarnetClient.cs b/libs/client/GarnetClient.cs index dcd976a7e6..6ee24e0406 100644 --- a/libs/client/GarnetClient.cs +++ b/libs/client/GarnetClient.cs @@ -529,17 +529,17 @@ async ValueTask InternalExecuteAsync(TcsWrapper tcs, Memory op, string par if (param1 != null) { int len = Encoding.UTF8.GetByteCount(param1); - totalLen += 1 + NumUtils.NumDigits(len) + 2 + len + 2; + totalLen += 1 + NumUtils.CountDigits(len) + 2 + len + 2; arraySize++; } if (param2 != null) { int len = Encoding.UTF8.GetByteCount(param2); - totalLen += 1 + NumUtils.NumDigits(len) + 2 + len + 2; + totalLen += 1 + NumUtils.CountDigits(len) + 2 + len + 2; arraySize++; } - totalLen += 1 + NumUtils.NumDigits(arraySize) + 2; + totalLen += 1 + NumUtils.CountDigits(arraySize) + 2; CheckLength(totalLen, tcs); await InputGateAsync(token); @@ -578,13 +578,13 @@ async ValueTask InternalExecuteAsync(TcsWrapper tcs, Memory op, string par { byte* curr = (byte*)networkWriter.GetPhysicalAddress(address); byte* end = curr + totalLen; - RespWriteUtils.WriteArrayLength(arraySize, ref curr, end); + RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end); - RespWriteUtils.WriteDirect(op.Span, ref curr, end); + RespWriteUtils.TryWriteDirect(op.Span, ref curr, end); if (param1 != null) - RespWriteUtils.WriteUtf8BulkString(param1, ref curr, end); + RespWriteUtils.TryWriteUtf8BulkString(param1, ref curr, end); if (param2 != null) - RespWriteUtils.WriteUtf8BulkString(param2, ref curr, end); + RespWriteUtils.TryWriteUtf8BulkString(param2, ref curr, end); Debug.Assert(curr == end); } @@ -641,26 +641,26 @@ async ValueTask InternalExecuteAsync(Memory op, Memory clusterOp, st totalLen += op.Length; int len = clusterOp.Length; - totalLen += 1 + NumUtils.NumDigits(len) + 2 + len + 2; + totalLen += 1 + NumUtils.CountDigits(len) + 2 + len + 2; arraySize++; len = Encoding.UTF8.GetByteCount(nodeId); - totalLen += 1 + NumUtils.NumDigits(len) + 2 + len + 2; + totalLen += 1 + NumUtils.CountDigits(len) + 2 + len + 2; arraySize++; - len = NumUtils.NumDigitsInLong(currentAddress); - totalLen += 1 + NumUtils.NumDigits(len) + 2 + len + 2; + len = NumUtils.CountDigits(currentAddress); + totalLen += 1 + NumUtils.CountDigits(len) + 2 + len + 2; arraySize++; - len = NumUtils.NumDigitsInLong(nextAddress); - totalLen += 1 + NumUtils.NumDigits(len) + 2 + len + 2; + len = NumUtils.CountDigits(nextAddress); + totalLen += 1 + NumUtils.CountDigits(len) + 2 + len + 2; arraySize++; len = payloadLength; - totalLen += 1 + NumUtils.NumDigits(len) + 2 + len + 2; + totalLen += 1 + NumUtils.CountDigits(len) + 2 + len + 2; arraySize++; - totalLen += 1 + NumUtils.NumDigits(arraySize) + 2; + totalLen += 1 + NumUtils.CountDigits(arraySize) + 2; if (totalLen > networkWriter.PageSize) { @@ -702,14 +702,14 @@ async ValueTask InternalExecuteAsync(Memory op, Memory clusterOp, st { byte* curr = (byte*)networkWriter.GetPhysicalAddress(address); byte* end = curr + totalLen; - RespWriteUtils.WriteArrayLength(arraySize, ref curr, end); + RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end); - RespWriteUtils.WriteDirect(op.Span, ref curr, end); - RespWriteUtils.WriteBulkString(clusterOp.Span, ref curr, end); - RespWriteUtils.WriteUtf8BulkString(nodeId, ref curr, end); - RespWriteUtils.WriteArrayItem(currentAddress, ref curr, end); - RespWriteUtils.WriteArrayItem(nextAddress, ref curr, end); - RespWriteUtils.WriteBulkString(new Span((void*)payloadPtr, payloadLength), ref curr, end); + RespWriteUtils.TryWriteDirect(op.Span, ref curr, end); + RespWriteUtils.TryWriteBulkString(clusterOp.Span, ref curr, end); + RespWriteUtils.TryWriteUtf8BulkString(nodeId, ref curr, end); + RespWriteUtils.TryWriteArrayItem(currentAddress, ref curr, end); + RespWriteUtils.TryWriteArrayItem(nextAddress, ref curr, end); + RespWriteUtils.TryWriteBulkString(new Span((void*)payloadPtr, payloadLength), ref curr, end); Debug.Assert(curr == end); } @@ -742,17 +742,17 @@ async ValueTask InternalExecuteAsync(TcsWrapper tcs, Memory op, Memory op, Memory respOp, IColle tcs.timestamp = GetTimestamp(); bool isArray = args != null; int arraySize = 1 + (isArray ? args.Count : 0); - int totalLen = 1 + NumUtils.NumDigits(arraySize) + 2 + respOp.Length; + int totalLen = 1 + NumUtils.CountDigits(arraySize) + 2 + respOp.Length; if (isArray) { foreach (var arg in args) { int len = arg.Length; - totalLen += 1 + NumUtils.NumDigits(len) + 2 + len + 2; + totalLen += 1 + NumUtils.CountDigits(len) + 2 + len + 2; } } @@ -1024,12 +1024,12 @@ async ValueTask InternalExecuteAsync(TcsWrapper tcs, Memory respOp, IColle { byte* curr = (byte*)networkWriter.GetPhysicalAddress(address); byte* end = curr + totalLen; - RespWriteUtils.WriteArrayLength(arraySize, ref curr, end); - RespWriteUtils.WriteDirect(respOp.Span, ref curr, end); + RespWriteUtils.TryWriteArrayLength(arraySize, ref curr, end); + RespWriteUtils.TryWriteDirect(respOp.Span, ref curr, end); if (isArray)//Write arg data { foreach (var arg in args) - RespWriteUtils.WriteBulkString(arg.Span, ref curr, end); + RespWriteUtils.TryWriteBulkString(arg.Span, ref curr, end); } Debug.Assert(curr == end); } diff --git a/libs/client/GarnetClientProcessReplies.cs b/libs/client/GarnetClientProcessReplies.cs index 9885c98b27..917057e0f9 100644 --- a/libs/client/GarnetClientProcessReplies.cs +++ b/libs/client/GarnetClientProcessReplies.cs @@ -31,27 +31,27 @@ unsafe bool ProcessReplyAsString(ref byte* ptr, byte* end, out string result, ou result = "OK"; break; } - if (!RespReadResponseUtils.ReadSimpleString(out result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadSimpleString(out result, ref ptr, end)) return false; break; case (byte)':': - if (!RespReadResponseUtils.ReadIntegerAsString(out result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadIntegerAsString(out result, ref ptr, end)) return false; break; case (byte)'-': - if (!RespReadResponseUtils.ReadErrorAsString(out error, ref ptr, end)) + if (!RespReadResponseUtils.TryReadErrorAsString(out error, ref ptr, end)) return false; break; case (byte)'$': - if (!RespReadResponseUtils.ReadStringWithLengthHeader(out result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadStringWithLengthHeader(out result, ref ptr, end)) return false; break; case (byte)'*': - if (!RespReadResponseUtils.ReadStringArrayWithLengthHeader(out var resultArray, ref ptr, end)) + if (!RespReadResponseUtils.TryReadStringArrayWithLengthHeader(out var resultArray, ref ptr, end)) return false; // Return first element of array if (resultArray != null) result = resultArray[0]; @@ -73,17 +73,17 @@ unsafe bool ProcessReplyAsNumber(ref byte* ptr, byte* end, out long number, out switch (*ptr) { case (byte)':': - if (!RespReadUtils.Read64Int(out number, ref ptr, end)) + if (!RespReadUtils.TryReadInt64(out number, ref ptr, end)) return false; break; case (byte)'-': - if (!RespReadResponseUtils.ReadErrorAsString(out error, ref ptr, end)) + if (!RespReadResponseUtils.TryReadErrorAsString(out error, ref ptr, end)) return false; break; case (byte)'$': - if (!RespReadResponseUtils.ReadIntWithLengthHeader(out var intWithLength, ref ptr, end)) + if (!RespReadResponseUtils.TryReadIntWithLengthHeader(out var intWithLength, ref ptr, end)) return false; number = intWithLength; break; @@ -110,29 +110,29 @@ unsafe bool ProcessReplyAsStringArray(ref byte* ptr, byte* end, out string[] res result = ["OK"]; break; } - if (!RespReadResponseUtils.ReadSimpleString(out var _result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadSimpleString(out var _result, ref ptr, end)) return false; result = [_result]; break; case (byte)':': - if (!RespReadResponseUtils.ReadIntegerAsString(out _result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadIntegerAsString(out _result, ref ptr, end)) return false; result = [_result]; break; case (byte)'-': - if (!RespReadResponseUtils.ReadErrorAsString(out error, ref ptr, end)) + if (!RespReadResponseUtils.TryReadErrorAsString(out error, ref ptr, end)) return false; break; case (byte)'$': - if (!RespReadResponseUtils.ReadStringWithLengthHeader(out _result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadStringWithLengthHeader(out _result, ref ptr, end)) return false; result = [_result]; break; case (byte)'*': - if (!RespReadResponseUtils.ReadStringArrayWithLengthHeader(out result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadStringArrayWithLengthHeader(out result, ref ptr, end)) return false; break; @@ -159,26 +159,26 @@ unsafe bool ProcessReplyAsMemoryByte(ref byte* ptr, byte* end, out MemoryResult< result = RESP_OK; break; } - if (!RespReadResponseUtils.ReadSimpleString(memoryPool, out result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadSimpleString(memoryPool, out result, ref ptr, end)) return false; break; case (byte)':': - if (!RespReadResponseUtils.ReadIntegerAsString(memoryPool, out result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadIntegerAsString(memoryPool, out result, ref ptr, end)) return false; break; case (byte)'-': - if (!RespReadResponseUtils.ReadErrorAsString(out error, ref ptr, end)) + if (!RespReadResponseUtils.TryReadErrorAsString(out error, ref ptr, end)) return false; break; case (byte)'$': - if (!RespReadResponseUtils.ReadStringWithLengthHeader(memoryPool, out result, ref ptr, end)) + if (!RespReadResponseUtils.TryReadStringWithLengthHeader(memoryPool, out result, ref ptr, end)) return false; break; case (byte)'*': - if (!RespReadResponseUtils.ReadStringArrayWithLengthHeader(memoryPool, out var resultArray, ref ptr, end)) + if (!RespReadResponseUtils.TryReadStringArrayWithLengthHeader(memoryPool, out var resultArray, ref ptr, end)) return false; // Return first element of array for (var i = 1; i < resultArray.Length; i++) @@ -201,7 +201,7 @@ unsafe bool ProcessReplyAsMemoryByteArray(ref byte* ptr, byte* end, out MemoryRe switch (*ptr) { case (byte)'*': - if (!RespReadResponseUtils.ReadStringArrayWithLengthHeader(memoryPool, out var resultArray, ref ptr, end)) + if (!RespReadResponseUtils.TryReadStringArrayWithLengthHeader(memoryPool, out var resultArray, ref ptr, end)) return false; result = resultArray; break; diff --git a/libs/client/RespReadResponseUtils.cs b/libs/client/RespReadResponseUtils.cs index bc2a46d664..f44f85097b 100644 --- a/libs/client/RespReadResponseUtils.cs +++ b/libs/client/RespReadResponseUtils.cs @@ -13,18 +13,16 @@ namespace Garnet.client { public static unsafe class RespReadResponseUtils { - /// - /// Read simple string - /// + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadSimpleString(out string result, ref byte* ptr, byte* end) - => RespReadUtils.ReadSimpleString(out result, ref ptr, end); + public static bool TryReadSimpleString(out string result, ref byte* ptr, byte* end) + => RespReadUtils.TryReadSimpleString(out result, ref ptr, end); /// /// Read simple string /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadSimpleString(MemoryPool pool, out MemoryResult result, ref byte* ptr, byte* end) + public static bool TryReadSimpleString(MemoryPool pool, out MemoryResult result, ref byte* ptr, byte* end) { result = default; if (ptr + 2 >= end) @@ -38,21 +36,19 @@ public static bool ReadSimpleString(MemoryPool pool, out MemoryResult - /// Read integer as string - /// + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadIntegerAsString(out string result, ref byte* ptr, byte* end) - => RespReadUtils.ReadIntegerAsString(out result, ref ptr, end); + public static bool TryReadIntegerAsString(out string result, ref byte* ptr, byte* end) + => RespReadUtils.TryReadIntegerAsString(out result, ref ptr, end); /// /// Read integer as string /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadIntegerAsString(MemoryPool pool, out MemoryResult result, ref byte* ptr, byte* end) + public static bool TryReadIntegerAsString(MemoryPool pool, out MemoryResult result, ref byte* ptr, byte* end) { result = default; if (ptr + 2 >= end) @@ -66,7 +62,7 @@ public static bool ReadIntegerAsString(MemoryPool pool, out MemoryResult @@ -78,13 +74,13 @@ public static bool ReadIntegerAsString(MemoryPool pool, out MemoryResult /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadStringWithLengthHeader(out string result, ref byte* ptr, byte* end) + public static bool TryReadStringWithLengthHeader(out string result, ref byte* ptr, byte* end) { result = null; byte* keyPtr = null; var length = 0; - if (!ReadPtrWithSignedLengthHeader(ref keyPtr, ref length, ref ptr, end)) + if (!TryReadPtrWithSignedLengthHeader(ref keyPtr, ref length, ref ptr, end)) return false; if (length < 0) @@ -103,13 +99,13 @@ public static bool ReadStringWithLengthHeader(out string result, ref byte* ptr, /// The current end of the RESP message. /// True if a RESP string was successfully read. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadStringWithLengthHeader(MemoryPool pool, out MemoryResult result, ref byte* ptr, byte* end) + public static bool TryReadStringWithLengthHeader(MemoryPool pool, out MemoryResult result, ref byte* ptr, byte* end) { result = default; byte* keyPtr = null; var length = 0; - if (!ReadPtrWithSignedLengthHeader(ref keyPtr, ref length, ref ptr, end)) + if (!TryReadPtrWithSignedLengthHeader(ref keyPtr, ref length, ref ptr, end)) return false; if (length < 0) @@ -121,10 +117,10 @@ public static bool ReadStringWithLengthHeader(MemoryPool pool, out MemoryR } [MethodImpl(MethodImplOptions.AggressiveInlining)] - static bool ReadPtrWithSignedLengthHeader(ref byte* keyPtr, ref int length, ref byte* ptr, byte* end) + static bool TryReadPtrWithSignedLengthHeader(ref byte* keyPtr, ref int length, ref byte* ptr, byte* end) { // Parse RESP string header - if (!RespReadUtils.ReadSignedLengthHeader(out length, ref ptr, end)) + if (!RespReadUtils.TryReadSignedLengthHeader(out length, ref ptr, end)) { return false; } @@ -154,23 +150,21 @@ static bool ReadPtrWithSignedLengthHeader(ref byte* keyPtr, ref int length, ref return true; } - /// - /// Read error as string - /// + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadErrorAsString(out string error, ref byte* ptr, byte* end) - => RespReadUtils.ReadErrorAsString(out error, ref ptr, end); + public static bool TryReadErrorAsString(out string error, ref byte* ptr, byte* end) + => RespReadUtils.TryReadErrorAsString(out error, ref ptr, end); /// /// Read string array with length header /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadStringArrayWithLengthHeader(out string[] result, ref byte* ptr, byte* end) + public static bool TryReadStringArrayWithLengthHeader(out string[] result, ref byte* ptr, byte* end) { result = null; // Parse RESP array header - if (!RespReadUtils.ReadSignedArrayLength(out var length, ref ptr, end)) + if (!RespReadUtils.TryReadSignedArrayLength(out var length, ref ptr, end)) { return false; } @@ -187,17 +181,17 @@ public static bool ReadStringArrayWithLengthHeader(out string[] result, ref byte { if (*ptr == '$') { - if (!ReadStringWithLengthHeader(out result[i], ref ptr, end)) + if (!TryReadStringWithLengthHeader(out result[i], ref ptr, end)) return false; } else if (*ptr == '+') { - if (!ReadSimpleString(out result[i], ref ptr, end)) + if (!TryReadSimpleString(out result[i], ref ptr, end)) return false; } else { - if (!ReadIntegerAsString(out result[i], ref ptr, end)) + if (!TryReadIntegerAsString(out result[i], ref ptr, end)) return false; } } @@ -209,11 +203,11 @@ public static bool ReadStringArrayWithLengthHeader(out string[] result, ref byte /// Read string array with length header /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadStringArrayWithLengthHeader(MemoryPool pool, out MemoryResult[] result, ref byte* ptr, byte* end) + public static bool TryReadStringArrayWithLengthHeader(MemoryPool pool, out MemoryResult[] result, ref byte* ptr, byte* end) { result = null; // Parse RESP array header - if (!RespReadUtils.ReadSignedArrayLength(out var length, ref ptr, end)) + if (!RespReadUtils.TryReadSignedArrayLength(out var length, ref ptr, end)) { return false; } @@ -230,17 +224,17 @@ public static bool ReadStringArrayWithLengthHeader(MemoryPool pool, out Me { if (*ptr == '$') { - if (!ReadStringWithLengthHeader(pool, out result[i], ref ptr, end)) + if (!TryReadStringWithLengthHeader(pool, out result[i], ref ptr, end)) return false; } else if (*ptr == '+') { - if (!ReadSimpleString(pool, out result[i], ref ptr, end)) + if (!TryReadSimpleString(pool, out result[i], ref ptr, end)) return false; } else { - if (!ReadIntegerAsString(pool, out result[i], ref ptr, end)) + if (!TryReadIntegerAsString(pool, out result[i], ref ptr, end)) return false; } } @@ -248,18 +242,16 @@ public static bool ReadStringArrayWithLengthHeader(MemoryPool pool, out Me return true; } - /// - /// Read int with length header - /// + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadIntWithLengthHeader(out int number, ref byte* ptr, byte* end) - => RespReadUtils.ReadIntWithLengthHeader(out number, ref ptr, end); + public static bool TryReadIntWithLengthHeader(out int number, ref byte* ptr, byte* end) + => RespReadUtils.TryReadInt32WithLengthHeader(out number, ref ptr, end); /// /// Read ASCII string without header until string terminator ('\r\n'). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadString(MemoryPool pool, out MemoryResult result, ref byte* ptr, byte* end) + public static bool TryReadString(MemoryPool pool, out MemoryResult result, ref byte* ptr, byte* end) { result = default; if (ptr + 1 >= end) diff --git a/libs/cluster/Session/ClusterSession.cs b/libs/cluster/Session/ClusterSession.cs index b4e863e273..40255ea30e 100644 --- a/libs/cluster/Session/ClusterSession.cs +++ b/libs/cluster/Session/ClusterSession.cs @@ -99,7 +99,7 @@ public void ProcessClusterCommands(RespCommand command, ref SessionParseState pa { var errorMessage = string.Format(CmdStrings.GenericErrWrongNumArgs, respCommandName ?? command.ToString()); - while (!RespWriteUtils.WriteError(errorMessage, ref this.dcurr, this.dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref this.dcurr, this.dend)) SendAndReset(); } } diff --git a/libs/cluster/Session/FailoverCommand.cs b/libs/cluster/Session/FailoverCommand.cs index abd3524772..5c80ae1846 100644 --- a/libs/cluster/Session/FailoverCommand.cs +++ b/libs/cluster/Session/FailoverCommand.cs @@ -24,7 +24,7 @@ private bool TryFAILOVER() if (!parseState.TryGetFailoverOption(currTokenIdx, out var failoverOption) || failoverOption == FailoverOption.DEFAULT || failoverOption == FailoverOption.INVALID) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; @@ -41,7 +41,7 @@ private bool TryFAILOVER() // 2. Port if (!parseState.TryGetInt(currTokenIdx++, out replicaPort)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -49,7 +49,7 @@ private bool TryFAILOVER() case FailoverOption.TIMEOUT: if (!parseState.TryGetInt(currTokenIdx++, out timeout)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -67,7 +67,7 @@ private bool TryFAILOVER() if (clusterProvider.clusterManager.CurrentConfig.LocalNodeRole != NodeRole.PRIMARY) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_CANNOT_FAILOVER_FROM_NON_MASTER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_CANNOT_FAILOVER_FROM_NON_MASTER, ref dcurr, dend)) SendAndReset(); return true; } @@ -78,7 +78,7 @@ private bool TryFAILOVER() var replicaNodeId = clusterProvider.clusterManager.CurrentConfig.GetWorkerNodeIdFromAddress(replicaAddress, replicaPort); if (replicaNodeId == null) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNKNOWN_ENDPOINT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNKNOWN_ENDPOINT, ref dcurr, dend)) SendAndReset(); return true; } @@ -86,14 +86,14 @@ private bool TryFAILOVER() var worker = clusterProvider.clusterManager.CurrentConfig.GetWorkerFromNodeId(replicaNodeId); if (worker.Role != NodeRole.REPLICA) { - while (!RespWriteUtils.WriteError($"ERR Node @{replicaAddress}:{replicaPort} is not a replica.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Node @{replicaAddress}:{replicaPort} is not a replica.", ref dcurr, dend)) SendAndReset(); return true; } if (worker.ReplicaOfNodeId != clusterProvider.clusterManager.CurrentConfig.LocalNodeId) { - while (!RespWriteUtils.WriteError($"ERR Node @{replicaAddress}:{replicaPort} is not my replica.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Node @{replicaAddress}:{replicaPort} is not my replica.", ref dcurr, dend)) SendAndReset(); return true; } @@ -111,7 +111,7 @@ private bool TryFAILOVER() _ = clusterProvider.failoverManager.TryStartPrimaryFailover(replicaAddress, replicaPort, force ? FailoverOption.FORCE : FailoverOption.DEFAULT, timeoutTimeSpan); } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } diff --git a/libs/cluster/Session/MigrateCommand.cs b/libs/cluster/Session/MigrateCommand.cs index f23e3d4e3c..62a7d48d12 100644 --- a/libs/cluster/Session/MigrateCommand.cs +++ b/libs/cluster/Session/MigrateCommand.cs @@ -52,7 +52,7 @@ private bool HandleCommandParsingErrors(MigrateCmdParseState mpState, string tar MigrateCmdParseState.FAILEDTOADDKEY => CmdStrings.RESP_ERR_GENERIC_FAILEDTOADDKEY, _ => CmdStrings.RESP_ERR_GENERIC_PARSING, }; - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return false; } @@ -84,7 +84,7 @@ private bool TryMIGRATE(out bool invalidParameters) !parseState.TryGetInt(4, out var timeout)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -195,7 +195,7 @@ private bool TryMIGRATE(out bool invalidParameters) { if (!parseState.TryGetInt(currTokenIdx++, out var slot)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -245,7 +245,7 @@ private bool TryMIGRATE(out bool invalidParameters) if (!parseState.TryGetInt(currTokenIdx++, out var slotStart) || !parseState.TryGetInt(currTokenIdx++, out var slotEnd)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -314,7 +314,7 @@ private bool TryMIGRATE(out bool invalidParameters) out var mSession)) { // Migration task could not be added due to possible conflicting migration tasks - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_IOERR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_IOERR, ref dcurr, dend)) SendAndReset(); } else @@ -322,12 +322,12 @@ private bool TryMIGRATE(out bool invalidParameters) //Start migration task if (!mSession.TryStartMigrationTask(out var errorMessage)) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } } diff --git a/libs/cluster/Session/ReplicaOfCommand.cs b/libs/cluster/Session/ReplicaOfCommand.cs index 0e2a00eef7..d654f3bd8b 100644 --- a/libs/cluster/Session/ReplicaOfCommand.cs +++ b/libs/cluster/Session/ReplicaOfCommand.cs @@ -33,7 +33,7 @@ private bool TryREPLICAOF(out bool invalidParameters) if (!clusterProvider.replicationManager.StartRecovery()) { logger?.LogError($"{nameof(TryREPLICAOF)}: {{logMessage}}", Encoding.ASCII.GetString(CmdStrings.RESP_ERR_GENERIC_CANNOT_ACQUIRE_RECOVERY_LOCK)); - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_CANNOT_ACQUIRE_RECOVERY_LOCK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_CANNOT_ACQUIRE_RECOVERY_LOCK, ref dcurr, dend)) SendAndReset(); return true; } @@ -53,7 +53,7 @@ private bool TryREPLICAOF(out bool invalidParameters) { var portStr = Encoding.ASCII.GetString(portSpan); logger?.LogWarning($"{nameof(TryREPLICAOF)} failed to parse port {{port}}", portStr); - while (!RespWriteUtils.WriteError($"ERR REPLICAOF failed to parse port '{portStr}'", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR REPLICAOF failed to parse port '{portStr}'", ref dcurr, dend)) SendAndReset(); return true; } @@ -62,25 +62,25 @@ private bool TryREPLICAOF(out bool invalidParameters) var primaryId = clusterProvider.clusterManager.CurrentConfig.GetWorkerNodeIdFromAddress(addressStr, port); if (primaryId == null) { - while (!RespWriteUtils.WriteError($"ERR I don't know about node {addressStr}:{port}.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR I don't know about node {addressStr}:{port}.", ref dcurr, dend)) SendAndReset(); return true; } if (!clusterProvider.replicationManager.TryBeginReplicate(this, primaryId, background: false, force: true, out var errorMessage)) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } return true; } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/cluster/Session/RespClusterBasicCommands.cs b/libs/cluster/Session/RespClusterBasicCommands.cs index c364543d8c..16b5683b70 100644 --- a/libs/cluster/Session/RespClusterBasicCommands.cs +++ b/libs/cluster/Session/RespClusterBasicCommands.cs @@ -32,12 +32,12 @@ private bool NetworkClusterBumpEpoch(out bool invalidParameters) // Process BUMPEPOCH if (clusterProvider.clusterManager.TryBumpClusterEpoch()) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_CONFIG_UPDATE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_CONFIG_UPDATE, ref dcurr, dend)) SendAndReset(); } return true; @@ -68,7 +68,7 @@ private bool NetworkClusterForget(out bool invalidParameters) // [Optional] Parse expiry in seconds if (!parseState.TryGetInt(1, out expirySeconds)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -77,14 +77,14 @@ private bool NetworkClusterForget(out bool invalidParameters) logger?.LogTrace("CLUSTER FORGET {nodeid} {seconds}", nodeId, expirySeconds); if (!clusterProvider.clusterManager.TryRemoveWorker(nodeId, expirySeconds, out var errorMessage)) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } else { // Terminate any outstanding migration tasks _ = clusterProvider.migrationManager.TryRemoveMigrationTask(nodeId); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -108,7 +108,7 @@ private bool NetworkClusterInfo(out bool invalidParameters) } var clusterInfo = clusterProvider.clusterManager.GetInfo(); - while (!RespWriteUtils.WriteAsciiBulkString(clusterInfo, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(clusterInfo, ref dcurr, dend)) SendAndReset(); return true; @@ -131,11 +131,11 @@ private bool NetworkClusterHelp(out bool invalidParameters) } var clusterCommands = ClusterCommandInfo.GetClusterCommands(); - while (!RespWriteUtils.WriteArrayLength(clusterCommands.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(clusterCommands.Count, ref dcurr, dend)) SendAndReset(); foreach (var command in clusterCommands) { - while (!RespWriteUtils.WriteSimpleString(command, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString(command, ref dcurr, dend)) SendAndReset(); } @@ -161,7 +161,7 @@ private bool NetworkClusterMeet(out bool invalidParameters) var ipAddress = parseState.GetString(0); if (!parseState.TryGetInt(1, out var port)) { - while (!RespWriteUtils.WriteError( + while (!RespWriteUtils.TryWriteError( Encoding.ASCII.GetBytes(string.Format(CmdStrings.GenericErrInvalidPort, parseState.GetString(1))), ref dcurr, dend)) SendAndReset(); @@ -170,7 +170,7 @@ private bool NetworkClusterMeet(out bool invalidParameters) logger?.LogTrace("CLUSTER MEET {ipaddressStr} {port}", ipAddress, port); clusterProvider.clusterManager.RunMeetTask(ipAddress, port); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -192,7 +192,7 @@ private bool NetworkClusterMyId(out bool invalidParameters) return true; } - while (!RespWriteUtils.WriteAsciiBulkString(clusterProvider.clusterManager.CurrentConfig.LocalNodeId, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(clusterProvider.clusterManager.CurrentConfig.LocalNodeId, ref dcurr, dend)) SendAndReset(); return true; @@ -216,7 +216,7 @@ private bool NetworkClusterMyParentId(out bool invalidParameters) var current = clusterProvider.clusterManager.CurrentConfig; var parentId = current.LocalNodeRole == NodeRole.PRIMARY ? current.LocalNodeId : current.LocalNodePrimaryId; - while (!RespWriteUtils.WriteAsciiBulkString(parentId, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(parentId, ref dcurr, dend)) SendAndReset(); return true; @@ -242,7 +242,7 @@ private bool NetworkClusterEndpoint(out bool invalidParameters) var current = clusterProvider.clusterManager.CurrentConfig; var (host, port) = current.GetEndpointFromNodeId(nodeId); - while (!RespWriteUtils.WriteAsciiBulkString($"{host}:{port}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString($"{host}:{port}", ref dcurr, dend)) SendAndReset(); return true; } @@ -264,7 +264,7 @@ private bool NetworkClusterNodes(out bool invalidParameters) } var nodes = clusterProvider.clusterManager.CurrentConfig.GetClusterInfo(clusterProvider); - while (!RespWriteUtils.WriteAsciiBulkString(nodes, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(nodes, ref dcurr, dend)) SendAndReset(); return true; @@ -288,26 +288,26 @@ private bool NetworkClusterSetConfigEpoch(out bool invalidParameters) if (!parseState.TryGetLong(0, out var configEpoch)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } if (clusterProvider.clusterManager.CurrentConfig.NumWorkers > 2) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_CONFIG_EPOCH_ASSIGNMENT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_CONFIG_EPOCH_ASSIGNMENT, ref dcurr, dend)) SendAndReset(); } else { if (!clusterProvider.clusterManager.TrySetLocalConfigEpoch(configEpoch, out var errorMessage)) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } } @@ -332,7 +332,7 @@ private bool NetworkClusterShards(out bool invalidParameters) } var shardsInfo = clusterProvider.clusterManager.CurrentConfig.GetShardsInfo(); - while (!RespWriteUtils.WriteAsciiDirect(shardsInfo, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiDirect(shardsInfo, ref dcurr, dend)) SendAndReset(); return true; @@ -394,13 +394,13 @@ private bool NetworkClusterGossip(out bool invalidParameters) { var configByteArray = current.ToByteArray(); clusterProvider.clusterManager.gossipStats.UpdateGossipBytesSend(configByteArray.Length); - while (!RespWriteUtils.WriteBulkString(configByteArray, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(configByteArray, ref dcurr, dend)) SendAndReset(); lastSentConfig = current; } else { - while (!RespWriteUtils.WriteBulkString([], ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString([], ref dcurr, dend)) SendAndReset(); } @@ -436,7 +436,7 @@ private bool NetworkClusterReset(out bool invalidParameters) { if (!parseState.TryGetInt(1, out expirySeconds)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -445,7 +445,7 @@ private bool NetworkClusterReset(out bool invalidParameters) var resp = clusterProvider.clusterManager.TryReset(soft, expirySeconds); if (!soft) clusterProvider.FlushDB(true); - while (!RespWriteUtils.WriteDirect(resp, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(resp, ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/cluster/Session/RespClusterFailoverCommands.cs b/libs/cluster/Session/RespClusterFailoverCommands.cs index c4d2b32aef..f7c14e5849 100644 --- a/libs/cluster/Session/RespClusterFailoverCommands.cs +++ b/libs/cluster/Session/RespClusterFailoverCommands.cs @@ -36,7 +36,7 @@ private bool NetworkClusterFailover(out bool invalidParameters) var failoverOptionStr = parseState.GetString(0); // On failure set the invalid flag, write error and continue parsing to drain rest of parameters if any - while (!RespWriteUtils.WriteError($"ERR Failover option ({failoverOptionStr}) not supported", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Failover option ({failoverOptionStr}) not supported", ref dcurr, dend)) SendAndReset(); return true; @@ -46,7 +46,7 @@ private bool NetworkClusterFailover(out bool invalidParameters) { if (!parseState.TryGetInt(1, out var failoverTimeoutSeconds)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -68,14 +68,14 @@ private bool NetworkClusterFailover(out bool invalidParameters) { if (!clusterProvider.failoverManager.TryStartReplicaFailover(failoverOption, failoverTimeout)) { - while (!RespWriteUtils.WriteError($"ERR failed to start failover for primary({current.GetLocalNodePrimaryAddress()})", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR failed to start failover for primary({current.GetLocalNodePrimaryAddress()})", ref dcurr, dend)) SendAndReset(); return true; } } else { - while (!RespWriteUtils.WriteError($"ERR Node is not configured as a {NodeRole.REPLICA}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Node is not configured as a {NodeRole.REPLICA}", ref dcurr, dend)) SendAndReset(); return true; } @@ -84,13 +84,13 @@ private bool NetworkClusterFailover(out bool invalidParameters) else { // Return error if AOF is not enabled - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_REPLICATION_AOF_TURNEDOFF, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_REPLICATION_AOF_TURNEDOFF, ref dcurr, dend)) SendAndReset(); return true; } // Finally return +OK if operation completed without any errors - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -123,7 +123,7 @@ private bool NetworkClusterFailStopWrites(out bool invalidParameters) clusterProvider.clusterManager.TryResetReplica(); } UnsafeBumpAndWaitForEpochTransition(); - while (!RespWriteUtils.WriteInteger(clusterProvider.replicationManager.ReplicationOffset, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt64(clusterProvider.replicationManager.ReplicationOffset, ref dcurr, dend)) SendAndReset(); return true; } @@ -146,13 +146,13 @@ private bool NetworkClusterFailReplicationOffset(out bool invalidParameters) if (!parseState.TryGetLong(0, out var primaryReplicationOffset)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } var rOffset = clusterProvider.replicationManager.WaitForReplicationOffset(primaryReplicationOffset).GetAwaiter().GetResult(); - while (!RespWriteUtils.WriteInteger(rOffset, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt64(rOffset, ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/cluster/Session/RespClusterMigrateCommands.cs b/libs/cluster/Session/RespClusterMigrateCommands.cs index f32ab24731..b50a23cb29 100644 --- a/libs/cluster/Session/RespClusterMigrateCommands.cs +++ b/libs/cluster/Session/RespClusterMigrateCommands.cs @@ -106,7 +106,7 @@ private bool NetworkClusterMigrate(out bool invalidParameters) TrackImportProgress(keyCount, isMainStore: true, keyCount == 0); while (i < keyCount) { - if (!RespReadUtils.ReadSerializedData(out var key, out var data, out var expiration, ref payloadPtr, payloadEndPtr)) + if (!RespReadUtils.TryReadSerializedData(out var key, out var data, out var expiration, ref payloadPtr, payloadEndPtr)) return false; // An error has occurred @@ -138,12 +138,12 @@ private bool NetworkClusterMigrate(out bool invalidParameters) if (migrateState == 1) { logger?.LogError("{errorMsg}", Encoding.ASCII.GetString(CmdStrings.RESP_ERR_GENERIC_NOT_IN_IMPORTING_STATE)); - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_NOT_IN_IMPORTING_STATE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_NOT_IN_IMPORTING_STATE, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -166,7 +166,7 @@ private bool NetworkClusterMTasks(out bool invalidParameters) } var mtasks = clusterProvider.migrationManager.GetMigrationTaskCount(); - while (!RespWriteUtils.WriteInteger(mtasks, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(mtasks, ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/cluster/Session/RespClusterReplicationCommands.cs b/libs/cluster/Session/RespClusterReplicationCommands.cs index 7fd9d416a2..f61328fe5a 100644 --- a/libs/cluster/Session/RespClusterReplicationCommands.cs +++ b/libs/cluster/Session/RespClusterReplicationCommands.cs @@ -30,12 +30,12 @@ private bool NetworkClusterReplicas(out bool invalidParameters) var nodeId = parseState.GetString(0); var replicas = clusterProvider.clusterManager.ListReplicas(nodeId, clusterProvider); - while (!RespWriteUtils.WriteArrayLength(replicas.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(replicas.Count, ref dcurr, dend)) SendAndReset(); foreach (var replica in replicas) { - while (!RespWriteUtils.WriteAsciiBulkString(replica, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(replica, ref dcurr, dend)) SendAndReset(); } @@ -71,7 +71,7 @@ private bool NetworkClusterReplicate(out bool invalidParameters) background = true; else { - while (!RespWriteUtils.WriteError( + while (!RespWriteUtils.TryWriteError( $"ERR Invalid CLUSTER REPLICATE FLAG ({Encoding.ASCII.GetString(backgroundFlagSpan)}) not valid", ref dcurr, dend)) SendAndReset(); @@ -81,19 +81,19 @@ private bool NetworkClusterReplicate(out bool invalidParameters) if (!clusterProvider.serverOptions.EnableAOF) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_REPLICATION_AOF_TURNEDOFF, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_REPLICATION_AOF_TURNEDOFF, ref dcurr, dend)) SendAndReset(); } else { if (!clusterProvider.replicationManager.TryBeginReplicate(this, nodeId, background: background, force: false, out var errorMessage)) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } } @@ -120,7 +120,7 @@ private bool NetworkClusterAOFSync(out bool invalidParameters) if (!parseState.TryGetLong(1, out var nextAddress)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -130,18 +130,18 @@ private bool NetworkClusterAOFSync(out bool invalidParameters) clusterProvider.replicationManager.TryAddReplicationTask(nodeId, nextAddress, out var aofSyncTaskInfo); if (!clusterProvider.replicationManager.TryConnectToReplica(nodeId, nextAddress, aofSyncTaskInfo, out var errorMessage)) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_REPLICATION_AOF_TURNEDOFF, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_REPLICATION_AOF_TURNEDOFF, ref dcurr, dend)) SendAndReset(); } @@ -219,7 +219,7 @@ private bool NetworkClusterInitiateReplicaSync(out bool invalidParameters) if (!parseState.TryGetLong(3, out var replicaAofBeginAddress) || !parseState.TryGetLong(4, out var replicaAofTailAddress)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -229,12 +229,12 @@ private bool NetworkClusterInitiateReplicaSync(out bool invalidParameters) if (!clusterProvider.replicationManager.TryBeginReplicaSyncSession( nodeId, primaryReplicaId, remoteEntry, replicaAofBeginAddress, replicaAofTailAddress, out var errorMessage)) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -261,7 +261,7 @@ private bool NetworkClusterSendCheckpointMetadata(out bool invalidParameters) if (!parseState.TryGetInt(1, out var fileTypeInt)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -271,7 +271,7 @@ private bool NetworkClusterSendCheckpointMetadata(out bool invalidParameters) var fileToken = new Guid(fileTokenBytes); var fileType = (CheckpointFileType)fileTypeInt; clusterProvider.replicationManager.ProcessCheckpointMetadata(fileToken, fileType, checkpointMetadata); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -298,7 +298,7 @@ private bool NetworkClusterSendCheckpointFileSegment(out bool invalidParameters) !parseState.TryGetLong(2, out var startAddress) || !parseState.TryGetInt(4, out var segmentId)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -311,7 +311,7 @@ private bool NetworkClusterSendCheckpointFileSegment(out bool invalidParameters) // Commenting due to high verbosity // logger?.LogTrace("send_ckpt_file_segment {fileToken} {ckptFileType} {startAddress} {dataLength}", fileToken, ckptFileType, startAddress, data.Length); clusterProvider.replicationManager.recvCheckpointHandler.ProcessFileSegments(segmentId, fileToken, ckptFileType, startAddress, data); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -337,7 +337,7 @@ private bool NetworkClusterBeginReplicaRecover(out bool invalidParameters) !parseState.TryGetBool(1, out var recoverObjectStoreFromToken) || !parseState.TryGetBool(2, out var replayAOF)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_BOOLEAN, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_BOOLEAN, ref dcurr, dend)) SendAndReset(); return true; } @@ -348,7 +348,7 @@ private bool NetworkClusterBeginReplicaRecover(out bool invalidParameters) if (!parseState.TryGetLong(5, out var beginAddress) || !parseState.TryGetLong(6, out var tailAddress)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -362,7 +362,7 @@ private bool NetworkClusterBeginReplicaRecover(out bool invalidParameters) entry, beginAddress, tailAddress); - while (!RespWriteUtils.WriteInteger(replicationOffset, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt64(replicationOffset, ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/cluster/Session/RespClusterSlotManagementCommands.cs b/libs/cluster/Session/RespClusterSlotManagementCommands.cs index 137ce3e48c..9786825182 100644 --- a/libs/cluster/Session/RespClusterSlotManagementCommands.cs +++ b/libs/cluster/Session/RespClusterSlotManagementCommands.cs @@ -34,7 +34,7 @@ private bool NetworkClusterAddSlots(out bool invalidParameters) // The slot parsing may give errorMessage even if the methods TryParseSlots true. if (!slotsParsed) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; } @@ -42,12 +42,12 @@ private bool NetworkClusterAddSlots(out bool invalidParameters) // Try to to add slots if (!clusterProvider.clusterManager.TryAddSlots(slots, out var slotIndex) && slotIndex != -1) { - while (!RespWriteUtils.WriteError($"ERR Slot {slotIndex} is already busy", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Slot {slotIndex} is already busy", ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -76,7 +76,7 @@ private bool NetworkClusterAddSlotsRange(out bool invalidParameters) //The slot parsing may give errorMessage even if the TryParseSlots returns true. if (!slotsParsed) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; } @@ -84,12 +84,12 @@ private bool NetworkClusterAddSlotsRange(out bool invalidParameters) // Try to to add slots if (!clusterProvider.clusterManager.TryAddSlots(slots, out var slotIndex) && slotIndex != -1) { - while (!RespWriteUtils.WriteError($"ERR Slot {slotIndex} is already busy", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Slot {slotIndex} is already busy", ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -114,11 +114,11 @@ private bool NetworkClusterBanList(out bool invalidParameters) var banlist = clusterProvider.clusterManager.GetBanList(); - while (!RespWriteUtils.WriteArrayLength(banlist.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(banlist.Count, ref dcurr, dend)) SendAndReset(); foreach (var replica in banlist) { - while (!RespWriteUtils.WriteAsciiBulkString(replica, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(replica, ref dcurr, dend)) SendAndReset(); } @@ -144,14 +144,14 @@ private bool NetworkClusterCountKeysInSlot(out bool invalidParameters) var current = clusterProvider.clusterManager.CurrentConfig; if (!parseState.TryGetInt(0, out var slot)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) SendAndReset(); return true; } if (ClusterConfig.OutOfRange(slot)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_SLOT_OUT_OFF_RANGE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_SLOT_OUT_OFF_RANGE, ref dcurr, dend)) SendAndReset(); return true; } @@ -165,13 +165,13 @@ private bool NetworkClusterCountKeysInSlot(out bool invalidParameters) try { var keyCount = CountKeysInSlot(slot); - while (!RespWriteUtils.WriteInteger(keyCount, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(keyCount, ref dcurr, dend)) SendAndReset(); } catch (Exception ex) { logger?.LogError(ex, "Critical error in count keys"); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_N1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_N1, ref dcurr, dend)) SendAndReset(); } } @@ -201,7 +201,7 @@ private bool NetworkClusterDelSlots(out bool invalidParameters) //The slot parsing may give errorMessage even if the TryParseSlots returns true. if (!slotsParsed) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; } @@ -209,12 +209,12 @@ private bool NetworkClusterDelSlots(out bool invalidParameters) //Try remove the slots if (!clusterProvider.clusterManager.TryRemoveSlots(slots, out var slotIndex) && slotIndex != -1) { - while (!RespWriteUtils.WriteError($"ERR Slot {slotIndex} is not assigned", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Slot {slotIndex} is not assigned", ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -243,7 +243,7 @@ private bool NetworkClusterDelSlotsRange(out bool invalidParameters) //The slot parsing may give errorMessage even if the TryParseSlots returns true. if (!slotsParsed) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; } @@ -251,12 +251,12 @@ private bool NetworkClusterDelSlotsRange(out bool invalidParameters) //Try remove the slots if (!clusterProvider.clusterManager.TryRemoveSlots(slots, out var slotIndex) && slotIndex != -1) { - while (!RespWriteUtils.WriteError($"ERR Slot {slotIndex} is not assigned", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Slot {slotIndex} is not assigned", ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -281,7 +281,7 @@ private bool NetworkClusterDelKeysInSlot(out bool invalidParameters) if (!parseState.TryGetInt(0, out var slot)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) SendAndReset(); return true; } @@ -291,7 +291,7 @@ private bool NetworkClusterDelKeysInSlot(out bool invalidParameters) if (!clusterProvider.serverOptions.DisableObjects) ClusterManager.DeleteKeysInSlotsFromObjectStore(basicGarnetApi, slots); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -319,7 +319,7 @@ private bool NetworkClusterDelKeysInSlotRange(out bool invalidParameters) //The slot parsing may give errorMessage even if the TryParseSlots returns true. if (!slotsParsed) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; } @@ -328,7 +328,7 @@ private bool NetworkClusterDelKeysInSlotRange(out bool invalidParameters) if (!clusterProvider.serverOptions.DisableObjects) ClusterManager.DeleteKeysInSlotsFromObjectStore(basicGarnetApi, slots); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -352,21 +352,21 @@ private bool NetworkClusterGetKeysInSlot(out bool invalidParameters) var current = clusterProvider.clusterManager.CurrentConfig; if (!parseState.TryGetInt(0, out var slot)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) SendAndReset(); return true; } if (!parseState.TryGetInt(1, out var keyCount)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } if (ClusterConfig.OutOfRange(slot)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_SLOT_OUT_OFF_RANGE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_SLOT_OUT_OFF_RANGE, ref dcurr, dend)) SendAndReset(); return true; } @@ -379,10 +379,10 @@ private bool NetworkClusterGetKeysInSlot(out bool invalidParameters) { var keys = GetKeysInSlot(slot, keyCount); var keyCountRet = Math.Min(keys.Count, keyCount); - while (!RespWriteUtils.WriteArrayLength(keyCountRet, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(keyCountRet, ref dcurr, dend)) SendAndReset(); for (var i = 0; i < keyCountRet; i++) - while (!RespWriteUtils.WriteBulkString(keys[i], ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(keys[i], ref dcurr, dend)) SendAndReset(); } @@ -410,7 +410,7 @@ private bool NetworkClusterKeySlot(out bool invalidParameters) var keySize = sbKey.Length; int slot = HashSlotUtils.HashSlot(keyPtr, keySize); - while (!RespWriteUtils.WriteInteger(slot, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(slot, ref dcurr, dend)) SendAndReset(); return true; @@ -434,7 +434,7 @@ private bool NetworkClusterSetSlot(out bool invalidParameters) if (!parseState.TryGetInt(0, out var slot)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) SendAndReset(); return true; } @@ -443,7 +443,7 @@ private bool NetworkClusterSetSlot(out bool invalidParameters) slotState == SlotState.OFFLINE) { var slotStateStr = parseState.GetString(1); - while (!RespWriteUtils.WriteError($"ERR Slot state {slotStateStr} not supported.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Slot state {slotStateStr} not supported.", ref dcurr, dend)) SendAndReset(); return true; @@ -458,7 +458,7 @@ private bool NetworkClusterSetSlot(out bool invalidParameters) // Check that node id is only provided for options other than STABLE if ((slotState == SlotState.STABLE && nodeId is not null) || (slotState != SlotState.STABLE && nodeId is null)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; @@ -492,18 +492,18 @@ private bool NetworkClusterSetSlot(out bool invalidParameters) { UnsafeBumpAndWaitForEpochTransition(); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_SLOT_OUT_OFF_RANGE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_SLOT_OUT_OFF_RANGE, ref dcurr, dend)) SendAndReset(); } @@ -543,7 +543,7 @@ private bool NetworkClusterSetSlotsRange(out bool invalidParameters) if (slotState == SlotState.INVALID) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_SLOT_STATE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_SLOT_STATE, ref dcurr, dend)) SendAndReset(); return true; } @@ -558,7 +558,7 @@ private bool NetworkClusterSetSlotsRange(out bool invalidParameters) var slotsParsed = TryParseSlots(slotState == SlotState.STABLE ? 1 : 2, out var slots, out var errorMessage, range: true); if (!slotsParsed) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; } @@ -591,12 +591,12 @@ private bool NetworkClusterSetSlotsRange(out bool invalidParameters) { UnsafeBumpAndWaitForEpochTransition(); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } @@ -620,7 +620,7 @@ private bool NetworkClusterSlots(out bool invalidParameters) } var slotsInfo = clusterProvider.clusterManager.CurrentConfig.GetSlotsInfo(); - while (!RespWriteUtils.WriteAsciiDirect(slotsInfo, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiDirect(slotsInfo, ref dcurr, dend)) SendAndReset(); return true; @@ -644,7 +644,7 @@ private bool NetworkClusterSlotState(out bool invalidParameters) if (!parseState.TryGetInt(0, out var slot)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_INVALID_SLOT, ref dcurr, dend)) SendAndReset(); return true; } @@ -661,7 +661,7 @@ private bool NetworkClusterSlotState(out bool invalidParameters) SlotState.FAIL => "*", _ => throw new Exception($"Invalid SlotState filetype {state}"), }; - while (!RespWriteUtils.WriteAsciiDirect($"+{slot} {stateStr} {nodeId}\r\n", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiDirect($"+{slot} {stateStr} {nodeId}\r\n", ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/cluster/Session/SlotVerification/RespClusterIterativeSlotVerify.cs b/libs/cluster/Session/SlotVerification/RespClusterIterativeSlotVerify.cs index 03bc660f29..3fe36867e9 100644 --- a/libs/cluster/Session/SlotVerification/RespClusterIterativeSlotVerify.cs +++ b/libs/cluster/Session/SlotVerification/RespClusterIterativeSlotVerify.cs @@ -71,7 +71,7 @@ public bool NetworkIterativeSlotVerify(ArgSlice keySlice, bool readOnly, byte Se public void WriteCachedSlotVerificationMessage(ref MemoryResult output) { var errorMessage = GetSlotVerificationMessage(configSnapshot, cachedVerificationResult); - RespWriteUtils.WriteError(errorMessage, ref output); + RespWriteUtils.TryWriteError(errorMessage, ref output); } } } \ No newline at end of file diff --git a/libs/cluster/Session/SlotVerification/RespClusterSlotVerify.cs b/libs/cluster/Session/SlotVerification/RespClusterSlotVerify.cs index 056c7232c9..31e5390b6e 100644 --- a/libs/cluster/Session/SlotVerification/RespClusterSlotVerify.cs +++ b/libs/cluster/Session/SlotVerification/RespClusterSlotVerify.cs @@ -28,7 +28,7 @@ private void Redirect(ushort slot, ClusterConfig config) errorMessage = CmdStrings.RESP_ERR_CLUSTERDOWN; logger?.LogDebug("SEND: {msg}", Encoding.ASCII.GetString(errorMessage)); - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); } @@ -81,7 +81,7 @@ private ReadOnlySpan GetSlotVerificationMessage(ClusterConfig config, Clus private void WriteClusterSlotVerificationMessage(ClusterConfig config, ClusterSlotVerificationResult vres, ref byte* dcurr, ref byte* dend) { var errorMessage = GetSlotVerificationMessage(config, vres); - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(ref dcurr, ref dend); } diff --git a/libs/common/NumUtils.cs b/libs/common/NumUtils.cs index 98433df301..a796c42dc5 100644 --- a/libs/common/NumUtils.cs +++ b/libs/common/NumUtils.cs @@ -8,7 +8,7 @@ namespace Garnet.common { /// - /// Utilities for numeric parsing + /// Utilities for numeric parsing and formatting /// public static unsafe class NumUtils { @@ -16,36 +16,36 @@ public static unsafe class NumUtils public const int MaximumFormatDoubleLength = 310; // (i.e. -1.7976931348623157E+308) /// - /// Convert long number into sequence of ASCII bytes + /// Writes 64-bit signed integer as ASCII. /// - /// Value to convert - /// Span Byte - /// Length of number in result - public static int LongToSpanByte(long value, Span dest) + /// The value to write + /// Span Byte + /// The length of written text in bytes. + public static int WriteInt64(long value, Span destination) { - int valueLen = NumDigitsInLong(value); - byte sign = (byte)(value < 0 ? 1 : 0); - int totalLen = sign + valueLen; - if (totalLen > dest.Length) + var valueLen = CountDigits(value); + var signLen = (byte)(value < 0 ? 1 : 0); + var totalLen = signLen + valueLen; + if (totalLen > destination.Length) return 0; - fixed (byte* ptr = dest) + fixed (byte* ptr = destination) { byte* curr = ptr; - LongToBytes(value, valueLen, ref curr); + WriteInt64(value, valueLen, ref curr); } return totalLen; } /// - /// Convert long into sequence of ASCII bytes + /// Writes 64-bit signed integer as ASCII. /// - /// + /// The value to write /// - /// - public static unsafe void LongToBytes(long value, int length, ref byte* result) + /// Byte pointer, will be updated to point after the written number + public static unsafe void WriteInt64(long value, int length, ref byte* result) { - byte sign = (byte)(value < 0 ? 1 : 0); + var isNegative = value < 0; if (value == long.MinValue) { *(long*)(result) = 3618417120593983789L; @@ -61,7 +61,7 @@ public static unsafe void LongToBytes(long value, int length, ref byte* result) return; } - if (sign == 0x1) + if (isNegative) { *result++ = 0x2d; value = -value; @@ -77,34 +77,34 @@ public static unsafe void LongToBytes(long value, int length, ref byte* result) } /// - /// Convert double number into sequence of ASCII bytes + /// Writes as ASCII. /// - /// Value to convert - /// Span Byte - /// Length of number in result - public static int DoubleToSpanByte(double value, Span dest) + /// The value to write + /// Buffer to write the ASCII formatted value to + /// The length of written text in bytes. + public static int WriteDouble(double value, Span destination) { - int totalLen = NumOfCharInDouble(value, out var integerDigits, out var signSize, out var fractionalDigits); - bool isNegative = value < 0; - if (totalLen > dest.Length) + var totalLen = CountCharsInDouble(value, out var integerDigits, out var signSize, out var fractionalDigits); + var isNegative = value < 0; + if (totalLen > destination.Length) return 0; - fixed (byte* ptr = dest) + fixed (byte* ptr = destination) { byte* curr = ptr; - DoubleToBytes(value, integerDigits, fractionalDigits, ref curr); + WriteDouble(value, integerDigits, fractionalDigits, ref curr); } return totalLen; } /// - /// Convert double number into sequence of ASCII bytes + /// Writes as ASCII. /// - /// Value to convert + /// The value to write /// Number of digits in the integer part of the double value /// Number of digits in the fractional part of the double value /// Byte pointer, will be updated to point after the written number - public static unsafe void DoubleToBytes(double value, int integerDigits, int fractionalDigits, ref byte* result) + public static unsafe void WriteDouble(double value, int integerDigits, int fractionalDigits, ref byte* result) { Debug.Assert(!double.IsNaN(value) && !double.IsInfinity(value), "Cannot convert NaN or Infinity to bytes."); @@ -114,7 +114,7 @@ public static unsafe void DoubleToBytes(double value, int integerDigits, int fra return; } - bool isNegative = value < 0; + var isNegative = value < 0; if (isNegative) { *result++ = (byte)'-'; @@ -123,7 +123,7 @@ public static unsafe void DoubleToBytes(double value, int integerDigits, int fra result += integerDigits; var integerPart = Math.Truncate(value); - double fractionalPart = fractionalDigits > 0 ? Math.Round(value - integerPart, fractionalDigits) : 0; + var fractionalPart = fractionalDigits > 0 ? Math.Round(value - integerPart, fractionalDigits) : 0; // Convert integer part do @@ -152,57 +152,57 @@ public static unsafe void DoubleToBytes(double value, int integerDigits, int fra } /// - /// Convert sequence of ASCII bytes into long number + /// Parses 64-bit signed integer from ASCII. /// - /// Source bytes - /// Result - public static long BytesToLong(ReadOnlySpan source) + /// Source buffer + /// The double value parsed from the buffer. + public static long ReadInt64(ReadOnlySpan source) { fixed (byte* ptr = source) - return BytesToLong(source.Length, ptr); + return ReadInt64(source.Length, ptr); } /// - /// Convert sequence of ASCII bytes into long number + /// Parses 64-bit signed integer from ASCII. /// /// Length of number /// Source bytes - /// Result - public static long BytesToLong(int length, byte* source) + /// The double value parsed from the buffer which points to. + public static long ReadInt64(int length, byte* source) { - bool fNeg = (*source == '-'); - var beg = fNeg ? source + 1 : source; + var isNegative = (*source == '-'); + var beg = isNegative ? source + 1 : source; var end = source + length; long result = 0; while (beg < end) result = result * 10 + (*beg++ - '0'); - return fNeg ? -(result) : result; + return isNegative ? -result : result; } /// - /// Convert sequence of ASCII bytes into long number + /// Parses 64-bit signed integer from ASCII. /// - /// Source bytes + /// Pointer to source buffer /// Long value extracted from sequence - /// True if sequence contains only numeric digits, otherwise false - public static bool TryBytesToLong(ReadOnlySpan source, out long result) + /// True if buffer consisted only of a valid signed 64-bit integer, otherwise false + public static bool TryReadInt64(ReadOnlySpan source, out long result) { fixed (byte* ptr = source) - return TryBytesToLong(source.Length, ptr, out result); + return TryReadInt64(source.Length, ptr, out result); } /// - /// Convert sequence of ASCII bytes into long number + /// Parses 64-bit signed integer from ASCII. /// - /// Length of number - /// Source bytes - /// Long value extracted from sequence - /// True if sequence contains only numeric digits, otherwise false - public static bool TryBytesToLong(int length, byte* source, out long result) + /// The expected length of the integer in the buffer which points to + /// Pointer to the source buffer + /// 64-bit signed integer parsed from the buffer which points to + /// True if the buffer which points to consisted only of a valid signed 64-bit integer, otherwise false + public static bool TryReadInt64(int length, byte* source, out long result) { - var fNeg = *source == '-'; - var beg = fNeg ? source + 1 : source; - var len = fNeg ? length - 1 : length; + var isNegative = *source == '-'; + var beg = isNegative ? source + 1 : source; + var len = isNegative ? length - 1 : length; result = 0; // Do not allow leading zeros @@ -214,34 +214,34 @@ public static bool TryBytesToLong(int length, byte* source, out long result) return false; // Negate if parsed value has a leading negative sign - result = fNeg ? -result : result; + result = isNegative ? -result : result; return true; } /// - /// Convert sequence of ASCII bytes into double number + /// Parses from ASCII. /// - /// Source bytes - /// Double value extracted from sequence - /// True if sequence contains only numeric digits, otherwise false - public static bool TryBytesToDouble(ReadOnlySpan source, out double result) + /// Source buffer + /// parsed from the buffer + /// True if the buffer consisted only of a valid , otherwise false + public static bool TryReadDouble(ReadOnlySpan source, out double result) { fixed (byte* ptr = source) - return TryBytesToDouble(source.Length, ptr, out result); + return TryReadDouble(source.Length, ptr, out result); } /// - /// Convert sequence of ASCII bytes into double number + /// Writes as ASCII. /// - /// Length of number - /// Source bytes + /// The expected length of the number in the buffer points to + /// Pointer to the source buffer /// Double value extracted from sequence - /// True if sequence contains only numeric digits, otherwise false - public static bool TryBytesToDouble(int length, byte* source, out double result) + /// True if the buffer which points to consisted only of a valid , otherwise false + public static bool TryReadDouble(int length, byte* source, out double result) { - var fNeg = *source == '-'; - var beg = fNeg ? source + 1 : source; - var len = fNeg ? length - 1 : length; + var isNegative = *source == '-'; + var beg = isNegative ? source + 1 : source; + var len = isNegative ? length - 1 : length; result = 0; // Do not allow leading zeros @@ -253,53 +253,19 @@ public static bool TryBytesToDouble(int length, byte* source, out double result) return false; // Negate if parsed value has a leading negative sign - result = fNeg ? -result : result; + result = isNegative ? -result : result; return true; } - /// - /// Convert sequence of ASCII bytes into ulong number - /// - /// Length of number - /// Source bytes - /// Result - public static ulong BytesToULong(int length, byte* source) - { - Debug.Assert(*source != '-'); - var beg = source; - var end = source + length; - ulong result = 0; - while (beg < end) - result = result * 10 + (ulong)(*beg++ - '0'); - return result; - } - - /// - /// Convert sequence of ASCII bytes into int number - /// - /// Length of number - /// Source bytes - /// - public static int BytesToInt(int length, byte* source) - { - bool fNeg = (*source == '-'); - var beg = fNeg ? source + 1 : source; - var end = source + length; - int result = 0; - while (beg < end) - result = result * 10 + (*beg++ - '0'); - return fNeg ? -(result) : result; - } - /// /// Convert integer into sequence of ASCII bytes /// - /// Value to convert - /// Number of digits in value + /// The value to write + /// Number of digits in the integer value /// Byte pointer, will updated to point after the written number - public static unsafe void IntToBytes(int value, int length, ref byte* result) + public static unsafe void WriteInt32(int value, int length, ref byte* result) { - bool isNegative = value < 0; + var isNegative = value < 0; if (value == 0) { *result++ = (byte)'0'; @@ -322,117 +288,112 @@ public static unsafe void IntToBytes(int value, int length, ref byte* result) result += length; } - static ReadOnlySpan digits => "00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"u8; - /// - /// Return number of digits in given number + /// Counts the number of digits in a given integer. /// - /// - /// - public static int NumDigits(int v) + /// Integer value + /// Doesn't count the sign as a digit. + /// The number of digits in . + public static int CountDigits(int value) { - v = v < 0 ? ((~v) + 1) : v; + value = value < 0 ? ((~value) + 1) : value; - if (v < 10) return 1; - if (v < 100) return 2; - if (v < 1000) return 3; - if (v < 100000000L) + if (value < 10) return 1; + if (value < 100) return 2; + if (value < 1000) return 3; + if (value < 100000000L) { - if (v < 1000000) + if (value < 1000000) { - if (v < 10000) return 4; - return 5 + (v >= 100000 ? 1 : 0); + if (value < 10000) return 4; + return 5 + (value >= 100000 ? 1 : 0); } - return 7 + (v >= 10000000L ? 1 : 0); + return 7 + (value >= 10000000L ? 1 : 0); } - return 9 + (v >= 1000000000L ? 1 : 0); + return 9 + (value >= 1000000000L ? 1 : 0); } - /// - /// Num digits in long divide n conquer. - /// - /// - /// returns digit count not including sign. - public static int NumDigitsInLong(long v) + + /// + public static int CountDigits(long value) { - if (v == long.MinValue) return 19; - v = v < 0 ? -v : v; - int c = 0; + if (value == long.MinValue) return 19; + value = value < 0 ? -value : value; - if (v < 10000000000L)//1 - 10000000000L + if (value < 10000000000L)//1 - 10000000000L { - if (v < 100000) //1 - 100000 + if (value < 100000) //1 - 100000 { - if (v < 100) //1 - 100 + if (value < 100) //1 - 100 { - if (v < 10) return c + 1; else return c + 2; + if (value < 10) return 1; else return 2; } else//100 - 100000 { - if (v < 10000)//100 - 10000 + if (value < 10000)//100 - 10000 { - if (v < 1000) return c + 3; else return c + 4; + if (value < 1000) return 3; else return 4; } else//10000 - 100000 { - return c + 5; + return 5; } } } else // 100 000 - 10 000 000 000L { - if (v < 10000000) // 100 000 - 10 000 000 + if (value < 10000000) // 100 000 - 10 000 000 { - if (v < 1000000) return c + 6; else return c + 7; + if (value < 1000000) return 6; else return 7; } else // 10 000 000 - 10 000 000 000L { - if (v < 1000000000) + if (value < 1000000000) { - if (v < 100000000) return c + 8; else return c + 9; + if (value < 100000000) return 8; else return 9; } else // 1 000 000 000 - 10 000 000 000L { - return c + 10; + return 10; } } } } else // 10 000 000 000L - 1 000 000 000 000 000 000L { - if (v < 100000000000000L) //10 000 000 000L - 100 000 000 000 000L + if (value < 100000000000000L) //10 000 000 000L - 100 000 000 000 000L { - if (v < 1000000000000L) // 10 000 000 000L - 1 000 000 000 000L + if (value < 1000000000000L) // 10 000 000 000L - 1 000 000 000 000L { - if (v < 100000000000L) return c + 11; else return c + 12; + if (value < 100000000000L) return 11; else return 12; } else // 1 000 000 000 000L - 100 000 000 000 000L { - if (v < 10000000000000L) // 1 000 000 000 000L - 10 000 000 000 000L + if (value < 10000000000000L) // 1 000 000 000 000L - 10 000 000 000 000L { - return c + 13; + return 13; } else { - return c + 14; + return 14; } } } else//100 000 000 000 000L - 1 000 000 000 000 000 000L { - if (v < 10000000000000000L)//100 000 000 000 000L - 10 000 000 000 000 000L + if (value < 10000000000000000L)//100 000 000 000 000L - 10 000 000 000 000 000L { - if (v < 1000000000000000L) return c + 15; else return c + 16; + if (value < 1000000000000000L) return 15; else return 16; } else { - if (v < 1000000000000000000L) + if (value < 1000000000000000000L) { - if (v < 100000000000000000L) return c + 17; else return c + 18; + if (value < 100000000000000000L) return 17; else return 18; } else { - return c + 19; + return 19; } } } @@ -440,59 +401,60 @@ public static int NumDigitsInLong(long v) } /// - /// Return number of digits in given number + /// Counts the number of digits in a given integer. /// - /// - /// - /// - public static int NumDigitsInLong(long v, ref bool fNeg) + /// Integer value + /// Whether the is negative or not + /// Doesn't count the sign as a digit. + /// The number of digits in . + public static int CountDigits(long value, out bool isNegative) { - if (v == long.MinValue) + if (value == long.MinValue) { - fNeg = true; + isNegative = true; return 19; } - fNeg = false; - if (v < 0) + isNegative = false; + if (value < 0) { - fNeg = true; - v = -(v); + isNegative = true; + value = -value; } - if (v < 10) return 1; - if (v < 100) return 2; - if (v < 1000) return 3; - if (v < 1_000_000_00L) // 9 digit + if (value < 10) return 1; + if (value < 100) return 2; + if (value < 1000) return 3; + if (value < 1_000_000_00L) // 9 digit { - if (v < 1000000)// 7 dgiit + if (value < 1000000)// 7 dgiit { - if (v < 10000) return 4; - return 5 + (v >= 100000 ? 1 : 0); // 5 or 6 digit + if (value < 10000) return 4; + return 5 + (value >= 100000 ? 1 : 0); // 5 or 6 digit } - return 7 + (v >= 1_000_000_0L ? 1 : 0); + return 7 + (value >= 1_000_000_0L ? 1 : 0); } - if (v < 1000000000L) return 9; - if (v < 10000000000L) return 10; - if (v < 100000000000L) return 11; - if (v < 1000000000000L) return 12; - if (v < 10000000000000L) return 13; - if (v < 100000000000000L) return 14; - if (v < 1000000000000000L) return 15; - if (v < 10000000000000000L) return 16; - if (v < 100000000000000000L) return 17; - if (v < 1000000000000000000L) return 18; + if (value < 1000000000L) return 9; + if (value < 10000000000L) return 10; + if (value < 100000000000L) return 11; + if (value < 1000000000000L) return 12; + if (value < 10000000000000L) return 13; + if (value < 100000000000000L) return 14; + if (value < 1000000000000000L) return 15; + if (value < 10000000000000000L) return 16; + if (value < 100000000000000000L) return 17; + if (value < 1000000000000000000L) return 18; return 19; } /// /// Return number of digits in given double number incluing the decimal part and `.` character /// - /// Double value + /// Double value /// Number of digits in the integer part of the double value - public static int NumOfCharInDouble(double v, out int integerDigits, out byte signSize, out int fractionalDigits) + public static int CountCharsInDouble(double value, out int integerDigits, out byte signSize, out int fractionalDigits) { - if (v == 0) + if (value == 0) { integerDigits = 1; signSize = 0; @@ -500,14 +462,14 @@ public static int NumOfCharInDouble(double v, out int integerDigits, out byte si return 1; } - Debug.Assert(!double.IsNaN(v) && !double.IsInfinity(v)); + Debug.Assert(!double.IsNaN(value) && !double.IsInfinity(value)); - signSize = (byte)(v < 0 ? 1 : 0); // Add sign if the number is negative - v = Math.Abs(v); - integerDigits = (int)Math.Log10(v) + 1; + signSize = (byte)(value < 0 ? 1 : 0); // Add sign if the number is negative + value = Math.Abs(value); + integerDigits = (int)Math.Log10(value) + 1; fractionalDigits = 0; // Max of 15 significant digits - while (fractionalDigits <= 14 && Math.Abs(v - Math.Round(v, fractionalDigits)) > 2 * Double.Epsilon) // 2 * Double.Epsilon is used to handle floating point errors + while (fractionalDigits <= 14 && Math.Abs(value - Math.Round(value, fractionalDigits)) > 2 * Double.Epsilon) // 2 * Double.Epsilon is used to handle floating point errors { fractionalDigits++; } diff --git a/libs/common/RespReadUtils.cs b/libs/common/RespReadUtils.cs index a82ed7ee87..8b77b6939d 100644 --- a/libs/common/RespReadUtils.cs +++ b/libs/common/RespReadUtils.cs @@ -40,8 +40,9 @@ private static bool TryReadSign(byte* ptr, out bool negative) /// True if a ulong was successfully parsed, false if the input string did not start with /// a valid integer or the end of the string was reached before finishing parsing. /// + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static bool TryReadUlong(ref byte* ptr, byte* end, out ulong value, out ulong bytesRead) + private static bool TryReadUInt64(ref byte* ptr, byte* end, out ulong value, out ulong bytesRead) { bytesRead = 0; value = 0; @@ -112,10 +113,11 @@ private static bool TryReadUlong(ref byte* ptr, byte* end, out ulong value, out /// True if a long was successfully parsed, false if the input string did not start with /// a valid integer or the end of the string was reached before finishing parsing. /// + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool TryReadLong(ref byte* ptr, byte* end, out long value, out ulong bytesRead, bool allowLeadingZeros = true) + public static bool TryReadInt64(ref byte* ptr, byte* end, out long value, out ulong bytesRead, bool allowLeadingZeros = true) { - if (TryReadLongSafe(ref ptr, end, out value, out bytesRead, out var signRead, + if (TryReadInt64Safe(ref ptr, end, out value, out bytesRead, out var signRead, out var overflow, allowLeadingZeros)) return true; @@ -143,8 +145,9 @@ public static bool TryReadLong(ref byte* ptr, byte* end, out long value, out ulo /// True if a long was successfully parsed, false if the input string did not start with /// a valid integer or the end of the string was reached before finishing parsing. /// + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool TryReadLongSafe(ref byte* ptr, byte* end, out long value, out ulong bytesRead, out bool signRead, out bool overflow, bool allowLeadingZeros = true) + public static bool TryReadInt64Safe(ref byte* ptr, byte* end, out long value, out ulong bytesRead, out bool signRead, out bool overflow, bool allowLeadingZeros = true) { bytesRead = 0; value = 0; @@ -166,7 +169,7 @@ public static bool TryReadLongSafe(ref byte* ptr, byte* end, out long value, out } // Parse digits as ulong - if (!TryReadUlong(ref ptr, end, out var number, out var digitsRead)) + if (!TryReadUInt64(ref ptr, end, out var number, out var digitsRead)) { return false; } @@ -210,10 +213,11 @@ public static bool TryReadLongSafe(ref byte* ptr, byte* end, out long value, out /// True if an int was successfully parsed, false if the input string did not start with /// a valid integer or the end of the string was reached before finishing parsing. /// + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool TryReadInt(ref byte* ptr, byte* end, out int value, out ulong bytesRead, bool allowLeadingZeros = true) + public static bool TryReadInt32(ref byte* ptr, byte* end, out int value, out ulong bytesRead, bool allowLeadingZeros = true) { - if (TryReadIntSafe(ref ptr, end, out value, out bytesRead, out var signRead, + if (TryReadInt32Safe(ref ptr, end, out value, out bytesRead, out var signRead, out var overflow, allowLeadingZeros)) return true; @@ -241,8 +245,9 @@ public static bool TryReadInt(ref byte* ptr, byte* end, out int value, out ulong /// True if an int was successfully parsed, false if the input string did not start with /// a valid integer or the end of the string was reached before finishing parsing. /// + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool TryReadIntSafe(ref byte* ptr, byte* end, out int value, out ulong bytesRead, out bool signRead, out bool overflow, bool allowLeadingZeros = true) + public static bool TryReadInt32Safe(ref byte* ptr, byte* end, out int value, out ulong bytesRead, out bool signRead, out bool overflow, bool allowLeadingZeros = true) { bytesRead = 0; value = 0; @@ -256,8 +261,8 @@ public static bool TryReadIntSafe(ref byte* ptr, byte* end, out int value, out u bytesRead = 1; } - // Parse digits as ulong - if (!TryReadUlong(ref ptr, end, out var number, out var digitsRead)) + // Parse digits as unsigned 64-bit integer + if (!TryReadUInt64(ref ptr, end, out var number, out var digitsRead)) { return false; } @@ -291,8 +296,9 @@ public static bool TryReadIntSafe(ref byte* ptr, byte* end, out int value, out u /// /// Tries to read a RESP length header from the given ASCII-encoded RESP string /// and, if successful, moves the given ptr to the end of the length header. + /// /// NOTE: - /// It will throw an exception if length header is negative. + /// It will throw an if length header is negative. /// It is primarily used for parsing header length from packets received from server side. /// /// If parsing was successful, contains the extracted length from the header. @@ -300,8 +306,11 @@ public static bool TryReadIntSafe(ref byte* ptr, byte* end, out int value, out u /// The current end of the RESP string. /// Whether to parse an array length header ('*...\r\n') or a string length header ('$...\r\n'). /// True if a length header was successfully read. + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadUnsignedLengthHeader(out int length, ref byte* ptr, byte* end, bool isArray = false) + public static bool TryReadUnsignedLengthHeader(out int length, ref byte* ptr, byte* end, bool isArray = false) { length = -1; if (ptr + 3 > end) @@ -315,7 +324,7 @@ public static bool ReadUnsignedLengthHeader(out int length, ref byte* ptr, byte* RespParsingException.ThrowInvalidStringLength(length); } - if (!ReadSignedLengthHeader(out length, ref ptr, end, isArray)) + if (!TryReadSignedLengthHeader(out length, ref ptr, end, isArray)) return false; return true; @@ -324,6 +333,7 @@ public static bool ReadUnsignedLengthHeader(out int length, ref byte* ptr, byte* /// /// Tries to read a RESP a signed length header from the given ASCII-encoded RESP string /// and, if successful, moves the given ptr to the end of the length header. + /// /// NOTE: /// It will not throw an exception if length header is negative. /// It is primarily used by client side code. @@ -334,8 +344,10 @@ public static bool ReadUnsignedLengthHeader(out int length, ref byte* ptr, byte* /// The current end of the RESP string. /// Whether to parse an array length header ('*...\r\n') or a string length header ('$...\r\n'). /// True if a length header was successfully read. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadSignedLengthHeader(out int length, ref byte* ptr, byte* end, bool isArray = false) + public static bool TryReadSignedLengthHeader(out int length, ref byte* ptr, byte* end, bool isArray = false) { length = -1; if (ptr + 3 > end) @@ -367,7 +379,7 @@ public static bool ReadSignedLengthHeader(out int length, ref byte* ptr, byte* e } // Parse length - if (!TryReadUlong(ref readHead, end, out var value, out var digitsRead)) + if (!TryReadUInt64(ref readHead, end, out var value, out var digitsRead)) { return false; } @@ -402,11 +414,12 @@ public static bool ReadSignedLengthHeader(out int length, ref byte* ptr, byte* e } /// - /// Read signed 64 bit number + /// Read signed 64 bit integer /// - public static bool Read64Int(out long number, ref byte* ptr, byte* end) + /// Thrown if unexpected token is read. + public static bool TryReadInt64(out long number, ref byte* ptr, byte* end) { - var success = TryRead64Int(out number, ref ptr, end, out var unexpectedToken); + var success = TryReadInt64(out number, ref ptr, end, out var unexpectedToken); if (!success && unexpectedToken.HasValue) { @@ -417,9 +430,10 @@ public static bool Read64Int(out long number, ref byte* ptr, byte* end) } /// - /// Try read signed 64 bit number + /// Try read signed 64 bit integer /// - public static bool TryRead64Int(out long number, ref byte* ptr, byte* end, out byte? unexpectedToken) + /// Thrown if integer overflow occurs. + public static bool TryReadInt64(out long number, ref byte* ptr, byte* end, out byte? unexpectedToken) { number = 0; unexpectedToken = null; @@ -437,7 +451,7 @@ public static bool TryRead64Int(out long number, ref byte* ptr, byte* end, out b ptr++; // Parse length - if (!TryReadLong(ref ptr, end, out number, out _)) + if (!TryReadInt64(ref ptr, end, out number, out _)) { return false; } @@ -461,36 +475,48 @@ public static bool TryRead64Int(out long number, ref byte* ptr, byte* end, out b /// /// Tries to read a RESP array length header from the given ASCII-encoded RESP string /// and, if successful, moves the given ptr to the end of the length header. + /// /// NOTE: We use ReadUnsignedLengthHeader because server does not accept $-1\r\n headers /// /// If parsing was successful, contains the extracted length from the header. /// The starting position in the RESP string. Will be advanced if parsing is successful. /// The current end of the RESP string. /// True if a length header was successfully read. - public static bool ReadUnsignedArrayLength(out int length, ref byte* ptr, byte* end) - => ReadUnsignedLengthHeader(out length, ref ptr, end, isArray: true); + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + public static bool TryReadUnsignedArrayLength(out int length, ref byte* ptr, byte* end) + => TryReadUnsignedLengthHeader(out length, ref ptr, end, isArray: true); /// /// Tries to read a RESP array length header from the given ASCII-encoded RESP string /// and, if successful, moves the given ptr to the end of the length header. + /// /// NOTE: It will not throw an exception if length header is negative. /// /// If parsing was successful, contains the extracted length from the header. /// The starting position in the RESP string. Will be advanced if parsing is successful. /// The current end of the RESP string. /// True if a length header was successfully read. - public static bool ReadSignedArrayLength(out int length, ref byte* ptr, byte* end) - => ReadSignedLengthHeader(out length, ref ptr, end, isArray: true); + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + public static bool TryReadSignedArrayLength(out int length, ref byte* ptr, byte* end) + => TryReadSignedLengthHeader(out length, ref ptr, end, isArray: true); /// - /// Read int with length header + /// Reads a signed 32-bit integer with length header /// - public static bool ReadIntWithLengthHeader(out int number, ref byte* ptr, byte* end) + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + /// Thrown if not a number is read. + public static bool TryReadInt32WithLengthHeader(out int number, ref byte* ptr, byte* end) { number = 0; // Parse RESP string header - if (!ReadUnsignedLengthHeader(out var numberLength, ref ptr, end)) + if (!TryReadUnsignedLengthHeader(out var numberLength, ref ptr, end)) return false; if (ptr + numberLength + 2 > end) @@ -498,7 +524,7 @@ public static bool ReadIntWithLengthHeader(out int number, ref byte* ptr, byte* // Parse associated integer value var numberStart = ptr; - if (!TryReadInt(ref ptr, end, out number, out var bytesRead)) + if (!TryReadInt32(ref ptr, end, out number, out var bytesRead)) { return false; } @@ -520,14 +546,18 @@ public static bool ReadIntWithLengthHeader(out int number, ref byte* ptr, byte* } /// - /// Read long with length header + /// Read a signed 64-bit integer with length header /// - public static bool ReadLongWithLengthHeader(out long number, ref byte* ptr, byte* end) + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + /// Thrown if not a number is read. + public static bool TryReadInt64WithLengthHeader(out long number, ref byte* ptr, byte* end) { number = 0; // Parse RESP string header - if (!ReadUnsignedLengthHeader(out var numberLength, ref ptr, end)) + if (!TryReadUnsignedLengthHeader(out var numberLength, ref ptr, end)) return false; if (ptr + numberLength + 2 > end) @@ -535,7 +565,7 @@ public static bool ReadLongWithLengthHeader(out long number, ref byte* ptr, byte // Parse associated integer value var numberStart = ptr; - if (!TryReadLong(ref ptr, end, out number, out var bytesRead)) + if (!TryReadInt64(ref ptr, end, out number, out var bytesRead)) { return false; } @@ -559,12 +589,16 @@ public static bool ReadLongWithLengthHeader(out long number, ref byte* ptr, byte /// /// Read long with length header /// - public static bool ReadULongWithLengthHeader(out ulong number, ref byte* ptr, byte* end) + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + /// Thrown if not a number is read. + public static bool TryReadUInt64WithLengthHeader(out ulong number, ref byte* ptr, byte* end) { number = 0; // Parse RESP string header - if (!ReadUnsignedLengthHeader(out var numberLength, ref ptr, end)) + if (!TryReadUnsignedLengthHeader(out var numberLength, ref ptr, end)) return false; if (ptr + numberLength + 2 > end) @@ -572,7 +606,7 @@ public static bool ReadULongWithLengthHeader(out ulong number, ref byte* ptr, by // Parse associated integer value var numberStart = ptr; - if (!TryReadUlong(ref ptr, end, out number, out var bytesRead)) + if (!TryReadUInt64(ref ptr, end, out number, out var bytesRead)) { return false; } @@ -596,10 +630,13 @@ public static bool ReadULongWithLengthHeader(out ulong number, ref byte* ptr, by /// /// Skip byte array with length header /// - public static bool SkipByteArrayWithLengthHeader(ref byte* ptr, byte* end) + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + public static bool TrySkipByteArrayWithLengthHeader(ref byte* ptr, byte* end) { // Parse RESP string header - if (!ReadUnsignedLengthHeader(out var length, ref ptr, end)) + if (!TryReadUnsignedLengthHeader(out var length, ref ptr, end)) return false; // Advance read pointer to the end of the array (including terminator) @@ -621,7 +658,10 @@ public static bool SkipByteArrayWithLengthHeader(ref byte* ptr, byte* end) /// /// Read byte array with length header /// - public static bool ReadByteArrayWithLengthHeader(out byte[] result, ref byte* ptr, byte* end) + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + public static bool TryReadByteArrayWithLengthHeader(out byte[] result, ref byte* ptr, byte* end) { result = null; if (!TrySliceWithLengthHeader(out var resultSpan, ref ptr, end)) @@ -651,12 +691,15 @@ public static bool ReadByteArrayWithLengthHeader(out byte[] result, ref byte* pt /// } /// /// + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. public static bool TrySliceWithLengthHeader(out ReadOnlySpan result, scoped ref byte* ptr, byte* end) { result = default; // Parse RESP string header - if (!ReadUnsignedLengthHeader(out var length, ref ptr, end)) + if (!TryReadUnsignedLengthHeader(out var length, ref ptr, end)) return false; // Advance read pointer to the end of the array (including terminator) @@ -680,7 +723,10 @@ public static bool TrySliceWithLengthHeader(out ReadOnlySpan result, scope /// /// Read boolean value with length header /// - public static bool ReadBoolWithLengthHeader(out bool result, ref byte* ptr, byte* end) + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + public static bool TryReadBoolWithLengthHeader(out bool result, ref byte* ptr, byte* end) { result = false; @@ -696,7 +742,7 @@ public static bool ReadBoolWithLengthHeader(out bool result, ref byte* ptr, byte else { // Parse malformed RESP string header - if (!ReadUnsignedLengthHeader(out var length, ref ptr, end)) + if (!TryReadUnsignedLengthHeader(out var length, ref ptr, end)) return false; if (length != 1) @@ -722,15 +768,19 @@ public static bool ReadBoolWithLengthHeader(out bool result, ref byte* ptr, byte /// /// Tries to read a RESP-formatted string including its length header from the given ASCII-encoded /// RESP message and, if successful, moves the given ptr to the end of the string value. + /// /// NOTE: We use ReadUnsignedLengthHeader because server does not accept $-1\r\n headers /// /// If parsing was successful, contains the extracted string value. /// The starting position in the RESP message. Will be advanced if parsing is successful. /// The current end of the RESP message. /// True if a RESP string was successfully read. - public static bool ReadStringWithLengthHeader(out string result, ref byte* ptr, byte* end) + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + public static bool TryReadStringWithLengthHeader(out string result, ref byte* ptr, byte* end) { - ReadSpanWithLengthHeader(out var resultSpan, ref ptr, end); + TryReadSpanWithLengthHeader(out var resultSpan, ref ptr, end); result = Encoding.UTF8.GetString(resultSpan); return true; } @@ -738,13 +788,17 @@ public static bool ReadStringWithLengthHeader(out string result, ref byte* ptr, /// /// Tries to read a RESP-formatted string as span including its length header from the given ASCII-encoded /// RESP message and, if successful, moves the given ptr to the end of the string value. + /// /// NOTE: We use ReadUnsignedLengthHeader because server does not accept $-1\r\n headers /// /// If parsing was successful, contains the extracted string value. /// The starting position in the RESP message. Will be advanced if parsing is successful. /// The current end of the RESP message. /// True if a RESP string was successfully read. - public static bool ReadSpanWithLengthHeader(out ReadOnlySpan result, ref byte* ptr, byte* end) + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + public static bool TryReadSpanWithLengthHeader(out ReadOnlySpan result, ref byte* ptr, byte* end) { result = null; @@ -752,7 +806,7 @@ public static bool ReadSpanWithLengthHeader(out ReadOnlySpan result, ref b return false; // Parse RESP string header - if (!ReadUnsignedLengthHeader(out var length, ref ptr, end)) + if (!TryReadUnsignedLengthHeader(out var length, ref ptr, end)) return false; // Extract string content + '\r\n' terminator @@ -776,20 +830,21 @@ public static bool ReadSpanWithLengthHeader(out ReadOnlySpan result, ref b /// /// Try to read a RESP formatted bulk string + /// /// NOTE: This is used with client implementation to parse responses that may include a null value (i.e. $-1\r\n) /// - /// - /// - /// - /// + /// If parsing was successful, contains the extracted string value. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP string was successfully read. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadStringResponseWithLengthHeader(out string result, ref byte* ptr, byte* end) + public static bool TryReadStringResponseWithLengthHeader(out string result, ref byte* ptr, byte* end) { result = null; byte* keyPtr = null; var length = 0; - if (!ReadPtrWithSignedLengthHeader(ref keyPtr, ref length, ref ptr, end)) + if (!TryReadPtrWithSignedLengthHeader(ref keyPtr, ref length, ref ptr, end)) return false; if (length < 0) @@ -799,11 +854,24 @@ public static bool ReadStringResponseWithLengthHeader(out string result, ref byt return true; } + /// + /// Try to read a RESP string and return pointer to the start of the string + /// + /// NOTE: This is used with client implementation to parse responses that may include a null value (i.e. $-1\r\n) + /// + /// If parsing was successful, contains the pointer to start of the parsed string value. + /// If parsing was successful, contains the length of the string value. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP string was successfully read. + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - static bool ReadPtrWithSignedLengthHeader(ref byte* keyPtr, ref int length, ref byte* ptr, byte* end) + static bool TryReadPtrWithSignedLengthHeader(ref byte* stringPtr, ref int length, ref byte* ptr, byte* end) { // Parse RESP string header - if (!ReadSignedLengthHeader(out length, ref ptr, end)) + if (!TryReadSignedLengthHeader(out length, ref ptr, end)) { return false; } @@ -812,11 +880,11 @@ static bool ReadPtrWithSignedLengthHeader(ref byte* keyPtr, ref int length, ref if (length < 0) { // NULL value ('$-1\r\n') - keyPtr = null; + stringPtr = null; return true; } - keyPtr = ptr; + stringPtr = ptr; // Parse content: ensure that input contains key + '\r\n' ptr += length + 2; @@ -836,7 +904,12 @@ static bool ReadPtrWithSignedLengthHeader(ref byte* keyPtr, ref int length, ref /// /// Read simple string /// - public static bool ReadSimpleString(out string result, ref byte* ptr, byte* end) + /// If parsing was successful, contains the extracted string value. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP simple string was successfully read. + /// Thrown if unexpected token is read. + public static bool TryReadSimpleString(out string result, ref byte* ptr, byte* end) { result = null; @@ -851,13 +924,18 @@ public static bool ReadSimpleString(out string result, ref byte* ptr, byte* end) ptr++; - return ReadString(out result, ref ptr, end); + return TryReadString(out result, ref ptr, end); } /// /// Read error as string /// - public static bool ReadErrorAsString(out string result, ref byte* ptr, byte* end) + /// If parsing was successful, contains the extracted string value. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP error string was successfully read. + /// Thrown if unexpected token is read. + public static bool TryReadErrorAsString(out string result, ref byte* ptr, byte* end) { result = null; if (ptr + 2 >= end) @@ -871,12 +949,16 @@ public static bool ReadErrorAsString(out string result, ref byte* ptr, byte* end ptr++; - return ReadString(out result, ref ptr, end); + return TryReadString(out result, ref ptr, end); } /// /// Read error as span /// + /// If parsing was successful, contains the span pointing to parsed error string value. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP error was successfully read. public static bool TryReadErrorAsSpan(out ReadOnlySpan result, ref byte* ptr, byte* end) { result = null; @@ -891,15 +973,20 @@ public static bool TryReadErrorAsSpan(out ReadOnlySpan result, ref byte* p ptr++; - return ReadAsSpan(out result, ref ptr, end); + return TryReadAsSpan(out result, ref ptr, end); } /// /// Read integer as string /// - public static bool ReadIntegerAsString(out string result, ref byte* ptr, byte* end) + /// If parsing was successful, contains the parsed integer as a string. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP integer was successfully read. + /// Thrown if unexpected token is read. + public static bool TryReadIntegerAsString(out string result, ref byte* ptr, byte* end) { - var success = ReadIntegerAsSpan(out var resultSpan, ref ptr, end); + var success = TryReadIntegerAsSpan(out var resultSpan, ref ptr, end); result = Encoding.UTF8.GetString(resultSpan); return success; } @@ -907,7 +994,12 @@ public static bool ReadIntegerAsString(out string result, ref byte* ptr, byte* e /// /// Read integer as string /// - public static bool ReadIntegerAsSpan(out ReadOnlySpan result, ref byte* ptr, byte* end) + /// If parsing was successful, contains a span pointing to the integer in the buffer. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP integer was successfully read. + /// Thrown if unexpected token is read. + public static bool TryReadIntegerAsSpan(out ReadOnlySpan result, ref byte* ptr, byte* end) { result = null; if (ptr + 2 >= end) @@ -921,19 +1013,27 @@ public static bool ReadIntegerAsSpan(out ReadOnlySpan result, ref byte* pt ptr++; - return ReadAsSpan(out result, ref ptr, end); + return TryReadAsSpan(out result, ref ptr, end); } /// /// Read string array with length header + /// /// NOTE: We use ReadUnsignedLengthHeader because server does not accept *-1\r\n headers. /// - public static bool ReadStringArrayWithLengthHeader(out string[] result, ref byte* ptr, byte* end) + /// If parsing was successful, contains a array of parsed string values. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP string array was successfully read. + /// Thrown if the array length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. + public static bool TryReadStringArrayWithLengthHeader(out string[] result, ref byte* ptr, byte* end) { result = null; // Parse RESP array header - if (!ReadUnsignedArrayLength(out var length, ref ptr, end)) + if (!TryReadUnsignedArrayLength(out var length, ref ptr, end)) { return false; } @@ -944,12 +1044,12 @@ public static bool ReadStringArrayWithLengthHeader(out string[] result, ref byte { if (*ptr == '$') { - if (!ReadStringWithLengthHeader(out result[i], ref ptr, end)) + if (!TryReadStringWithLengthHeader(out result[i], ref ptr, end)) return false; } else { - if (!ReadIntegerAsString(out result[i], ref ptr, end)) + if (!TryReadIntegerAsString(out result[i], ref ptr, end)) return false; } } @@ -960,7 +1060,12 @@ public static bool ReadStringArrayWithLengthHeader(out string[] result, ref byte /// /// Read double with length header /// - public static bool ReadDoubleWithLengthHeader(out double result, out bool parsed, ref byte* ptr, byte* end) + /// If parsing was successful, contains the parsed value. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + /// True if a RESP double was successfully read. + /// Thrown if unexpected token is read. + public static bool TryReadDoubleWithLengthHeader(out double result, out bool parsed, ref byte* ptr, byte* end) { if (!TrySliceWithLengthHeader(out var resultBytes, ref ptr, end)) { @@ -982,12 +1087,14 @@ public static bool ReadDoubleWithLengthHeader(out double result, out bool parsed /// Current read head of the input RESP stream. /// Current end of the input RESP stream. /// True if input was complete, otherwise false. - /// Thrown if array length was invalid. + /// Thrown if the length header is negative. + /// Thrown if unexpected token is read. + /// Thrown if integer overflow occurs. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ReadPtrWithLengthHeader(ref byte* result, ref int len, ref byte* ptr, byte* end) + public static bool TryReadPtrWithLengthHeader(ref byte* result, ref int len, ref byte* ptr, byte* end) { // Parse RESP string header - if (!ReadUnsignedLengthHeader(out len, ref ptr, end)) + if (!TryReadUnsignedLengthHeader(out len, ref ptr, end)) { return false; } @@ -1012,7 +1119,10 @@ public static bool ReadPtrWithLengthHeader(ref byte* result, ref int len, ref by /// /// Read ASCII string without header until string terminator ('\r\n'). /// - public static bool ReadString(out string result, ref byte* ptr, byte* end) + /// If parsing was successful, contains the parsed string value. + /// The starting position in the RESP message. Will be advanced if parsing is successful. + /// The current end of the RESP message. + public static bool TryReadString(out string result, ref byte* ptr, byte* end) { result = null; @@ -1038,7 +1148,7 @@ public static bool ReadString(out string result, ref byte* ptr, byte* end) /// /// Read ASCII string as span without header until string terminator ('\r\n'). /// - public static bool ReadAsSpan(out ReadOnlySpan result, ref byte* ptr, byte* end) + public static bool TryReadAsSpan(out ReadOnlySpan result, ref byte* ptr, byte* end) { result = null; @@ -1064,7 +1174,7 @@ public static bool ReadAsSpan(out ReadOnlySpan result, ref byte* ptr, byte /// /// Read serialized data for migration /// - public static bool ReadSerializedSpanByte(ref byte* keyPtr, ref byte keyMetaDataSize, ref byte* valPtr, ref byte valMetaDataSize, ref byte* ptr, byte* end) + public static bool TryReadSerializedSpanByte(ref byte* keyPtr, ref byte keyMetaDataSize, ref byte* valPtr, ref byte valMetaDataSize, ref byte* ptr, byte* end) { //1. safe read ksize if (ptr + sizeof(int) > end) @@ -1098,7 +1208,7 @@ public static bool ReadSerializedSpanByte(ref byte* keyPtr, ref byte keyMetaData /// /// Read serialized data for migration /// - public static bool ReadSerializedData(out byte[] key, out byte[] value, out long expiration, ref byte* ptr, byte* end) + public static bool TryReadSerializedData(out byte[] key, out byte[] value, out long expiration, ref byte* ptr, byte* end) { expiration = -1; key = null; diff --git a/libs/common/RespWriteUtils.cs b/libs/common/RespWriteUtils.cs index 16ea6ce641..714b8fe9af 100644 --- a/libs/common/RespWriteUtils.cs +++ b/libs/common/RespWriteUtils.cs @@ -8,7 +8,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; -using Tsavorite.core; namespace Garnet.common { @@ -18,41 +17,41 @@ namespace Garnet.common public static unsafe class RespWriteUtils { /// - /// Write map length + /// Writes a map length /// - public static bool WriteMapLength(int len, ref byte* curr, byte* end) + public static bool TryWriteMapLength(int len, ref byte* curr, byte* end) { - var numDigits = NumUtils.NumDigits(len); + var numDigits = NumUtils.CountDigits(len); var totalLen = 1 + numDigits + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'%'; - NumUtils.IntToBytes(len, numDigits, ref curr); + NumUtils.WriteInt32(len, numDigits, ref curr); WriteNewline(ref curr); return true; } /// - /// Write push type length + /// Writes a push type length /// - public static bool WritePushLength(int len, ref byte* curr, byte* end) + public static bool TryWritePushLength(int len, ref byte* curr, byte* end) { - var numDigits = NumUtils.NumDigits(len); + var numDigits = NumUtils.CountDigits(len); var totalLen = 1 + numDigits + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'>'; - NumUtils.IntToBytes(len, numDigits, ref curr); + NumUtils.WriteInt32(len, numDigits, ref curr); WriteNewline(ref curr); return true; } /// - /// Write bulk string length header, padded to specified total length (including protocol bytes) + /// Writes a bulk string length header, padded to specified total length (including protocol bytes) /// - public static bool WritePaddedBulkStringLength(int len, int paddedLen, ref byte* curr, byte* end) + public static bool TryWritePaddedBulkStringLength(int len, int paddedLen, ref byte* curr, byte* end) { - var numDigits = NumUtils.NumDigits(len); + var numDigits = NumUtils.CountDigits(len); var totalLen = 1 + numDigits + 2; Debug.Assert(totalLen <= paddedLen); if (paddedLen > (int)(end - curr)) @@ -60,46 +59,46 @@ public static bool WritePaddedBulkStringLength(int len, int paddedLen, ref byte* *curr++ = (byte)'$'; for (int i = 0; i < paddedLen - totalLen; i++) *curr++ = (byte)'0'; - NumUtils.IntToBytes(len, numDigits, ref curr); + NumUtils.WriteInt32(len, numDigits, ref curr); WriteNewline(ref curr); return true; } /// - /// Write array length + /// Writes an array length /// - public static bool WriteArrayLength(int len, ref byte* curr, byte* end) + public static bool TryWriteArrayLength(int len, ref byte* curr, byte* end) { - var numDigits = NumUtils.NumDigits(len); + var numDigits = NumUtils.CountDigits(len); var totalLen = 1 + numDigits + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'*'; - NumUtils.IntToBytes(len, numDigits, ref curr); + NumUtils.WriteInt32(len, numDigits, ref curr); WriteNewline(ref curr); return true; } - public static bool WriteArrayLength(int len, ref byte* curr, byte* end, out int numDigits, out int totalLen) + public static bool TryWriteArrayLength(int len, ref byte* curr, byte* end, out int numDigits, out int totalLen) { - numDigits = NumUtils.NumDigits(len); + numDigits = NumUtils.CountDigits(len); totalLen = 1 + numDigits + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'*'; - NumUtils.IntToBytes(len, numDigits, ref curr); + NumUtils.WriteInt32(len, numDigits, ref curr); WriteNewline(ref curr); return true; } /// - /// Write array item + /// Writes an array item /// - public static bool WriteArrayItem(long integer, ref byte* curr, byte* end) + public static bool TryWriteArrayItem(long integer, ref byte* curr, byte* end) { - var integerLen = NumUtils.NumDigitsInLong(integer); + var integerLen = NumUtils.CountDigits(integer); var sign = (byte)(integer < 0 ? 1 : 0); - var integerLenLen = NumUtils.NumDigits(sign + integerLen); + var integerLenLen = NumUtils.CountDigits(sign + integerLen); // $[integerLen]\r\n[integer]\r\n var totalLen = 1 + integerLenLen + 2 + sign + integerLen + 2; @@ -107,18 +106,18 @@ public static bool WriteArrayItem(long integer, ref byte* curr, byte* end) return false; *curr++ = (byte)'$'; - NumUtils.IntToBytes(sign + integerLen, integerLenLen, ref curr); + NumUtils.WriteInt32(sign + integerLen, integerLenLen, ref curr); WriteNewline(ref curr); - NumUtils.LongToBytes(integer, integerLen, ref curr); + NumUtils.WriteInt64(integer, integerLen, ref curr); WriteNewline(ref curr); return true; } /// - /// Write null + /// Writes a null /// - public static bool WriteNull(ref byte* curr, byte* end) + public static bool TryWriteNull(ref byte* curr, byte* end) { if (5 > (int)(end - curr)) return false; @@ -129,9 +128,9 @@ public static bool WriteNull(ref byte* curr, byte* end) } /// - /// Write null array + /// Writes a null array /// - public static bool WriteNullArray(ref byte* curr, byte* end) + public static bool TryWriteNullArray(ref byte* curr, byte* end) { if (5 > (int)(end - curr)) return false; @@ -142,10 +141,10 @@ public static bool WriteNullArray(ref byte* curr, byte* end) } /// - /// Write simple string + /// Writes a simple string /// /// An ASCII encoded simple string. The string mustn't contain a CR (\r) or LF (\n) bytes. - public static bool WriteSimpleString(ReadOnlySpan simpleString, ref byte* curr, byte* end) + public static bool TryWriteSimpleString(ReadOnlySpan simpleString, ref byte* curr, byte* end) { // Simple strings are of the form "+OK\r\n" var totalLen = 1 + simpleString.Length + 2; @@ -163,7 +162,7 @@ public static bool WriteSimpleString(ReadOnlySpan simpleString, ref byte* /// Write simple string /// /// An ASCII simple string. The string mustn't contain a CR (\r) or LF (\n) characters. - public static bool WriteSimpleString(ReadOnlySpan simpleString, ref byte* curr, byte* end) + public static bool TryWriteSimpleString(ReadOnlySpan simpleString, ref byte* curr, byte* end) { // Simple strings are of the form "+OK\r\n" int totalLen = 1 + simpleString.Length + 2; @@ -178,18 +177,18 @@ public static bool WriteSimpleString(ReadOnlySpan simpleString, ref byte* } /// - /// Write a long as a simple string + /// Write a signed 64-bit integer as a simple string /// - public static bool WriteLongAsSimpleString(long value, ref byte* curr, byte* end) + public static bool TryWriteInt64AsSimpleString(long value, ref byte* curr, byte* end) { // Simple strings are of the form "+cc\r\n" - var longLength = NumUtils.NumDigitsInLong(value); + var longLength = NumUtils.CountDigits(value); var totalLen = 1 + longLength + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'+'; - NumUtils.LongToBytes(value, longLength, ref curr); + NumUtils.WriteInt64(value, longLength, ref curr); WriteNewline(ref curr); return true; } @@ -198,7 +197,7 @@ public static bool WriteLongAsSimpleString(long value, ref byte* curr, byte* end /// Write simple error /// /// An ASCII encoded error string. The string mustn't contain a CR (\r) or LF (\n) bytes. - public static bool WriteError(ReadOnlySpan errorString, ref byte* curr, byte* end) + public static bool TryWriteError(ReadOnlySpan errorString, ref byte* curr, byte* end) { var totalLen = 1 + errorString.Length + 2; if (totalLen > (int)(end - curr)) @@ -215,7 +214,7 @@ public static bool WriteError(ReadOnlySpan errorString, ref byte* curr, by /// Write simple error /// /// An ASCII encoded error string. The string mustn't contain a CR (\r) or LF (\n) bytes. - public static bool WriteError(ReadOnlySpan errorString, ref MemoryResult output) + public static bool TryWriteError(ReadOnlySpan errorString, ref MemoryResult output) { var totalLen = 1 + errorString.Length + 2; output.MemoryOwner = MemoryPool.Shared.Rent(totalLen); @@ -236,7 +235,7 @@ public static bool WriteError(ReadOnlySpan errorString, ref MemoryResult /// An ASCII error string. The string mustn't contain a CR (\r) or LF (\n) characters. - public static bool WriteError(ReadOnlySpan errorString, ref byte* curr, byte* end) + public static bool TryWriteError(ReadOnlySpan errorString, ref byte* curr, byte* end) { var totalLen = 1 + errorString.Length + 2; if (totalLen > (int)(end - curr)) @@ -253,7 +252,7 @@ public static bool WriteError(ReadOnlySpan errorString, ref byte* curr, by /// Writes the contents of as byte array to /// /// if the could be written to ; otherwise. - public static bool WriteDirect(ReadOnlySpan span, ref byte* curr, byte* end) + public static bool TryWriteDirect(ReadOnlySpan span, ref byte* curr, byte* end) { if (span.Length > (int)(end - curr)) return false; @@ -267,7 +266,7 @@ public static bool WriteDirect(ReadOnlySpan span, ref byte* curr, byte* en /// Encodes the as ASCII to /// /// if the could be written to ; otherwise. - public static bool WriteAsciiDirect(ReadOnlySpan span, ref byte* curr, byte* end) + public static bool TryWriteAsciiDirect(ReadOnlySpan span, ref byte* curr, byte* end) { if (span.Length > (int)(end - curr)) return false; @@ -280,7 +279,7 @@ public static bool WriteAsciiDirect(ReadOnlySpan span, ref byte* curr, byt /// /// Write struct directly /// - public static bool WriteDirect(ref T item, ref byte* curr, byte* end) where T : unmanaged + public static bool TryWriteDirect(ref T item, ref byte* curr, byte* end) where T : unmanaged { int totalLen = sizeof(T); if (totalLen > (int)(end - curr)) @@ -293,15 +292,15 @@ public static bool WriteDirect(ref T item, ref byte* curr, byte* end) where T /// /// Write length header of bulk string /// - public static bool WriteBulkStringLength(ReadOnlySpan item, ref byte* curr, byte* end) + public static bool TryWriteBulkStringLength(ReadOnlySpan item, ref byte* curr, byte* end) { - var itemDigits = NumUtils.NumDigits(item.Length); + var itemDigits = NumUtils.CountDigits(item.Length); var totalLen = 1 + itemDigits + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'$'; - NumUtils.IntToBytes(item.Length, itemDigits, ref curr); + NumUtils.WriteInt32(item.Length, itemDigits, ref curr); WriteNewline(ref curr); return true; } @@ -309,15 +308,15 @@ public static bool WriteBulkStringLength(ReadOnlySpan item, ref byte* curr /// /// Write bulk string /// - public static bool WriteBulkString(ReadOnlySpan item, ref byte* curr, byte* end) + public static bool TryWriteBulkString(ReadOnlySpan item, ref byte* curr, byte* end) { - var itemDigits = NumUtils.NumDigits(item.Length); + var itemDigits = NumUtils.CountDigits(item.Length); int totalLen = 1 + itemDigits + 2 + item.Length + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'$'; - NumUtils.IntToBytes(item.Length, itemDigits, ref curr); + NumUtils.WriteInt32(item.Length, itemDigits, ref curr); WriteNewline(ref curr); item.CopyTo(new Span(curr, item.Length)); curr += item.Length; @@ -328,15 +327,15 @@ public static bool WriteBulkString(ReadOnlySpan item, ref byte* curr, byte /// /// Encodes the as ASCII bulk string to /// - public static bool WriteAsciiBulkString(ReadOnlySpan chars, ref byte* curr, byte* end) + public static bool TryWriteAsciiBulkString(ReadOnlySpan chars, ref byte* curr, byte* end) { - var itemDigits = NumUtils.NumDigits(chars.Length); + var itemDigits = NumUtils.CountDigits(chars.Length); var totalLen = 1 + itemDigits + 2 + chars.Length + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'$'; - NumUtils.IntToBytes(chars.Length, itemDigits, ref curr); + NumUtils.WriteInt32(chars.Length, itemDigits, ref curr); WriteNewline(ref curr); var bytesWritten = Encoding.ASCII.GetBytes(chars, new Span(curr, chars.Length)); curr += bytesWritten; @@ -347,18 +346,18 @@ public static bool WriteAsciiBulkString(ReadOnlySpan chars, ref byte* curr /// /// Encodes the as UTF8 bulk string to /// - public static bool WriteUtf8BulkString(ReadOnlySpan chars, ref byte* curr, byte* end) + public static bool TryWriteUtf8BulkString(ReadOnlySpan chars, ref byte* curr, byte* end) { // Calculate the amount of bytes it takes to encoded the UTF16 string as UTF8 var encodedByteCount = Encoding.UTF8.GetByteCount(chars); - var itemDigits = NumUtils.NumDigits(encodedByteCount); + var itemDigits = NumUtils.CountDigits(encodedByteCount); var totalLen = 1 + itemDigits + 2 + encodedByteCount + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'$'; - NumUtils.IntToBytes(encodedByteCount, itemDigits, ref curr); + NumUtils.WriteInt32(encodedByteCount, itemDigits, ref curr); WriteNewline(ref curr); var bytesWritten = Encoding.UTF8.GetBytes(chars, new Span(curr, encodedByteCount)); curr += bytesWritten; @@ -369,7 +368,7 @@ public static bool WriteUtf8BulkString(ReadOnlySpan chars, ref byte* curr, /// /// Write new line /// - public static bool WriteNewLine(ref byte* curr, byte* end) + public static bool TryWriteNewLine(ref byte* curr, byte* end) { var totalLen = 2; if (totalLen > (int)(end - curr)) @@ -383,15 +382,15 @@ public static bool WriteNewLine(ref byte* curr, byte* end) /// Get length of bulk string /// public static int GetBulkStringLength(int length) - => 1 + NumUtils.NumDigits(length) + 2 + length + 2; + => 1 + NumUtils.CountDigits(length) + 2 + length + 2; /// /// Write integer /// - public static bool WriteInteger(int integer, ref byte* curr, byte* end) + public static bool TryWriteInt32(int value, ref byte* curr, byte* end) { - var integerLen = NumUtils.NumDigitsInLong(integer); - var sign = (byte)(integer < 0 ? 1 : 0); + var integerLen = NumUtils.CountDigits((long)value); + var sign = (byte)(value < 0 ? 1 : 0); //:integer\r\n var totalLen = 1 + sign + integerLen + 2; @@ -399,7 +398,7 @@ public static bool WriteInteger(int integer, ref byte* curr, byte* end) return false; *curr++ = (byte)':'; - NumUtils.IntToBytes(integer, integerLen, ref curr); + NumUtils.WriteInt32(value, integerLen, ref curr); WriteNewline(ref curr); return true; } @@ -407,10 +406,10 @@ public static bool WriteInteger(int integer, ref byte* curr, byte* end) /// /// Write integer /// - public static bool WriteInteger(long integer, ref byte* curr, byte* end) + public static bool TryWriteInt64(long value, ref byte* curr, byte* end) { - var integerLen = NumUtils.NumDigitsInLong(integer); - var sign = (byte)(integer < 0 ? 1 : 0); + var integerLen = NumUtils.CountDigits(value); + var sign = (byte)(value < 0 ? 1 : 0); //:integer\r\n var totalLen = 1 + sign + integerLen + 2; @@ -418,7 +417,7 @@ public static bool WriteInteger(long integer, ref byte* curr, byte* end) return false; *curr++ = (byte)':'; - NumUtils.LongToBytes(integer, integerLen, ref curr); + NumUtils.WriteInt64(value, integerLen, ref curr); WriteNewline(ref curr); return true; } @@ -426,10 +425,10 @@ public static bool WriteInteger(long integer, ref byte* curr, byte* end) /// /// Write integer /// - public static bool WriteInteger(long integer, ref byte* curr, byte* end, out int integerLen, out int totalLen) + public static bool TryWriteInt64(long value, ref byte* curr, byte* end, out int integerLen, out int totalLen) { - integerLen = NumUtils.NumDigitsInLong(integer); - byte sign = (byte)(integer < 0 ? 1 : 0); + integerLen = NumUtils.CountDigits(value); + byte sign = (byte)(value < 0 ? 1 : 0); //:integer\r\n totalLen = 1 + sign + integerLen + 2; @@ -437,7 +436,7 @@ public static bool WriteInteger(long integer, ref byte* curr, byte* end, out int return false; *curr++ = (byte)':'; - NumUtils.LongToBytes(integer, integerLen, ref curr); + NumUtils.WriteInt64(value, integerLen, ref curr); WriteNewline(ref curr); return true; } @@ -445,7 +444,7 @@ public static bool WriteInteger(long integer, ref byte* curr, byte* end, out int /// /// Write integer from bytes /// - public static bool WriteIntegerFromBytes(ReadOnlySpan integerBytes, ref byte* curr, byte* end) + public static bool TryWriteIntegerFromBytes(ReadOnlySpan integerBytes, ref byte* curr, byte* end) { int totalLen = 1 + integerBytes.Length + 2; if ((int)(end - curr) < totalLen) @@ -459,14 +458,14 @@ public static bool WriteIntegerFromBytes(ReadOnlySpan integerBytes, ref by } /// - /// Write integer as bulk string + /// Write a signed 32-bit integer as bulk string /// - public static bool WriteIntegerAsBulkString(int integer, ref byte* curr, byte* end) + public static bool TryWriteInt32AsBulkString(int value, ref byte* curr, byte* end) { - var integerLen = NumUtils.NumDigitsInLong(integer); - var sign = (byte)(integer < 0 ? 1 : 0); + var integerLen = NumUtils.CountDigits((long)value); + var sign = (byte)(value < 0 ? 1 : 0); - var integerLenSize = NumUtils.NumDigits(integerLen + sign); + var integerLenSize = NumUtils.CountDigits(integerLen + sign); //$size\r\ninteger\r\n var totalLen = 1 + integerLenSize + 2 + sign + integerLen + 2; @@ -474,22 +473,22 @@ public static bool WriteIntegerAsBulkString(int integer, ref byte* curr, byte* e return false; *curr++ = (byte)'$'; - NumUtils.IntToBytes(integerLen + sign, integerLenSize, ref curr); + NumUtils.WriteInt32(integerLen + sign, integerLenSize, ref curr); WriteNewline(ref curr); - NumUtils.IntToBytes(integer, integerLen, ref curr); + NumUtils.WriteInt32(value, integerLen, ref curr); WriteNewline(ref curr); return true; } /// - /// Write integer as bulk string + /// Write a signed 64-bit integer as bulk string /// - public static bool WriteIntegerAsBulkString(long integer, ref byte* curr, byte* end, out int totalLen) + public static bool TryWriteInt64AsBulkString(long integer, ref byte* curr, byte* end, out int totalLen) { - var integerLen = NumUtils.NumDigitsInLong(integer); + var integerLen = NumUtils.CountDigits(integer); var sign = (byte)(integer < 0 ? 1 : 0); - var integerLenSize = NumUtils.NumDigits(integerLen + sign); + var integerLenSize = NumUtils.CountDigits(integerLen + sign); //$size\r\ninteger\r\n totalLen = 1 + integerLenSize + 2 + sign + integerLen + 2; @@ -497,9 +496,9 @@ public static bool WriteIntegerAsBulkString(long integer, ref byte* curr, byte* return false; *curr++ = (byte)'$'; - NumUtils.IntToBytes(integerLen + sign, integerLenSize, ref curr); + NumUtils.WriteInt32(integerLen + sign, integerLenSize, ref curr); WriteNewline(ref curr); - NumUtils.LongToBytes(integer, integerLen, ref curr); + NumUtils.WriteInt64(integer, integerLen, ref curr); WriteNewline(ref curr); return true; } @@ -509,10 +508,10 @@ public static bool WriteIntegerAsBulkString(long integer, ref byte* curr, byte* /// public static int GetIntegerAsBulkStringLength(int integer) { - var integerLen = NumUtils.NumDigitsInLong(integer); + var integerLen = NumUtils.CountDigits((long)integer); var sign = (byte)(integer < 0 ? 1 : 0); - var integerLenSize = NumUtils.NumDigits(integerLen + sign); + var integerLenSize = NumUtils.CountDigits(integerLen + sign); //$size\r\ninteger\r\n return 1 + integerLenSize + 2 + sign + integerLen + 2; @@ -538,13 +537,13 @@ public static bool TryWriteDoubleBulkString(double value, ref byte* curr, byte* if (!Utf8Formatter.TryFormat(value, buffer, out var bytesWritten, format: default)) return false; - var itemDigits = NumUtils.NumDigits(bytesWritten); + var itemDigits = NumUtils.CountDigits(bytesWritten); int totalLen = 1 + itemDigits + 2 + bytesWritten + 2; if (totalLen > (int)(end - curr)) return false; *curr++ = (byte)'$'; - NumUtils.IntToBytes(bytesWritten, itemDigits, ref curr); + NumUtils.WriteInt32(bytesWritten, itemDigits, ref curr); WriteNewline(ref curr); buffer.Slice(0, bytesWritten).CopyTo(new Span(curr, bytesWritten)); curr += bytesWritten; @@ -572,7 +571,7 @@ public static bool TryWriteDoubleNumeric(double value, ref byte* curr, byte* end if (!Utf8Formatter.TryFormat(value, buffer, out var bytesWritten, format: default)) return false; - var itemDigits = NumUtils.NumDigits(bytesWritten); + var itemDigits = NumUtils.CountDigits(bytesWritten); int totalLen = 1 + bytesWritten + 2; if (totalLen > (int)(end - curr)) return false; @@ -651,13 +650,13 @@ private static bool TryWriteNaN_Numeric(double value, ref byte* curr, byte* end) /// /// /// - public static bool WriteScanOutputHeader(long cursor, ref byte* curr, byte* end) + public static bool TryWriteScanOutputHeader(long cursor, ref byte* curr, byte* end) { - if (!WriteArrayLength(2, ref curr, end)) + if (!TryWriteArrayLength(2, ref curr, end)) return false; // Cursor value - if (!WriteIntegerAsBulkString((int)cursor, ref curr, end)) + if (!TryWriteInt32AsBulkString((int)cursor, ref curr, end)) return false; return true; @@ -666,7 +665,7 @@ public static bool WriteScanOutputHeader(long cursor, ref byte* curr, byte* end) /// /// Write empty array /// - public static bool WriteEmptyArray(ref byte* curr, byte* end) + public static bool TryWriteEmptyArray(ref byte* curr, byte* end) { if (4 > (int)(end - curr)) return false; @@ -678,9 +677,9 @@ public static bool WriteEmptyArray(ref byte* curr, byte* end) /// /// Write an array with len number of null elements /// - public static bool WriteArrayWithNullElements(int len, ref byte* curr, byte* end) + public static bool TryWriteArrayWithNullElements(int len, ref byte* curr, byte* end) { - var numDigits = NumUtils.NumDigits(len); + var numDigits = NumUtils.CountDigits(len); var totalLen = 1 + numDigits + 2; totalLen += len * 5; // 5 is the length of $-1\r\n @@ -688,11 +687,11 @@ public static bool WriteArrayWithNullElements(int len, ref byte* curr, byte* end return false; *curr++ = (byte)'*'; - NumUtils.IntToBytes(len, numDigits, ref curr); + NumUtils.WriteInt32(len, numDigits, ref curr); WriteNewline(ref curr); for (var i = 0; i < len; i++) { - if (!WriteNull(ref curr, end)) + if (!TryWriteNull(ref curr, end)) return false; } return true; @@ -700,7 +699,7 @@ public static bool WriteArrayWithNullElements(int len, ref byte* curr, byte* end /// /// Writes an array consisting of an ETag followed by a Bulk string value into the buffer. - /// NOTE: Caller should make sure there is enough space in the buffer for sending the etag, and value array. + /// NOTE: Caller should make sure there is enough space in the buffer for sending the etag, and value array. Otherwise, this will quietly fail. /// /// etag value to write in the array /// value to write in the array @@ -710,23 +709,23 @@ public static bool WriteArrayWithNullElements(int len, ref byte* curr, byte* end public static void WriteEtagValArray(long etag, ref ReadOnlySpan value, ref byte* curr, byte* end, bool writeDirect) { // Writes a Resp encoded Array of Integer for ETAG as first element, and bulk string for value as second element - RespWriteUtils.WriteArrayLength(2, ref curr, end); - RespWriteUtils.WriteInteger(etag, ref curr, end); + RespWriteUtils.TryWriteArrayLength(2, ref curr, end); + RespWriteUtils.TryWriteInt64(etag, ref curr, end); if (writeDirect) - RespWriteUtils.WriteDirect(value, ref curr, end); + RespWriteUtils.TryWriteDirect(value, ref curr, end); else - RespWriteUtils.WriteBulkString(value, ref curr, end); + RespWriteUtils.TryWriteBulkString(value, ref curr, end); } /// - /// Write newline (\r\n) to + /// Writes newline (\r\n) to /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void WriteNewline(ref byte* curr) => WriteBytes(ref curr, "\r\n"u8); /// - /// Write to as type sized value. + /// Writes to as type sized value. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteBytes(ref byte* curr, ReadOnlySpan bytes) diff --git a/libs/server/ArgSlice/ScratchBufferManager.cs b/libs/server/ArgSlice/ScratchBufferManager.cs index 42fa904690..1a892820b9 100644 --- a/libs/server/ArgSlice/ScratchBufferManager.cs +++ b/libs/server/ArgSlice/ScratchBufferManager.cs @@ -126,9 +126,9 @@ public ArgSlice FormatScratchAsResp(int headerSize, ArgSlice arg1, ArgSlice arg2 retVal.Span[..headerSize].Clear(); // Clear the header byte* ptr = scratchBufferHead + scratchBufferOffset + headerSize; - var success = RespWriteUtils.WriteBulkString(arg1.Span, ref ptr, scratchBufferHead + scratchBuffer.Length); + var success = RespWriteUtils.TryWriteBulkString(arg1.Span, ref ptr, scratchBufferHead + scratchBuffer.Length); Debug.Assert(success); - success = RespWriteUtils.WriteBulkString(arg2.Span, ref ptr, scratchBufferHead + scratchBuffer.Length); + success = RespWriteUtils.TryWriteBulkString(arg2.Span, ref ptr, scratchBufferHead + scratchBuffer.Length); Debug.Assert(success); scratchBufferOffset += length; @@ -148,7 +148,7 @@ public ArgSlice FormatScratchAsResp(int headerSize, ArgSlice arg1) retVal.Span[..headerSize].Clear(); // Clear the header byte* ptr = scratchBufferHead + scratchBufferOffset + headerSize; - var success = RespWriteUtils.WriteBulkString(arg1.Span, ref ptr, scratchBufferHead + scratchBuffer.Length); + var success = RespWriteUtils.TryWriteBulkString(arg1.Span, ref ptr, scratchBufferHead + scratchBuffer.Length); Debug.Assert(success); scratchBufferOffset += length; @@ -235,14 +235,14 @@ public void StartCommand(ReadOnlySpan cmd, int argCount) var ptr = scratchBufferHead + scratchBufferOffset; - while (!RespWriteUtils.WriteArrayLength(argCount + 1, ref ptr, scratchBufferHead + scratchBuffer.Length)) + while (!RespWriteUtils.TryWriteArrayLength(argCount + 1, ref ptr, scratchBufferHead + scratchBuffer.Length)) { ExpandScratchBuffer(scratchBuffer.Length + 1); ptr = scratchBufferHead + scratchBufferOffset; } scratchBufferOffset = (int)(ptr - scratchBufferHead); - while (!RespWriteUtils.WriteBulkString(cmd, ref ptr, scratchBufferHead + scratchBuffer.Length)) + while (!RespWriteUtils.TryWriteBulkString(cmd, ref ptr, scratchBufferHead + scratchBuffer.Length)) { ExpandScratchBuffer(scratchBuffer.Length + 1); ptr = scratchBufferHead + scratchBufferOffset; @@ -257,7 +257,7 @@ public void WriteNullArgument() { var ptr = scratchBufferHead + scratchBufferOffset; - while (!RespWriteUtils.WriteNull(ref ptr, scratchBufferHead + scratchBuffer.Length)) + while (!RespWriteUtils.TryWriteNull(ref ptr, scratchBufferHead + scratchBuffer.Length)) { ExpandScratchBuffer(scratchBuffer.Length + 1); ptr = scratchBufferHead + scratchBufferOffset; @@ -273,7 +273,7 @@ public void WriteArgument(ReadOnlySpan arg) { var ptr = scratchBufferHead + scratchBufferOffset; - while (!RespWriteUtils.WriteBulkString(arg, ref ptr, scratchBufferHead + scratchBuffer.Length)) + while (!RespWriteUtils.TryWriteBulkString(arg, ref ptr, scratchBufferHead + scratchBuffer.Length)) { ExpandScratchBuffer(scratchBuffer.Length + 1); ptr = scratchBufferHead + scratchBufferOffset; @@ -290,7 +290,7 @@ public void WriteArgument(ReadOnlySpan arg) /// /// static int GetRespFormattedStringLength(ArgSlice slice) - => 1 + NumUtils.NumDigits(slice.Length) + 2 + slice.Length + 2; + => 1 + NumUtils.CountDigits(slice.Length) + 2 + slice.Length + 2; void ExpandScratchBufferIfNeeded(int newLength) { diff --git a/libs/server/Custom/CustomCommandUtils.cs b/libs/server/Custom/CustomCommandUtils.cs index d1acc7b4f7..3be9ba56b9 100644 --- a/libs/server/Custom/CustomCommandUtils.cs +++ b/libs/server/Custom/CustomCommandUtils.cs @@ -82,7 +82,7 @@ public static unsafe void WriteBulkString(ref (IMemoryOwner, int) output, { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteBulkString(bulkString, ref curr, ptr + len); + var success = RespWriteUtils.TryWriteBulkString(bulkString, ref curr, ptr + len); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } } @@ -100,7 +100,7 @@ public static unsafe void WriteError(ref (IMemoryOwner, int) output, strin { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteError(bytes, ref curr, ptr + len); + var success = RespWriteUtils.TryWriteError(bytes, ref curr, ptr + len); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } output.Item2 = len; @@ -119,7 +119,7 @@ public static unsafe void WriteNullBulkString(ref (IMemoryOwner, int) outp { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteNull(ref curr, ptr + len); + var success = RespWriteUtils.TryWriteNull(ref curr, ptr + len); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } } @@ -137,7 +137,7 @@ public static unsafe void WriteSimpleString(ref (IMemoryOwner, int) output { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteSimpleString(bytes, ref curr, ptr + len); + var success = RespWriteUtils.TryWriteSimpleString(bytes, ref curr, ptr + len); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } output.Item2 = len; diff --git a/libs/server/Custom/CustomFunctions.cs b/libs/server/Custom/CustomFunctions.cs index df5976baf1..1aafef8b96 100644 --- a/libs/server/Custom/CustomFunctions.cs +++ b/libs/server/Custom/CustomFunctions.cs @@ -43,7 +43,7 @@ protected static unsafe void WriteSimpleString(ref (IMemoryOwner, int) out { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteSimpleString(simpleString, ref curr, ptr + len); + var success = RespWriteUtils.TryWriteSimpleString(simpleString, ref curr, ptr + len); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } output.Item2 = len; @@ -65,7 +65,7 @@ protected static unsafe void WriteSimpleString(ref MemoryResult output, Re /// protected static unsafe void WriteBulkStringArray(ref MemoryResult output, params ArgSlice[] values) { - var totalLen = 1 + NumUtils.NumDigits(values.Length) + 2; + var totalLen = 1 + NumUtils.CountDigits(values.Length) + 2; for (var i = 0; i < values.Length; i++) totalLen += RespWriteUtils.GetBulkStringLength(values[i].Length); @@ -77,12 +77,12 @@ protected static unsafe void WriteBulkStringArray(ref MemoryResult output, { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteArrayLength(values.Length, ref curr, ptr + totalLen); + var success = RespWriteUtils.TryWriteArrayLength(values.Length, ref curr, ptr + totalLen); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); for (var i = 0; i < values.Length; i++) { // NOTE: Expected to always have enough space to write into pre-allocated buffer - success = RespWriteUtils.WriteBulkString(values[i].Span, ref curr, ptr + totalLen); + success = RespWriteUtils.TryWriteBulkString(values[i].Span, ref curr, ptr + totalLen); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } } @@ -93,7 +93,7 @@ protected static unsafe void WriteBulkStringArray(ref MemoryResult output, /// protected static unsafe void WriteBulkStringArray(ref MemoryResult output, List values) { - var totalLen = 1 + NumUtils.NumDigits(values.Count) + 2; + var totalLen = 1 + NumUtils.CountDigits(values.Count) + 2; for (var i = 0; i < values.Count; i++) totalLen += RespWriteUtils.GetBulkStringLength(values[i].Length); @@ -105,12 +105,12 @@ protected static unsafe void WriteBulkStringArray(ref MemoryResult output, { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteArrayLength(values.Count, ref curr, ptr + totalLen); + var success = RespWriteUtils.TryWriteArrayLength(values.Count, ref curr, ptr + totalLen); Debug.Assert(success, "Insufficient response buffer space"); for (var i = 0; i < values.Count; i++) { // NOTE: Expected to always have enough space to write into pre-allocated buffer - success = RespWriteUtils.WriteBulkString(values[i].Span, ref curr, ptr + totalLen); + success = RespWriteUtils.TryWriteBulkString(values[i].Span, ref curr, ptr + totalLen); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } } @@ -141,7 +141,7 @@ protected static unsafe void WriteBulkString(ref (IMemoryOwner, int) outpu { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteBulkString(bulkString, ref curr, ptr + len); + var success = RespWriteUtils.TryWriteBulkString(bulkString, ref curr, ptr + len); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } } @@ -160,7 +160,7 @@ protected static unsafe void WriteNullBulkString(ref (IMemoryOwner, int) o { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteNull(ref curr, ptr + len); + var success = RespWriteUtils.TryWriteNull(ref curr, ptr + len); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } } @@ -178,7 +178,7 @@ protected static unsafe void WriteError(ref (IMemoryOwner, int) output, Re { var curr = ptr; // NOTE: Expected to always have enough space to write into pre-allocated buffer - var success = RespWriteUtils.WriteError(errorMessage, ref curr, ptr + len); + var success = RespWriteUtils.TryWriteError(errorMessage, ref curr, ptr + len); Debug.Assert(success, "Insufficient space in pre-allocated buffer"); } output.Item2 = len; diff --git a/libs/server/Custom/CustomRespCommands.cs b/libs/server/Custom/CustomRespCommands.cs index 1dd5f5b031..dbc671b5e9 100644 --- a/libs/server/Custom/CustomRespCommands.cs +++ b/libs/server/Custom/CustomRespCommands.cs @@ -32,7 +32,7 @@ private bool TryTransactionProc(byte id, CustomTransactionProcedure proc, int st if (output.MemoryOwner != null) SendAndReset(output.MemoryOwner, output.Length); else - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else @@ -41,7 +41,7 @@ private bool TryTransactionProc(byte id, CustomTransactionProcedure proc, int st if (output.MemoryOwner != null) SendAndReset(output.MemoryOwner, output.Length); else - while (!RespWriteUtils.WriteError($"ERR Transaction failed.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Transaction failed.", ref dcurr, dend)) SendAndReset(); } latencyMetrics?.Stop(LatencyMetricsType.TX_PROC_LAT); @@ -68,7 +68,7 @@ private void TryCustomProcedure(CustomProcedure proc, int startIdx = 0) if (output.MemoryOwner != null) SendAndReset(output.MemoryOwner, output.Length); else - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else @@ -76,7 +76,7 @@ private void TryCustomProcedure(CustomProcedure proc, int startIdx = 0) if (output.MemoryOwner != null) SendAndReset(output.MemoryOwner, output.Length); else - while (!RespWriteUtils.WriteError($"ERR Command failed.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Command failed.", ref dcurr, dend)) SendAndReset(); } } @@ -102,7 +102,7 @@ private bool TryCustomRawStringCommand(RespCommand cmd, long expirat if (output.Memory != null) SendAndReset(output.Memory, output.Length); else - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else @@ -115,13 +115,13 @@ private bool TryCustomRawStringCommand(RespCommand cmd, long expirat if (output.Memory != null) SendAndReset(output.Memory, output.Length); else - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { Debug.Assert(output.Memory == null); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } } @@ -154,14 +154,14 @@ private bool TryCustomObjectCommand(GarnetObjectType objType, byte s switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: if (output.SpanByteAndMemory.Memory != null) SendAndReset(output.SpanByteAndMemory.Memory, output.SpanByteAndMemory.Length); else - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); break; } @@ -177,16 +177,16 @@ private bool TryCustomObjectCommand(GarnetObjectType objType, byte s if (output.SpanByteAndMemory.Memory != null) SendAndReset(output.SpanByteAndMemory.Memory, output.SpanByteAndMemory.Length); else - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: Debug.Assert(output.SpanByteAndMemory.Memory == null); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } diff --git a/libs/server/Lua/LuaCommands.cs b/libs/server/Lua/LuaCommands.cs index f9a4df47f8..4359393aa8 100644 --- a/libs/server/Lua/LuaCommands.cs +++ b/libs/server/Lua/LuaCommands.cs @@ -56,7 +56,7 @@ private unsafe bool TryEVALSHA() if (runner == null) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NO_SCRIPT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NO_SCRIPT, ref dcurr, dend)) SendAndReset(); } else @@ -99,7 +99,7 @@ private unsafe bool TryEVAL() if (runner == null) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NO_SCRIPT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NO_SCRIPT, ref dcurr, dend)) SendAndReset(); } else @@ -127,7 +127,7 @@ private bool NetworkScriptExists() // Returns an array where each element is a 0 if the script does not exist, and a 1 if it does - while (!RespWriteUtils.WriteArrayLength(parseState.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(parseState.Count, ref dcurr, dend)) SendAndReset(); for (var shaIx = 0; shaIx < parseState.Count; shaIx++) @@ -145,7 +145,7 @@ private bool NetworkScriptExists() exists = storeWrapper.storeScriptCache.ContainsKey(sha1Arg) ? 1 : 0; } - while (!RespWriteUtils.WriteArrayItem(exists, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayItem(exists, ref dcurr, dend)) SendAndReset(); } @@ -187,7 +187,7 @@ private bool NetworkScriptFlush() // Flush session script cache sessionScriptCache.Clear(); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -229,7 +229,7 @@ private bool NetworkScriptLoad() _ = storeWrapper.storeScriptCache.TryAdd(digestOnHeap.Value, source.ToArray()); } - while (!RespWriteUtils.WriteBulkString(digest, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(digest, ref dcurr, dend)) SendAndReset(); } @@ -245,7 +245,7 @@ private bool CheckLuaEnabled() { if (!storeWrapper.serverOptions.EnableLua) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_LUA_DISABLED, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_LUA_DISABLED, ref dcurr, dend)) SendAndReset(); return false; @@ -266,7 +266,7 @@ private void ExecuteScript(int count, LuaRunner scriptRunner) catch (Exception ex) { logger?.LogError(ex, "Error executing Lua script"); - while (!RespWriteUtils.WriteError("ERR " + ex.Message, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR " + ex.Message, ref dcurr, dend)) SendAndReset(); } } diff --git a/libs/server/Lua/LuaRunner.cs b/libs/server/Lua/LuaRunner.cs index d9525df2da..315ff13e3b 100644 --- a/libs/server/Lua/LuaRunner.cs +++ b/libs/server/Lua/LuaRunner.cs @@ -433,7 +433,7 @@ public unsafe bool CompileForSession(RespServerSession session) var res = state.PCall(0, 0); if (res != LuaStatus.OK) { - while (!RespWriteUtils.WriteError("Internal Lua Error"u8, ref session.dcurr, session.dend)) + while (!RespWriteUtils.TryWriteError("Internal Lua Error"u8, ref session.dcurr, session.dend)) session.SendAndReset(); return false; @@ -506,7 +506,7 @@ private unsafe int CompileCommon(ref TResponse resp) state.KnownStringToBuffer(1, out var errorBuf); var errStr = $"Compilation error: {Encoding.UTF8.GetString(errorBuf)}"; - while (!RespWriteUtils.WriteError(errStr, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteError(errStr, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); } @@ -711,7 +711,7 @@ private unsafe int ProcessResponse(byte* ptr, int length) case (byte)'+': ptr++; length--; - if (RespReadUtils.ReadAsSpan(out var resultSpan, ref ptr, ptr + length)) + if (RespReadUtils.TryReadAsSpan(out var resultSpan, ref ptr, ptr + length)) { state.PushBuffer(resultSpan); return 1; @@ -719,7 +719,7 @@ private unsafe int ProcessResponse(byte* ptr, int length) goto default; case (byte)':': - if (RespReadUtils.Read64Int(out var number, ref ptr, ptr + length)) + if (RespReadUtils.TryReadInt64(out var number, ref ptr, ptr + length)) { state.PushInteger(number); return 1; @@ -729,7 +729,7 @@ private unsafe int ProcessResponse(byte* ptr, int length) case (byte)'-': ptr++; length--; - if (RespReadUtils.ReadAsSpan(out var errSpan, ref ptr, ptr + length)) + if (RespReadUtils.TryReadAsSpan(out var errSpan, ref ptr, ptr + length)) { if (errSpan.SequenceEqual(CmdStrings.RESP_ERR_GENERIC_UNK_CMD)) { @@ -752,7 +752,7 @@ private unsafe int ProcessResponse(byte* ptr, int length) return 1; } - else if (RespReadUtils.ReadSpanWithLengthHeader(out var bulkSpan, ref ptr, ptr + length)) + else if (RespReadUtils.TryReadSpanWithLengthHeader(out var bulkSpan, ref ptr, ptr + length)) { state.PushBuffer(bulkSpan); @@ -761,7 +761,7 @@ private unsafe int ProcessResponse(byte* ptr, int length) goto default; case (byte)'*': - if (RespReadUtils.ReadUnsignedArrayLength(out var itemCount, ref ptr, ptr + length)) + if (RespReadUtils.TryReadUnsignedArrayLength(out var itemCount, ref ptr, ptr + length)) { // Create the new table state.CreateTable(itemCount, 0); @@ -777,7 +777,7 @@ private unsafe int ProcessResponse(byte* ptr, int length) // See: https://redis.io/docs/latest/develop/interact/programmability/lua-api/#lua-to-resp2-type-conversion state.PushBoolean(false); } - else if (RespReadUtils.ReadSpanWithLengthHeader(out var strSpan, ref ptr, ptr + length)) + else if (RespReadUtils.TryReadSpanWithLengthHeader(out var strSpan, ref ptr, ptr + length)) { state.PushBuffer(strSpan); } @@ -831,7 +831,7 @@ public unsafe void RunForSession(int count, RespServerSession outerSession) var callRes = state.PCall(0, 0); if (callRes != LuaStatus.OK) { - while (!RespWriteUtils.WriteError("Internal Lua Error"u8, ref outerSession.dcurr, outerSession.dend)) + while (!RespWriteUtils.TryWriteError("Internal Lua Error"u8, ref outerSession.dcurr, outerSession.dend)) outerSession.SendAndReset(); return; @@ -1006,13 +1006,13 @@ static object MapRespToObject(ref byte* cur, byte* end) switch (*cur) { case (byte)'+': - var simpleStrRes = RespReadUtils.ReadSimpleString(out var simpleStr, ref cur, end); + var simpleStrRes = RespReadUtils.TryReadSimpleString(out var simpleStr, ref cur, end); Debug.Assert(simpleStrRes, "Should never fail"); return simpleStr; case (byte)':': - var readIntRes = RespReadUtils.Read64Int(out var int64, ref cur, end); + var readIntRes = RespReadUtils.TryReadInt64(out var int64, ref cur, end); Debug.Assert(readIntRes, "Should never fail"); return int64; @@ -1028,13 +1028,13 @@ static object MapRespToObject(ref byte* cur, byte* end) return null; } - var bulkStrRes = RespReadUtils.ReadStringResponseWithLengthHeader(out var bulkStr, ref cur, end); + var bulkStrRes = RespReadUtils.TryReadStringResponseWithLengthHeader(out var bulkStr, ref cur, end); Debug.Assert(bulkStrRes, "Should never fail"); return bulkStr; case (byte)'*': - var arrayLengthRes = RespReadUtils.ReadUnsignedArrayLength(out var itemCount, ref cur, end); + var arrayLengthRes = RespReadUtils.TryReadUnsignedArrayLength(out var itemCount, ref cur, end); Debug.Assert(arrayLengthRes, "Should never fail"); if (itemCount == 0) @@ -1279,7 +1279,7 @@ private unsafe void RunCommon(ref TResponse resp) if (state.StackTop == 0) { - while (!RespWriteUtils.WriteError("ERR An error occurred while invoking a Lua script"u8, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteError("ERR An error occurred while invoking a Lua script"u8, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); return; @@ -1292,7 +1292,7 @@ private unsafe void RunCommon(ref TResponse resp) if (errBuf.Length >= 4 && MemoryMarshal.Read("ERR "u8) == Unsafe.As(ref MemoryMarshal.GetReference(errBuf))) { // Response came back with a ERR, already - just pass it along - while (!RespWriteUtils.WriteError(errBuf, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteError(errBuf, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); } else @@ -1300,13 +1300,13 @@ private unsafe void RunCommon(ref TResponse resp) // Otherwise, this is probably a Lua error - and those aren't very descriptive // So slap some more information in - while (!RespWriteUtils.WriteDirect("-ERR Lua encountered an error: "u8, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteDirect("-ERR Lua encountered an error: "u8, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); - while (!RespWriteUtils.WriteDirect(errBuf, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteDirect(errBuf, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); - while (!RespWriteUtils.WriteDirect("\r\n"u8, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteDirect("\r\n"u8, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); } @@ -1318,7 +1318,7 @@ private unsafe void RunCommon(ref TResponse resp) { logger?.LogError("Got an unexpected number of values back from a pcall error {callRes}", callRes); - while (!RespWriteUtils.WriteError("ERR Unexpected error response"u8, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteError("ERR Unexpected error response"u8, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); state.ClearStack(); @@ -1335,7 +1335,7 @@ private unsafe void RunCommon(ref TResponse resp) // Write a null RESP value, remove the top value on the stack if there is one static void WriteNull(LuaRunner runner, ref TResponse resp) { - while (!RespWriteUtils.WriteNull(ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteNull(ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); // The stack _could_ be empty if we're writing a null, so check before popping @@ -1355,7 +1355,7 @@ static void WriteNumber(LuaRunner runner, ref TResponse resp) // See: https://redis.io/docs/latest/develop/interact/programmability/lua-api/#lua-to-resp2-type-conversion var num = (long)runner.state.CheckNumber(runner.state.StackTop); - while (!RespWriteUtils.WriteInteger(num, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteInt64(num, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); runner.state.Pop(1); @@ -1366,7 +1366,7 @@ static void WriteString(LuaRunner runner, ref TResponse resp) { runner.state.KnownStringToBuffer(runner.state.StackTop, out var buf); - while (!RespWriteUtils.WriteBulkString(buf, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteBulkString(buf, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); runner.state.Pop(1); @@ -1382,12 +1382,12 @@ static void WriteBoolean(LuaRunner runner, ref TResponse resp) // See: https://redis.io/docs/latest/develop/interact/programmability/lua-api/#lua-to-resp2-type-conversion if (runner.state.ToBoolean(runner.state.StackTop)) { - while (!RespWriteUtils.WriteInteger(1, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteInt32(1, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); } else { - while (!RespWriteUtils.WriteNull(ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteNull(ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); } @@ -1399,7 +1399,7 @@ static void WriteError(LuaRunner runner, ref TResponse resp) { runner.state.KnownStringToBuffer(runner.state.StackTop, out var errBuff); - while (!RespWriteUtils.WriteError(errBuff, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteError(errBuff, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); runner.state.Pop(1); @@ -1431,7 +1431,7 @@ static void WriteArray(LuaRunner runner, ref TResponse resp) } } - while (!RespWriteUtils.WriteArrayLength(trueLen, ref resp.BufferCur, resp.BufferEnd)) + while (!RespWriteUtils.TryWriteArrayLength(trueLen, ref resp.BufferCur, resp.BufferEnd)) resp.SendAndReset(); for (var i = 1; i <= trueLen; i++) diff --git a/libs/server/Metrics/Info/InfoCommand.cs b/libs/server/Metrics/Info/InfoCommand.cs index 4233a02175..c933a4cda3 100644 --- a/libs/server/Metrics/Info/InfoCommand.cs +++ b/libs/server/Metrics/Info/InfoCommand.cs @@ -44,7 +44,7 @@ private bool NetworkINFO() if (invalid) { - while (!RespWriteUtils.WriteError($"ERR Invalid section {invalidSection}. Try INFO HELP", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Invalid section {invalidSection}. Try INFO HELP", ref dcurr, dend)) SendAndReset(); return true; } @@ -57,7 +57,7 @@ private bool NetworkINFO() { if (storeWrapper.monitor != null) storeWrapper.monitor.resetEventFlags[InfoMetricsType.STATS] = true; - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else @@ -67,12 +67,12 @@ private bool NetworkINFO() var info = garnetInfo.GetRespInfo(sectionsArr, storeWrapper); if (!string.IsNullOrEmpty(info)) { - while (!RespWriteUtils.WriteAsciiBulkString(info, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(info, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } } @@ -83,11 +83,11 @@ private bool NetworkINFO() private void GetHelpMessage() { List sectionsHelp = InfoHelp.GetInfoTypeHelpMessage(); - while (!RespWriteUtils.WriteArrayLength(sectionsHelp.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(sectionsHelp.Count, ref dcurr, dend)) SendAndReset(); foreach (var sectionInfo in sectionsHelp) { - while (!RespWriteUtils.WriteAsciiBulkString(sectionInfo, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(sectionInfo, ref dcurr, dend)) SendAndReset(); } } diff --git a/libs/server/Metrics/Latency/RespLatencyCommands.cs b/libs/server/Metrics/Latency/RespLatencyCommands.cs index 9c64f7a544..918b21140c 100644 --- a/libs/server/Metrics/Latency/RespLatencyCommands.cs +++ b/libs/server/Metrics/Latency/RespLatencyCommands.cs @@ -19,17 +19,17 @@ private bool NetworkLatencyHelp() // No additional arguments if (parseState.Count != 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for LATENCY HELP.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for LATENCY HELP.", ref dcurr, dend)) SendAndReset(); } List latencyCommands = RespLatencyHelp.GetLatencyCommands(); - while (!RespWriteUtils.WriteArrayLength(latencyCommands.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(latencyCommands.Count, ref dcurr, dend)) SendAndReset(); foreach (string command in latencyCommands) { - while (!RespWriteUtils.WriteSimpleString(command, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString(command, ref dcurr, dend)) SendAndReset(); } @@ -68,14 +68,14 @@ private bool NetworkLatencyHistogram() if (invalid) { - while (!RespWriteUtils.WriteError($"ERR Invalid event {invalidEvent}. Try LATENCY HELP", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Invalid event {invalidEvent}. Try LATENCY HELP", ref dcurr, dend)) SendAndReset(); } else { var garnetLatencyMetrics = storeWrapper.monitor?.GlobalMetrics.globalLatencyMetrics; string response = garnetLatencyMetrics != null ? garnetLatencyMetrics.GetRespHistograms(events) : "*0\r\n"; - while (!RespWriteUtils.WriteAsciiDirect(response, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiDirect(response, ref dcurr, dend)) SendAndReset(); } @@ -114,7 +114,7 @@ private bool NetworkLatencyReset() if (invalid) { - while (!RespWriteUtils.WriteError($"ERR Invalid type {invalidEvent}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Invalid type {invalidEvent}", ref dcurr, dend)) SendAndReset(); } else @@ -125,7 +125,7 @@ private bool NetworkLatencyReset() storeWrapper.monitor.resetLatencyMetrics[e] = true; } - while (!RespWriteUtils.WriteInteger(events.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(events.Count, ref dcurr, dend)) SendAndReset(); } diff --git a/libs/server/Objects/Hash/HashObjectImpl.cs b/libs/server/Objects/Hash/HashObjectImpl.cs index 14f6a84a41..c4b41ba5b6 100644 --- a/libs/server/Objects/Hash/HashObjectImpl.cs +++ b/libs/server/Objects/Hash/HashObjectImpl.cs @@ -35,12 +35,12 @@ private void HashGet(ref ObjectInput input, ref SpanByteAndMemory output) if (TryGetValue(key, out var hashValue)) { - while (!RespWriteUtils.WriteBulkString(hashValue, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(hashValue, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -48,7 +48,7 @@ private void HashGet(ref ObjectInput input, ref SpanByteAndMemory output) } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -68,7 +68,7 @@ private void HashMultipleGet(ref ObjectInput input, ref SpanByteAndMemory output ObjectOutputHeader _output = default; try { - while (!RespWriteUtils.WriteArrayLength(input.parseState.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(input.parseState.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); for (var i = 0; i < input.parseState.Count; i++) @@ -77,12 +77,12 @@ private void HashMultipleGet(ref ObjectInput input, ref SpanByteAndMemory output if (TryGetValue(key, out var hashValue)) { - while (!RespWriteUtils.WriteBulkString(hashValue, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(hashValue, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -91,7 +91,7 @@ private void HashMultipleGet(ref ObjectInput input, ref SpanByteAndMemory output } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -115,12 +115,12 @@ private void HashGetAll(ref ObjectInput input, ref SpanByteAndMemory output) { if (respProtocolVersion < 3) { - while (!RespWriteUtils.WriteArrayLength(Count() * 2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(Count() * 2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { - while (!RespWriteUtils.WriteMapLength(Count(), ref curr, end)) + while (!RespWriteUtils.TryWriteMapLength(Count(), ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -133,15 +133,15 @@ private void HashGetAll(ref ObjectInput input, ref SpanByteAndMemory output) continue; } - while (!RespWriteUtils.WriteBulkString(item.Key, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item.Key, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteBulkString(item.Value, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item.Value, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -214,7 +214,7 @@ private void HashRandomField(ref ObjectInput input, ref SpanByteAndMemory output if (count == 0) // This can happen because of expiration but RMW operation haven't applied yet { - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); _output.result1 = 0; return; @@ -227,18 +227,18 @@ private void HashRandomField(ref ObjectInput input, ref SpanByteAndMemory output var indexes = RandomUtils.PickKRandomIndexes(count, absCount, seed, countParameter > 0); // Write the size of the array reply - while (!RespWriteUtils.WriteArrayLength(withValues ? absCount * 2 : absCount, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(withValues ? absCount * 2 : absCount, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var index in indexes) { var pair = ElementAt(index); - while (!RespWriteUtils.WriteBulkString(pair.Key, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(pair.Key, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (withValues) { - while (!RespWriteUtils.WriteBulkString(pair.Value, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(pair.Value, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -251,7 +251,7 @@ private void HashRandomField(ref ObjectInput input, ref SpanByteAndMemory output var count = Count(); if (count == 0) // This can happen because of expiration but RMW operation haven't applied yet { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); _output.result1 = 0; return; @@ -259,7 +259,7 @@ private void HashRandomField(ref ObjectInput input, ref SpanByteAndMemory output var index = RandomUtils.PickRandomIndex(count, seed); var pair = ElementAt(index); - while (!RespWriteUtils.WriteBulkString(pair.Key, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(pair.Key, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); countDone = 1; } @@ -268,7 +268,7 @@ private void HashRandomField(ref ObjectInput input, ref SpanByteAndMemory output } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -324,7 +324,7 @@ private void HashGetKeysOrValues(ref ObjectInput input, ref SpanByteAndMemory ou ObjectOutputHeader _output = default; try { - while (!RespWriteUtils.WriteArrayLength(count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); var isExpirable = HasExpirableItems(); @@ -338,12 +338,12 @@ private void HashGetKeysOrValues(ref ObjectInput input, ref SpanByteAndMemory ou if (HashOperation.HKEYS == op) { - while (!RespWriteUtils.WriteBulkString(item.Key, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item.Key, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { - while (!RespWriteUtils.WriteBulkString(item.Value, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item.Value, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } _output.result1++; @@ -351,7 +351,7 @@ private void HashGetKeysOrValues(ref ObjectInput input, ref SpanByteAndMemory ou } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -385,7 +385,7 @@ private void HashIncrement(ref ObjectInput input, ref SpanByteAndMemory output) { if (!NumUtils.TryParse(incrSlice.ReadOnlySpan, out int incr)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -396,7 +396,7 @@ private void HashIncrement(ref ObjectInput input, ref SpanByteAndMemory output) { if (!NumUtils.TryParse(value, out int result)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_HASH_VALUE_IS_NOT_INTEGER, ref curr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_HASH_VALUE_IS_NOT_INTEGER, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); @@ -421,7 +421,7 @@ private void HashIncrement(ref ObjectInput input, ref SpanByteAndMemory output) Add(key, resultBytes); } - while (!RespWriteUtils.WriteIntegerFromBytes(resultBytes, ref curr, end)) + while (!RespWriteUtils.TryWriteIntegerFromBytes(resultBytes, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -429,7 +429,7 @@ private void HashIncrement(ref ObjectInput input, ref SpanByteAndMemory output) { if (!NumUtils.TryParse(incrSlice.ReadOnlySpan, out double incr)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; @@ -441,7 +441,7 @@ private void HashIncrement(ref ObjectInput input, ref SpanByteAndMemory output) { if (!NumUtils.TryParse(value, out double result)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_HASH_VALUE_IS_NOT_FLOAT, ref curr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_HASH_VALUE_IS_NOT_FLOAT, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); @@ -459,7 +459,7 @@ private void HashIncrement(ref ObjectInput input, ref SpanByteAndMemory output) Add(key, resultBytes); } - while (!RespWriteUtils.WriteBulkString(resultBytes, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(resultBytes, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -468,7 +468,7 @@ private void HashIncrement(ref ObjectInput input, ref SpanByteAndMemory output) } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -493,20 +493,20 @@ private void HashExpire(ref ObjectInput input, ref SpanByteAndMemory output) var expireOption = (ExpireOption)input.arg1; var expiration = input.parseState.GetLong(0); var numFields = input.parseState.Count - 1; - while (!RespWriteUtils.WriteArrayLength(numFields, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(numFields, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var item in input.parseState.Parameters.Slice(1)) { var result = SetExpiration(item.ToArray(), expiration, expireOption); - while (!RespWriteUtils.WriteInteger(result, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(result, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); _output.result1++; } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -531,7 +531,7 @@ private void HashTimeToLive(ref ObjectInput input, ref SpanByteAndMemory output) var isMilliseconds = input.arg1 == 1; var isTimestamp = input.arg2 == 1; var numFields = input.parseState.Count; - while (!RespWriteUtils.WriteArrayLength(numFields, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(numFields, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var item in input.parseState.Parameters) @@ -558,14 +558,14 @@ private void HashTimeToLive(ref ObjectInput input, ref SpanByteAndMemory output) } } - while (!RespWriteUtils.WriteInteger(result, ref curr, end)) + while (!RespWriteUtils.TryWriteInt64(result, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); _output.result1++; } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -588,20 +588,20 @@ private void HashPersist(ref ObjectInput input, ref SpanByteAndMemory output) DeleteExpiredItems(); var numFields = input.parseState.Count; - while (!RespWriteUtils.WriteArrayLength(numFields, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(numFields, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var item in input.parseState.Parameters) { var result = Persist(item.ToArray()); - while (!RespWriteUtils.WriteInteger(result, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(result, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); _output.result1++; } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); diff --git a/libs/server/Objects/List/ListObjectImpl.cs b/libs/server/Objects/List/ListObjectImpl.cs index 8e68535e16..fc62147528 100644 --- a/libs/server/Objects/List/ListObjectImpl.cs +++ b/libs/server/Objects/List/ListObjectImpl.cs @@ -136,14 +136,14 @@ private void ListIndex(ref ObjectInput input, ref SpanByteAndMemory output) var item = list.ElementAtOrDefault(index); if (item != default) { - while (!RespWriteUtils.WriteBulkString(item, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); _output.result1 = 1; } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -169,7 +169,7 @@ private void ListRange(ref ObjectInput input, ref SpanByteAndMemory output) if (0 == list.Count) { // write empty list - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else @@ -183,13 +183,13 @@ private void ListRange(ref ObjectInput input, ref SpanByteAndMemory output) if (start > stop || 0 == list.Count) { - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { var count = stop - start + 1; - while (!RespWriteUtils.WriteArrayLength(count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); var i = -1; @@ -200,7 +200,7 @@ private void ListRange(ref ObjectInput input, ref SpanByteAndMemory output) continue; if (i > stop) break; - while (!RespWriteUtils.WriteBulkString(bytes, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(bytes, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } _output.result1 = count; @@ -209,7 +209,7 @@ private void ListRange(ref ObjectInput input, ref SpanByteAndMemory output) } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -314,13 +314,13 @@ private void ListPop(ref ObjectInput input, ref SpanByteAndMemory output, bool f { if (list.Count == 0) { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); count = 0; } else if (count > 1) { - while (!RespWriteUtils.WriteArrayLength(count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -339,7 +339,7 @@ private void ListPop(ref ObjectInput input, ref SpanByteAndMemory output, bool f } UpdateSize(node.Value, false); - while (!RespWriteUtils.WriteBulkString(node.Value, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(node.Value, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); count--; @@ -348,7 +348,7 @@ private void ListPop(ref ObjectInput input, ref SpanByteAndMemory output, bool f } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -369,7 +369,7 @@ private void ListSet(ref ObjectInput input, ref SpanByteAndMemory output) { if (list.Count == 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_NOSUCHKEY, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_NOSUCHKEY, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); return; } @@ -377,7 +377,7 @@ private void ListSet(ref ObjectInput input, ref SpanByteAndMemory output) // index if (!input.parseState.TryGetInt(0, out var index)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); return; } @@ -386,7 +386,7 @@ private void ListSet(ref ObjectInput input, ref SpanByteAndMemory output) if (index > list.Count - 1 || index < 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_INDEX_OUT_RANGE, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_INDEX_OUT_RANGE, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); return; } @@ -402,14 +402,14 @@ private void ListSet(ref ObjectInput input, ref SpanByteAndMemory output) targetNode.Value = element; UpdateSize(targetNode.Value); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); _output.result1 = 1; } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); if (isMemory) ptrHandle.Dispose(); @@ -434,28 +434,28 @@ private void ListPosition(ref ObjectInput input, ref SpanByteAndMemory output) { if (!ReadListPositionInput(ref input, out var rank, out count, out isDefaultCount, out var maxlen, out var error)) { - while (!RespWriteUtils.WriteError(error, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteError(error, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); return; } if (count < 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); return; } if (maxlen < 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); return; } if (rank == 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); return; } @@ -466,7 +466,7 @@ private void ListPosition(ref ObjectInput input, ref SpanByteAndMemory output) if (!isDefaultCount) { - while (!RespWriteUtils.WriteArrayLength(count, ref output_currptr, output_end, out var _, out totalArrayHeaderLen)) + while (!RespWriteUtils.TryWriteArrayLength(count, ref output_currptr, output_end, out var _, out totalArrayHeaderLen)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); } @@ -484,7 +484,7 @@ private void ListPosition(ref ObjectInput input, ref SpanByteAndMemory output) if (rank == 1) { lastFoundItemIndex = currentIndex; - while (!RespWriteUtils.WriteInteger(currentIndex, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteInt32(currentIndex, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); noOfFoundItem++; @@ -516,7 +516,7 @@ private void ListPosition(ref ObjectInput input, ref SpanByteAndMemory output) if (rank == -1) { lastFoundItemIndex = currentIndex; - while (!RespWriteUtils.WriteInteger(currentIndex, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteInt32(currentIndex, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); noOfFoundItem++; @@ -539,20 +539,20 @@ private void ListPosition(ref ObjectInput input, ref SpanByteAndMemory output) if (isDefaultCount && noOfFoundItem == 0) { output_currptr = output_startptr; - while (!RespWriteUtils.WriteNull(ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteNull(ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); } else if (!isDefaultCount && noOfFoundItem == 0) { output_currptr = output_startptr; - while (!RespWriteUtils.WriteNullArray(ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteNullArray(ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); } else if (!isDefaultCount && noOfFoundItem != count) { var newTotalArrayHeaderLen = 0; var startOutputStartptr = output_startptr; - RespWriteUtils.WriteArrayLength(noOfFoundItem, ref startOutputStartptr, output_end, out var _, out newTotalArrayHeaderLen); // ReallocateOutput is not needed here as there should be always be available space in the output buffer as we have already written the max array length + RespWriteUtils.TryWriteArrayLength(noOfFoundItem, ref startOutputStartptr, output_end, out var _, out newTotalArrayHeaderLen); // ReallocateOutput is not needed here as there should be always be available space in the output buffer as we have already written the max array length Debug.Assert(totalArrayHeaderLen >= newTotalArrayHeaderLen, "newTotalArrayHeaderLen can't be bigger than totalArrayHeaderLen as we have already written max array lenght in the buffer"); if (totalArrayHeaderLen != newTotalArrayHeaderLen) @@ -567,7 +567,7 @@ private void ListPosition(ref ObjectInput input, ref SpanByteAndMemory output) } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref output_currptr, output_end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref output_currptr, output_end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref output_startptr, ref ptrHandle, ref output_currptr, ref output_end); if (isMemory) diff --git a/libs/server/Objects/ObjectUtils.cs b/libs/server/Objects/ObjectUtils.cs index bb9a050667..5223c0fc56 100644 --- a/libs/server/Objects/ObjectUtils.cs +++ b/libs/server/Objects/ObjectUtils.cs @@ -120,30 +120,30 @@ public static unsafe void WriteScanOutput(List items, long cursor, ref S try { - while (!RespWriteUtils.WriteScanOutputHeader(cursor, ref curr, end)) + while (!RespWriteUtils.TryWriteScanOutputHeader(cursor, ref curr, end)) ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (items.Count == 0) { // Empty array - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { // Write size of the array - while (!RespWriteUtils.WriteArrayLength(items.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(items.Count, ref curr, end)) ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var item in items) { if (item != null) { - while (!RespWriteUtils.WriteBulkString(item, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item, ref curr, end)) ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } @@ -151,7 +151,7 @@ public static unsafe void WriteScanOutput(List items, long cursor, ref S } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -177,12 +177,12 @@ public static unsafe void WriteScanError(ReadOnlySpan errorMessage, ref Sp try { - while (!RespWriteUtils.WriteError(errorMessage, ref curr, end)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref curr, end)) ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); diff --git a/libs/server/Objects/Set/SetObjectImpl.cs b/libs/server/Objects/Set/SetObjectImpl.cs index c6a215a1d2..86135dec06 100644 --- a/libs/server/Objects/Set/SetObjectImpl.cs +++ b/libs/server/Objects/Set/SetObjectImpl.cs @@ -44,19 +44,19 @@ private void SetMembers(ref SpanByteAndMemory output) ObjectOutputHeader _output = default; try { - while (!RespWriteUtils.WriteArrayLength(set.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(set.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var item in set) { - while (!RespWriteUtils.WriteBulkString(item, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); _output.result1++; } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -79,13 +79,13 @@ private void SetIsMember(ref ObjectInput input, ref SpanByteAndMemory output) var member = input.parseState.GetArgSliceByRef(0).SpanByte.ToByteArray(); var isMember = set.Contains(member); - while (!RespWriteUtils.WriteInteger(isMember ? 1 : 0, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(isMember ? 1 : 0, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); _output.result1 = 1; } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -105,7 +105,7 @@ private void SetMultiIsMember(ref ObjectInput input, ref SpanByteAndMemory outpu ObjectOutputHeader _output = default; try { - while (!RespWriteUtils.WriteArrayLength(input.parseState.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(input.parseState.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); for (var i = 0; i < input.parseState.Count; i++) @@ -113,7 +113,7 @@ private void SetMultiIsMember(ref ObjectInput input, ref SpanByteAndMemory outpu var member = input.parseState.GetArgSliceByRef(i).SpanByte.ToByteArray(); var isMember = set.Contains(member); - while (!RespWriteUtils.WriteInteger(isMember ? 1 : 0, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(isMember ? 1 : 0, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -121,7 +121,7 @@ private void SetMultiIsMember(ref ObjectInput input, ref SpanByteAndMemory outpu } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -176,7 +176,7 @@ private void SetPop(ref ObjectInput input, ref SpanByteAndMemory output) var countParameter = count > set.Count ? set.Count : count; // Write the size of the array reply - while (!RespWriteUtils.WriteArrayLength(countParameter, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(countParameter, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); for (int i = 0; i < countParameter; i++) @@ -186,7 +186,7 @@ private void SetPop(ref ObjectInput input, ref SpanByteAndMemory output) var item = set.ElementAt(index); set.Remove(item); this.UpdateSize(item, false); - while (!RespWriteUtils.WriteBulkString(item, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); countDone++; } @@ -202,13 +202,13 @@ private void SetPop(ref ObjectInput input, ref SpanByteAndMemory output) var item = set.ElementAt(index); set.Remove(item); this.UpdateSize(item, false); - while (!RespWriteUtils.WriteBulkString(item, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { // If set empty return nil - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } countDone++; @@ -217,7 +217,7 @@ private void SetPop(ref ObjectInput input, ref SpanByteAndMemory output) } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -253,13 +253,13 @@ private void SetRandomMember(ref ObjectInput input, ref SpanByteAndMemory output indexes = RandomUtils.PickKRandomIndexes(set.Count, countParameter, seed); // Write the size of the array reply - while (!RespWriteUtils.WriteArrayLength(countParameter, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(countParameter, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var index in indexes) { var element = set.ElementAt(index); - while (!RespWriteUtils.WriteBulkString(element, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(element, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); countDone++; } @@ -272,13 +272,13 @@ private void SetRandomMember(ref ObjectInput input, ref SpanByteAndMemory output { var index = RandomUtils.PickRandomIndex(set.Count, seed); var item = set.ElementAt(index); - while (!RespWriteUtils.WriteBulkString(item, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { // If set is empty, return nil - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } countDone++; @@ -293,13 +293,13 @@ private void SetRandomMember(ref ObjectInput input, ref SpanByteAndMemory output if (set.Count > 0) { // Write the size of the array reply - while (!RespWriteUtils.WriteArrayLength(countParameter, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(countParameter, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var index in indexes) { var element = set.ElementAt(index); - while (!RespWriteUtils.WriteBulkString(element, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(element, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); countDone++; } @@ -307,7 +307,7 @@ private void SetRandomMember(ref ObjectInput input, ref SpanByteAndMemory output else { // If set is empty, return nil - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } @@ -315,7 +315,7 @@ private void SetRandomMember(ref ObjectInput input, ref SpanByteAndMemory output } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); diff --git a/libs/server/Objects/SortedSet/SortedSetObjectImpl.cs b/libs/server/Objects/SortedSet/SortedSetObjectImpl.cs index 531f945552..d18d3e99f7 100644 --- a/libs/server/Objects/SortedSet/SortedSetObjectImpl.cs +++ b/libs/server/Objects/SortedSet/SortedSetObjectImpl.cs @@ -62,7 +62,7 @@ bool GetOptions(ref ObjectInput input, ref int currTokenIdx, out SortedSetAddOpt if (!optionsError.IsEmpty) { - while (!RespWriteUtils.WriteError(optionsError, ref curr, end)) + while (!RespWriteUtils.TryWriteError(optionsError, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return false; } @@ -71,7 +71,7 @@ bool GetOptions(ref ObjectInput input, ref int currTokenIdx, out SortedSetAddOpt // Remaining token count should be positive and even if (currTokenIdx == input.parseState.Count || (input.parseState.Count - currTokenIdx) % 2 != 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return false; } @@ -114,7 +114,7 @@ private void SortedSetAdd(ref ObjectInput input, ref SpanByteAndMemory output) else { // Invalid Score encountered - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -178,13 +178,13 @@ private void SortedSetAdd(ref ObjectInput input, ref SpanByteAndMemory output) } else { - while (!RespWriteUtils.WriteInteger(addedOrChanged, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(addedOrChanged, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -237,7 +237,7 @@ private void SortedSetScore(ref ObjectInput input, ref SpanByteAndMemory output) { if (!sortedSetDict.TryGetValue(member, out var score)) { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else @@ -249,7 +249,7 @@ private void SortedSetScore(ref ObjectInput input, ref SpanByteAndMemory output) } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -273,7 +273,7 @@ private void SortedSetScores(ref ObjectInput input, ref SpanByteAndMemory output try { - while (!RespWriteUtils.WriteArrayLength(count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); for (var i = 0; i < count; i++) @@ -282,7 +282,7 @@ private void SortedSetScores(ref ObjectInput input, ref SpanByteAndMemory output if (!sortedSetDict.TryGetValue(member, out var score)) { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else @@ -295,7 +295,7 @@ private void SortedSetScores(ref ObjectInput input, ref SpanByteAndMemory output } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -324,7 +324,7 @@ private void SortedSetCount(ref ObjectInput input, ref SpanByteAndMemory output) if (!TryParseParameter(minParamSpan, out var minValue, out var minExclusive) || !TryParseParameter(maxParamSpan, out var maxValue, out var maxExclusive)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_FLOAT, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_FLOAT, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -341,12 +341,12 @@ private void SortedSetCount(ref ObjectInput input, ref SpanByteAndMemory output) } } - while (!RespWriteUtils.WriteInteger(count, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -371,7 +371,7 @@ private void SortedSetIncrement(ref ObjectInput input, ref SpanByteAndMemory out // Try to read increment value if (!input.parseState.TryGetDouble(0, out var incrValue)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -399,7 +399,7 @@ private void SortedSetIncrement(ref ObjectInput input, ref SpanByteAndMemory out } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -477,7 +477,7 @@ private void SortedSetRange(ref ObjectInput input, ref SpanByteAndMemory output) // Verify that there are at least 2 more tokens to read if (input.parseState.Count - currIdx < 2) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -486,7 +486,7 @@ private void SortedSetRange(ref ObjectInput input, ref SpanByteAndMemory output) if (!input.parseState.TryGetInt(currIdx++, out var offset) || !input.parseState.TryGetInt(currIdx++, out var countLimit)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -506,7 +506,7 @@ private void SortedSetRange(ref ObjectInput input, ref SpanByteAndMemory output) if (!TryParseParameter(minSpan, out var minValue, out var minExclusive) || !TryParseParameter(maxSpan, out var maxValue, out var maxExclusive)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_FLOAT, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_FLOAT, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -522,14 +522,14 @@ private void SortedSetRange(ref ObjectInput input, ref SpanByteAndMemory output) int minIndex = (int)minValue, maxIndex = (int)maxValue; if (options.ValidLimit) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_LIMIT_NOT_SUPPORTED, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_LIMIT_NOT_SUPPORTED, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } else if (minValue > sortedSetDict.Count - 1) { // return empty list - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -552,7 +552,7 @@ private void SortedSetRange(ref ObjectInput input, ref SpanByteAndMemory output) // No elements to return if both indexes fall outside the range or min is higher than max if ((minIndex < 0 && maxIndex < 0) || (minIndex > maxIndex)) { - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -579,7 +579,7 @@ private void SortedSetRange(ref ObjectInput input, ref SpanByteAndMemory output) if (errorCode == int.MaxValue) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_STRING, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_STRING, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else @@ -590,7 +590,7 @@ private void SortedSetRange(ref ObjectInput input, ref SpanByteAndMemory output) } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -603,15 +603,15 @@ void WriteSortedSetResult(bool withScores, int count, int respProtocolVersion, I if (withScores && respProtocolVersion >= 3) { // write the size of the array reply - while (!RespWriteUtils.WriteArrayLength(count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var (score, element) in iterator) { - while (!RespWriteUtils.WriteArrayLength(2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteBulkString(element, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(element, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); while (!RespWriteUtils.TryWriteDoubleNumeric(score, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); @@ -620,12 +620,12 @@ void WriteSortedSetResult(bool withScores, int count, int respProtocolVersion, I else { // write the size of the array reply - while (!RespWriteUtils.WriteArrayLength(withScores ? count * 2 : count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(withScores ? count * 2 : count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var (score, element) in iterator) { - while (!RespWriteUtils.WriteBulkString(element, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(element, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (withScores) { @@ -653,7 +653,7 @@ private void SortedSetRemoveRangeByRank(ref ObjectInput input, ref SpanByteAndMe if (!input.parseState.TryGetInt(0, out var start) || !input.parseState.TryGetInt(1, out var stop)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -682,12 +682,12 @@ private void SortedSetRemoveRangeByRank(ref ObjectInput input, ref SpanByteAndMe } // Write the number of elements - while (!RespWriteUtils.WriteInteger(elementCount, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(elementCount, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -716,7 +716,7 @@ private void SortedSetRemoveRangeByScore(ref ObjectInput input, ref SpanByteAndM if (!TryParseParameter(minParamBytes, out var minValue, out var minExclusive) || !TryParseParameter(maxParamBytes, out var maxValue, out var maxExclusive)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_FLOAT, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_FLOAT, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -725,12 +725,12 @@ private void SortedSetRemoveRangeByScore(ref ObjectInput input, ref SpanByteAndM false, false, true).Count; // Write the number of elements - while (!RespWriteUtils.WriteInteger(elementCount, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(elementCount, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -762,7 +762,7 @@ private void SortedSetRandomMember(ref ObjectInput input, ref SpanByteAndMemory var arrayLength = Math.Abs(withScores ? count * 2 : count); if (arrayLength > 1 || (arrayLength == 1 && includedCount)) { - while (!RespWriteUtils.WriteArrayLength(arrayLength, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(arrayLength, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } @@ -772,7 +772,7 @@ private void SortedSetRandomMember(ref ObjectInput input, ref SpanByteAndMemory { var (element, score) = sortedSetDict.ElementAt(item); - while (!RespWriteUtils.WriteBulkString(element, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(element, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (withScores) @@ -787,7 +787,7 @@ private void SortedSetRandomMember(ref ObjectInput input, ref SpanByteAndMemory } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -841,7 +841,7 @@ private void SortedSetRank(ref ObjectInput input, ref SpanByteAndMemory output, if (!sortedSetDict.TryGetValue(member, out var score)) { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else @@ -859,10 +859,10 @@ private void SortedSetRank(ref ObjectInput input, ref SpanByteAndMemory output, if (withScore) { - while (!RespWriteUtils.WriteArrayLength(2, ref curr, end)) // Rank and score + while (!RespWriteUtils.TryWriteArrayLength(2, ref curr, end)) // Rank and score ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteInteger(rank, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(rank, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); while (!RespWriteUtils.TryWriteDoubleBulkString(score, ref curr, end)) @@ -870,14 +870,14 @@ private void SortedSetRank(ref ObjectInput input, ref SpanByteAndMemory output, } else { - while (!RespWriteUtils.WriteInteger(rank, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(rank, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -929,7 +929,7 @@ private void SortedSetPopMinOrMaxCount(ref ObjectInput input, ref SpanByteAndMem try { - while (!RespWriteUtils.WriteArrayLength(count * 2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(count * 2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); while (count > 0) @@ -940,7 +940,7 @@ private void SortedSetPopMinOrMaxCount(ref ObjectInput input, ref SpanByteAndMem this.UpdateSize(max.Element, false); - while (!RespWriteUtils.WriteBulkString(max.Element, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(max.Element, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); while (!RespWriteUtils.TryWriteDoubleBulkString(max.Score, ref curr, end)) @@ -954,7 +954,7 @@ private void SortedSetPopMinOrMaxCount(ref ObjectInput input, ref SpanByteAndMem } finally { - while (!RespWriteUtils.WriteDirect(ref outputHeader, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref outputHeader, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); diff --git a/libs/server/Objects/SortedSetGeo/SortedSetGeoObjectImpl.cs b/libs/server/Objects/SortedSetGeo/SortedSetGeoObjectImpl.cs index 66f627f841..6d7ee6a77a 100644 --- a/libs/server/Objects/SortedSetGeo/SortedSetGeoObjectImpl.cs +++ b/libs/server/Objects/SortedSetGeo/SortedSetGeoObjectImpl.cs @@ -87,7 +87,7 @@ private void GeoAdd(ref ObjectInput input, ref SpanByteAndMemory output) if (!input.parseState.TryGetDouble(currTokenIdx++, out var longitude) || !input.parseState.TryGetDouble(currTokenIdx++, out var latitude)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; @@ -123,12 +123,12 @@ private void GeoAdd(ref ObjectInput input, ref SpanByteAndMemory output) } } - while (!RespWriteUtils.WriteInteger(ch ? elementsChanged : elementsAdded, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(ch ? elementsChanged : elementsAdded, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -148,7 +148,7 @@ private void GeoHash(ref ObjectInput input, ref SpanByteAndMemory output) ObjectOutputHeader _output = default; try { - while (!RespWriteUtils.WriteArrayLength(input.parseState.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(input.parseState.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); for (var i = 0; i < input.parseState.Count; i++) @@ -159,19 +159,19 @@ private void GeoHash(ref ObjectInput input, ref SpanByteAndMemory output) if (sortedSetDict.TryGetValue(member, out var value52Int)) { var geoHash = server.GeoHash.GetGeoHashCode((long)value52Int); - while (!RespWriteUtils.WriteAsciiBulkString(geoHash, ref curr, end)) + while (!RespWriteUtils.TryWriteAsciiBulkString(geoHash, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -217,13 +217,13 @@ private void GeoDistance(ref ObjectInput input, ref SpanByteAndMemory output) } else { - while (!RespWriteUtils.WriteNull(ref curr, end)) + while (!RespWriteUtils.TryWriteNull(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -243,7 +243,7 @@ private void GeoPosition(ref ObjectInput input, ref SpanByteAndMemory output) ObjectOutputHeader _output = default; try { - while (!RespWriteUtils.WriteArrayLength(input.parseState.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(input.parseState.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); for (var i = 0; i < input.parseState.Count; i++) @@ -256,7 +256,7 @@ private void GeoPosition(ref ObjectInput input, ref SpanByteAndMemory output) var (lat, lon) = server.GeoHash.GetCoordinatesFromLong((long)scoreMember1); // write array of 2 values - while (!RespWriteUtils.WriteArrayLength(2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); while (!RespWriteUtils.TryWriteDoubleBulkString(lon, ref curr, end)) @@ -267,14 +267,14 @@ private void GeoPosition(ref ObjectInput input, ref SpanByteAndMemory output) } else { - while (!RespWriteUtils.WriteNullArray(ref curr, end)) + while (!RespWriteUtils.TryWriteNullArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); @@ -422,7 +422,7 @@ private void GeoSearch(ref ObjectInput input, ref SpanByteAndMemory output) // Check if we encountered an error while checking the parse state if (errorMessage != default) { - while (!RespWriteUtils.WriteError(errorMessage, ref curr, end)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -430,7 +430,7 @@ private void GeoSearch(ref ObjectInput input, ref SpanByteAndMemory output) // Not supported options in Garnet: WITHHASH if (opts.WithHash) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -444,7 +444,7 @@ private void GeoSearch(ref ObjectInput input, ref SpanByteAndMemory output) if (opts.ByRadius) { // Not supported in Garnet: ByRadius - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else @@ -475,7 +475,7 @@ private void GeoSearch(ref ObjectInput input, ref SpanByteAndMemory output) if (responseData.Count == 0) { - while (!RespWriteUtils.WriteInteger(0, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(0, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else @@ -495,18 +495,18 @@ private void GeoSearch(ref ObjectInput input, ref SpanByteAndMemory output) } // Write results - while (!RespWriteUtils.WriteArrayLength(responseData.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(responseData.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var item in responseData) { if (innerArrayLength > 1) { - while (!RespWriteUtils.WriteArrayLength(innerArrayLength, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(innerArrayLength, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } - while (!RespWriteUtils.WriteBulkString(item.Member, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(item.Member, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (opts.WithDist) @@ -521,7 +521,7 @@ private void GeoSearch(ref ObjectInput input, ref SpanByteAndMemory output) if (opts.WithCoord) { // Write array of 2 values - while (!RespWriteUtils.WriteArrayLength(2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); while (!RespWriteUtils.TryWriteDoubleBulkString(item.Coordinates.Longitude, ref curr, end)) @@ -538,13 +538,13 @@ private void GeoSearch(ref ObjectInput input, ref SpanByteAndMemory output) // Not supported options in Garnet: FROMLONLAT BYBOX BYRADIUS if (opts.FromLonLat) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref curr, end)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } finally { - while (!RespWriteUtils.WriteDirect(ref _output, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(ref _output, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (isMemory) ptrHandle.Dispose(); diff --git a/libs/server/PubSub/SubscribeBroker.cs b/libs/server/PubSub/SubscribeBroker.cs index 75afb319a5..f63cabd220 100644 --- a/libs/server/PubSub/SubscribeBroker.cs +++ b/libs/server/PubSub/SubscribeBroker.cs @@ -426,19 +426,19 @@ public unsafe void Channels(ref ObjectInput input, ref SpanByteAndMemory output) { if (subscriptions is null || subscriptions.Count == 0) { - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } if (input.parseState.Count == 0) { - while (!RespWriteUtils.WriteArrayLength(subscriptions.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(subscriptions.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var key in subscriptions.Keys) { - while (!RespWriteUtils.WriteBulkString(key.AsSpan().Slice(sizeof(int)), ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(key.AsSpan().Slice(sizeof(int)), ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } return; @@ -447,7 +447,7 @@ public unsafe void Channels(ref ObjectInput input, ref SpanByteAndMemory output) // Below WriteArrayLength is primarily to move the start of the buffer to the max length that is required to write the array length. The actual length is written in the below line. // This is done to avoid multiple two passes over the subscriptions or new array allocation if we use single pass over the subscriptions var totalArrayHeaderLen = 0; - while (!RespWriteUtils.WriteArrayLength(subscriptions.Count, ref curr, end, out var _, out totalArrayHeaderLen)) + while (!RespWriteUtils.TryWriteArrayLength(subscriptions.Count, ref curr, end, out var _, out totalArrayHeaderLen)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); var noOfFoundChannels = 0; @@ -463,7 +463,7 @@ public unsafe void Channels(ref ObjectInput input, ref SpanByteAndMemory output) var _patternPtr = patternPtr; if (keySerializer.Match(ref keySerializer.ReadKeyByRef(ref endKeyPtr), true, ref keySerializer.ReadKeyByRef(ref _patternPtr), true)) { - while (!RespWriteUtils.WriteSimpleString(key.AsSpan().Slice(sizeof(int)), ref curr, end)) + while (!RespWriteUtils.TryWriteSimpleString(key.AsSpan().Slice(sizeof(int)), ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); noOfFoundChannels++; } @@ -473,7 +473,7 @@ public unsafe void Channels(ref ObjectInput input, ref SpanByteAndMemory output) if (noOfFoundChannels == 0) { curr = ptr; - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } @@ -483,7 +483,7 @@ public unsafe void Channels(ref ObjectInput input, ref SpanByteAndMemory output) var newTotalArrayHeaderLen = 0; var _ptr = ptr; // ReallocateOutput is not needed here as there should be always be available space in the output buffer as we have already written the max array length - _ = RespWriteUtils.WriteArrayLength(noOfFoundChannels, ref _ptr, end, out var _, out newTotalArrayHeaderLen); + _ = RespWriteUtils.TryWriteArrayLength(noOfFoundChannels, ref _ptr, end, out var _, out newTotalArrayHeaderLen); Debug.Assert(totalArrayHeaderLen >= newTotalArrayHeaderLen, "newTotalArrayHeaderLen can't be bigger than totalArrayHeaderLen as we have already written max array lenght in the buffer"); if (totalArrayHeaderLen != newTotalArrayHeaderLen) @@ -529,12 +529,12 @@ public unsafe void NumSubscriptions(ref ObjectInput input, ref SpanByteAndMemory var numOfChannels = input.parseState.Count; if (subscriptions is null || numOfChannels == 0) { - while (!RespWriteUtils.WriteEmptyArray(ref curr, end)) + while (!RespWriteUtils.TryWriteEmptyArray(ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return; } - while (!RespWriteUtils.WriteArrayLength(numOfChannels * 2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(numOfChannels * 2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); var currChannelIdx = 0; @@ -545,13 +545,13 @@ public unsafe void NumSubscriptions(ref ObjectInput input, ref SpanByteAndMemory var channelPtr = channelSpan.ToPointer() - sizeof(int); // Memory would have been already pinned *(int*)channelPtr = channelSpan.Length; - while (!RespWriteUtils.WriteBulkString(channelArg.ReadOnlySpan, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(channelArg.ReadOnlySpan, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); var channel = new Span(channelPtr, channelSpan.Length + sizeof(int)).ToArray(); subscriptions.TryGetValue(channel, out var subscriptionDict); - while (!RespWriteUtils.WriteInteger(subscriptionDict is null ? 0 : subscriptionDict.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(subscriptionDict is null ? 0 : subscriptionDict.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); currChannelIdx++; diff --git a/libs/server/Resp/ACLCommands.cs b/libs/server/Resp/ACLCommands.cs index 61c4f6e8c5..150cf31528 100644 --- a/libs/server/Resp/ACLCommands.cs +++ b/libs/server/Resp/ACLCommands.cs @@ -20,7 +20,7 @@ private bool ValidateACLAuthenticator() { if (_authenticator is null or not GarnetACLAuthenticator) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_ACL_AUTH_DISABLED, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_ACL_AUTH_DISABLED, ref dcurr, dend)) SendAndReset(); return false; } @@ -31,7 +31,7 @@ private bool ValidateACLFileUse() { if (storeWrapper.serverOptions.AuthSettings is not AclAuthenticationSettings) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_ACL_AUTH_DISABLED, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_ACL_AUTH_DISABLED, ref dcurr, dend)) SendAndReset(); return false; } @@ -39,7 +39,7 @@ private bool ValidateACLFileUse() var aclAuthenticationSettings = (AclAuthenticationSettings)storeWrapper.serverOptions.AuthSettings; if (aclAuthenticationSettings.AclConfigurationFile == null) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_ACL_AUTH_FILE_DISABLED, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_ACL_AUTH_FILE_DISABLED, ref dcurr, dend)) SendAndReset(); return false; } @@ -56,7 +56,7 @@ private bool NetworkAclList() // No additional args allowed if (parseState.Count != 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for ACL LIST.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for ACL LIST.", ref dcurr, dend)) SendAndReset(); } else @@ -66,12 +66,12 @@ private bool NetworkAclList() var aclAuthenticator = (GarnetACLAuthenticator)_authenticator; var users = aclAuthenticator.GetAccessControlList().GetUsers(); - while (!RespWriteUtils.WriteArrayLength(users.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(users.Count, ref dcurr, dend)) SendAndReset(); foreach (var user in users) { - while (!RespWriteUtils.WriteAsciiBulkString(user.Value.DescribeUser(), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(user.Value.DescribeUser(), ref dcurr, dend)) SendAndReset(); } } @@ -88,7 +88,7 @@ private bool NetworkAclUsers() // No additional args allowed if (parseState.Count != 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for ACL USERS.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for ACL USERS.", ref dcurr, dend)) SendAndReset(); } else @@ -98,12 +98,12 @@ private bool NetworkAclUsers() var aclAuthenticator = (GarnetACLAuthenticator)_authenticator; var users = aclAuthenticator.GetAccessControlList().GetUsers(); - while (!RespWriteUtils.WriteArrayLength(users.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(users.Count, ref dcurr, dend)) SendAndReset(); foreach (var user in users) { - while (!RespWriteUtils.WriteAsciiBulkString(user.Key, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(user.Key, ref dcurr, dend)) SendAndReset(); } } @@ -120,7 +120,7 @@ private bool NetworkAclCat() // No additional args allowed if (parseState.Count != 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for ACL CAT.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for ACL CAT.", ref dcurr, dend)) SendAndReset(); } else @@ -129,11 +129,11 @@ private bool NetworkAclCat() return true; var categories = ACLParser.ListCategories(); - RespWriteUtils.WriteArrayLength(categories.Count, ref dcurr, dend); + RespWriteUtils.TryWriteArrayLength(categories.Count, ref dcurr, dend); foreach (var category in categories) { - while (!RespWriteUtils.WriteAsciiBulkString(category, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(category, ref dcurr, dend)) SendAndReset(); } } @@ -150,7 +150,7 @@ private bool NetworkAclSetUser() // Have to have at least the username if (parseState.Count == 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for ACL SETUSER.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for ACL SETUSER.", ref dcurr, dend)) SendAndReset(); } else @@ -186,13 +186,13 @@ private bool NetworkAclSetUser() logger?.LogDebug("ACLException: {message}", exception.Message); // Abort command execution - while (!RespWriteUtils.WriteError($"ERR {exception.Message}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR {exception.Message}", ref dcurr, dend)) SendAndReset(); return true; } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -208,7 +208,7 @@ private bool NetworkAclDelUser() // Have to have at least the username if (parseState.Count == 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for ACL DELUSER.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for ACL DELUSER.", ref dcurr, dend)) SendAndReset(); } else @@ -237,14 +237,14 @@ private bool NetworkAclDelUser() logger?.LogDebug("ACLException: {message}", exception.Message); // Abort command execution - while (!RespWriteUtils.WriteError($"ERR {exception.Message}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR {exception.Message}", ref dcurr, dend)) SendAndReset(); return true; } // Return the number of successful deletes - while (!RespWriteUtils.WriteInteger(successfulDeletes, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(successfulDeletes, ref dcurr, dend)) SendAndReset(); } @@ -260,7 +260,7 @@ private bool NetworkAclWhoAmI() // No additional args allowed if (parseState.Count != 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for ACL WHOAMI.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for ACL WHOAMI.", ref dcurr, dend)) SendAndReset(); } else @@ -273,7 +273,7 @@ private bool NetworkAclWhoAmI() // Return the name of the currently authenticated user. Debug.Assert(aclAuthenticator.GetUser() != null); - while (!RespWriteUtils.WriteSimpleString(aclAuthenticator.GetUser().Name, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString(aclAuthenticator.GetUser().Name, ref dcurr, dend)) SendAndReset(); } @@ -289,7 +289,7 @@ private bool NetworkAclLoad() // No additional args allowed if (parseState.Count != 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for ACL LOAD.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for ACL LOAD.", ref dcurr, dend)) SendAndReset(); } else @@ -311,12 +311,12 @@ private bool NetworkAclLoad() logger?.LogInformation("Reading updated ACL configuration file '{filepath}'", aclAuthenticationSettings.AclConfigurationFile); storeWrapper.accessControlList.Load(aclAuthenticationSettings.DefaultPassword, aclAuthenticationSettings.AclConfigurationFile); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } catch (ACLException exception) { - while (!RespWriteUtils.WriteError($"ERR {exception.Message}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR {exception.Message}", ref dcurr, dend)) SendAndReset(); } } @@ -332,7 +332,7 @@ private bool NetworkAclSave() { if (parseState.Count != 0) { - while (!RespWriteUtils.WriteError($"ERR Unknown subcommand or wrong number of arguments for ACL SAVE.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unknown subcommand or wrong number of arguments for ACL SAVE.", ref dcurr, dend)) SendAndReset(); } @@ -355,13 +355,13 @@ private bool NetworkAclSave() catch (Exception ex) { logger?.LogError(ex, "ACL SAVE faulted"); - while (!RespWriteUtils.WriteError($"ERR {ex.Message}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR {ex.Message}", ref dcurr, dend)) SendAndReset(); return true; } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/server/Resp/AdminCommands.cs b/libs/server/Resp/AdminCommands.cs index 16aa01e797..96b0fdc6c6 100644 --- a/libs/server/Resp/AdminCommands.cs +++ b/libs/server/Resp/AdminCommands.cs @@ -27,7 +27,7 @@ private void ProcessAdminCommands(RespCommand command, ref TGarnetAp if (_authenticator.CanAuthenticate && !_authenticator.IsAuthenticated) { // If the current session is unauthenticated, we stop parsing, because no other commands are allowed - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOAUTH, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOAUTH, ref dcurr, dend)) SendAndReset(); } @@ -71,7 +71,7 @@ RespCommand.MIGRATE or return; } - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) SendAndReset(); } @@ -130,7 +130,7 @@ private bool NetworkMonitor() return AbortWithWrongNumberOfArguments(nameof(RespCommand.MONITOR)); } - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) SendAndReset(); return true; @@ -402,7 +402,7 @@ private bool NetworkRegisterCs(CustomCommandManager customCommandManager) // Check optional parameters for previous sub-command if (optionalParamsRead < 2 && args is RegisterCmdArgs cmdArgs) { - if (NumUtils.TryBytesToLong(token, out var expTicks)) + if (NumUtils.TryReadInt64(token, out var expTicks)) { cmdArgs.ExpirationTicks = expTicks; optionalParamsRead++; @@ -457,12 +457,12 @@ private bool NetworkRegisterCs(CustomCommandManager customCommandManager) if (errorMsg.IsEmpty && TryRegisterCustomCommands(binaryPaths, cmdInfoPath, cmdDocsPath, classNameToRegisterArgs, customCommandManager, out errorMsg)) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(errorMsg, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMsg, ref dcurr, dend)) SendAndReset(); } @@ -498,7 +498,7 @@ private bool NetworkModuleLoad(CustomCommandManager customCommandManager) { if (!errorMsg.IsEmpty) { - while (!RespWriteUtils.WriteError(errorMsg, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMsg, ref dcurr, dend)) SendAndReset(); } @@ -515,14 +515,14 @@ private bool NetworkModuleLoad(CustomCommandManager customCommandManager) if (ModuleRegistrar.Instance.LoadModule(customCommandManager, assembliesList[0], moduleArgs, logger, out errorMsg)) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } } if (!errorMsg.IsEmpty) { - while (!RespWriteUtils.WriteError(errorMsg, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMsg, ref dcurr, dend)) SendAndReset(); } @@ -537,7 +537,7 @@ private bool NetworkCOMMITAOF() } CommitAof(); - while (!RespWriteUtils.WriteSimpleString("AOF file committed"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString("AOF file committed"u8, ref dcurr, dend)) SendAndReset(); return true; @@ -555,14 +555,14 @@ private bool NetworkFORCEGC() { if (!parseState.TryGetInt(0, out generation) || generation < 0 || generation > GC.MaxGeneration) { - while (!RespWriteUtils.WriteError("ERR Invalid GC generation."u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR Invalid GC generation."u8, ref dcurr, dend)) SendAndReset(); return true; } } GC.Collect(generation, GCCollectionMode.Forced, true); - while (!RespWriteUtils.WriteSimpleString("GC completed"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString("GC completed"u8, ref dcurr, dend)) SendAndReset(); return true; @@ -586,11 +586,11 @@ private bool NetworkHCOLLECT(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); break; default: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_HCOLLECT_ALREADY_IN_PROGRESS, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_HCOLLECT_ALREADY_IN_PROGRESS, ref dcurr, dend)) SendAndReset(); break; } @@ -602,7 +602,7 @@ private bool NetworkProcessClusterCommand(RespCommand command) { if (clusterSession == null) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_CLUSTER_DISABLED, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_CLUSTER_DISABLED, ref dcurr, dend)) SendAndReset(); return true; } @@ -620,12 +620,12 @@ private bool NetworkSAVE() if (!storeWrapper.TakeCheckpoint(false, StoreType.All, logger)) { - while (!RespWriteUtils.WriteError("ERR checkpoint already in progress"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR checkpoint already in progress"u8, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } @@ -640,7 +640,7 @@ private bool NetworkLASTSAVE() } var seconds = storeWrapper.lastSaveTime.ToUnixTimeSeconds(); - while (!RespWriteUtils.WriteInteger(seconds, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt64(seconds, ref dcurr, dend)) SendAndReset(); return true; @@ -656,12 +656,12 @@ private bool NetworkBGSAVE() var success = storeWrapper.TakeCheckpoint(true, StoreType.All, logger); if (success) { - while (!RespWriteUtils.WriteSimpleString("Background saving started"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString("Background saving started"u8, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError("ERR checkpoint already in progress"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR checkpoint already in progress"u8, ref dcurr, dend)) SendAndReset(); } diff --git a/libs/server/Resp/ArrayCommands.cs b/libs/server/Resp/ArrayCommands.cs index d1e534ae3b..5a247e0c3c 100644 --- a/libs/server/Resp/ArrayCommands.cs +++ b/libs/server/Resp/ArrayCommands.cs @@ -23,7 +23,7 @@ private bool NetworkMGET(ref TGarnetApi storageApi) if (storeWrapper.serverOptions.EnableScatterGatherGet) return NetworkMGET_SG(ref storageApi); - while (!RespWriteUtils.WriteArrayLength(parseState.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(parseState.Count, ref dcurr, dend)) SendAndReset(); RawStringInput input = default; @@ -44,7 +44,7 @@ private bool NetworkMGET(ref TGarnetApi storageApi) break; case GarnetStatus.NOTFOUND: Debug.Assert(o.IsSpanByte); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; } @@ -62,7 +62,7 @@ private bool NetworkMGET_SG(ref TGarnetApi storageApi) (GarnetStatus, SpanByteAndMemory)[] outputArr = null; // Write array length header - while (!RespWriteUtils.WriteArrayLength(parseState.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(parseState.Count, ref dcurr, dend)) SendAndReset(); RawStringInput input = default; @@ -111,7 +111,7 @@ private bool NetworkMGET_SG(ref TGarnetApi storageApi) if (firstPending == -1) { // Realized not-found without IO, and no earlier pending, so we can add directly to the output - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); o = new SpanByteAndMemory(dcurr, (int)(dend - dcurr)); } @@ -143,7 +143,7 @@ private bool NetworkMGET_SG(ref TGarnetApi storageApi) } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } } @@ -165,7 +165,7 @@ private bool NetworkMSET(ref TGarnetApi storageApi) var val = parseState.GetArgSliceByRef(c + 1).SpanByte; _ = storageApi.SET(ref key, ref val); } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } @@ -192,7 +192,7 @@ private bool NetworkMSETNX(ref TGarnetApi storageApi) anyValuesSet = true; } - while (!RespWriteUtils.WriteInteger(anyValuesSet ? 1 : 0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(anyValuesSet ? 1 : 0, ref dcurr, dend)) SendAndReset(); return true; } @@ -211,7 +211,7 @@ private bool NetworkDEL(ref TGarnetApi storageApi) keysDeleted++; } - while (!RespWriteUtils.WriteInteger(keysDeleted, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(keysDeleted, ref dcurr, dend)) SendAndReset(); return true; } @@ -230,14 +230,14 @@ private bool NetworkSELECT() // Validate index if (!parseState.TryGetInt(0, out var index)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } if (index < storeWrapper.databaseNum) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else @@ -245,12 +245,12 @@ private bool NetworkSELECT() if (storeWrapper.serverOptions.EnableCluster) { // Cluster mode does not allow DBID - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_SELECT_CLUSTER_MODE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_SELECT_CLUSTER_MODE, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_SELECT_INVALID_INDEX, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_SELECT_INVALID_INDEX, ref dcurr, dend)) SendAndReset(); } } @@ -265,7 +265,7 @@ private bool NetworkDBSIZE(ref TGarnetApi storageApi) return AbortWithWrongNumberOfArguments(nameof(RespCommand.DBSIZE)); } - while (!RespWriteUtils.WriteInteger(storageApi.GetDbSize(), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(storageApi.GetDbSize(), ref dcurr, dend)) SendAndReset(); return true; @@ -287,19 +287,19 @@ private bool NetworkKEYS(ref TGarnetApi storageApi) if (keys.Count > 0) { // Write size of the array - while (!RespWriteUtils.WriteArrayLength(keys.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(keys.Count, ref dcurr, dend)) SendAndReset(); // Write the keys matching the pattern foreach (var item in keys) { - while (!RespWriteUtils.WriteBulkString(item, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(item, ref dcurr, dend)) SendAndReset(); } } else { - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); } @@ -315,7 +315,7 @@ private bool NetworkSCAN(ref TGarnetApi storageApi) // Validate scan cursor if (!parseState.TryGetLong(0, out var cursorFromInput)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_INVALIDCURSOR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_INVALIDCURSOR, ref dcurr, dend)) SendAndReset(); return true; } @@ -344,7 +344,7 @@ private bool NetworkSCAN(ref TGarnetApi storageApi) // Validate count if (!parseState.TryGetLong(tokenIdx++, out countValue)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -361,21 +361,21 @@ private bool NetworkSCAN(ref TGarnetApi storageApi) // Prepare values for output if (keys.Count == 0) { - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); // Number of keys "0" - while (!RespWriteUtils.WriteIntegerAsBulkString(0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32AsBulkString(0, ref dcurr, dend)) SendAndReset(); // Empty array - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); } else { // The response is two elements: the value of the cursor and the array of keys found matching the pattern - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); if (keys.Count > 0) @@ -398,12 +398,12 @@ private bool NetworkTYPE(ref TGarnetApi storageApi) if (status == GarnetStatus.OK) { - while (!RespWriteUtils.WriteSimpleString(typeName, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString(typeName, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteSimpleString("none"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString("none"u8, ref dcurr, dend)) SendAndReset(); } @@ -419,11 +419,11 @@ private void WriteOutputForScan(long cursorValue, List keys) { // The output is an array of two elements: cursor value and an array of keys // Note the cursor value should be formatted as bulk string ('$') - while (!RespWriteUtils.WriteIntegerAsBulkString(cursorValue, ref dcurr, dend, out _)) + while (!RespWriteUtils.TryWriteInt64AsBulkString(cursorValue, ref dcurr, dend, out _)) SendAndReset(); // Write size of the array - while (!RespWriteUtils.WriteArrayLength(keys.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(keys.Count, ref dcurr, dend)) SendAndReset(); // Write the keys matching the pattern diff --git a/libs/server/Resp/AsyncProcessor.cs b/libs/server/Resp/AsyncProcessor.cs index 987a56629f..1f1a1ea974 100644 --- a/libs/server/Resp/AsyncProcessor.cs +++ b/libs/server/Resp/AsyncProcessor.cs @@ -50,7 +50,7 @@ void NetworkGETPending(ref TGarnetApi storageApi) { unsafe { - while (!RespWriteUtils.WriteError($"ASYNC {asyncStarted}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ASYNC {asyncStarted}", ref dcurr, dend)) SendAndReset(); } @@ -104,11 +104,11 @@ async Task AsyncGetProcessor(TGarnetApi storageApi) var o = completedOutputs.Current.Output; // We write async push response as an array: [ "async", "", "" ] - while (!RespWriteUtils.WritePushLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWritePushLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(CmdStrings.async, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(CmdStrings.async, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteIntegerAsBulkString((int)completedOutputs.Current.Context, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32AsBulkString((int)completedOutputs.Current.Context, ref dcurr, dend)) SendAndReset(); if (completedOutputs.Current.Status.Found) { @@ -119,7 +119,7 @@ async Task AsyncGetProcessor(TGarnetApi storageApi) else { sessionMetrics?.incr_total_notfound(); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } } diff --git a/libs/server/Resp/BasicCommands.cs b/libs/server/Resp/BasicCommands.cs index f02da25b49..a5c0867c53 100644 --- a/libs/server/Resp/BasicCommands.cs +++ b/libs/server/Resp/BasicCommands.cs @@ -46,7 +46,7 @@ bool NetworkGET(ref TGarnetApi storageApi) break; case GarnetStatus.NOTFOUND: Debug.Assert(o.IsSpanByte); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; } @@ -79,7 +79,7 @@ bool NetworkGETEX(ref TGarnetApi storageApi) { if (parseState.Count < 3 || !parseState.TryGetLong(2, out var expireTime) || expireTime <= 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_OUT_OF_RANGE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_OUT_OF_RANGE, ref dcurr, dend)) SendAndReset(); return true; } @@ -103,7 +103,7 @@ bool NetworkGETEX(ref TGarnetApi storageApi) break; default: - while (!RespWriteUtils.WriteError($"ERR Unsupported option {parseState.GetString(1)}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unsupported option {parseState.GetString(1)}", ref dcurr, dend)) SendAndReset(); return true; } @@ -126,7 +126,7 @@ bool NetworkGETEX(ref TGarnetApi storageApi) break; case GarnetStatus.NOTFOUND: Debug.Assert(o.IsSpanByte); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; } @@ -166,7 +166,7 @@ bool NetworkGETAsync(ref TGarnetApi storageApi) break; case GarnetStatus.NOTFOUND: Debug.Assert(o.IsSpanByte); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; } @@ -227,7 +227,7 @@ bool NetworkGET_SG(ref TGarnetApi storageApi) if (firstPending == -1) { // Realized not-found without IO, and no earlier pending, so we can add directly to the output - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); o = new SpanByteAndMemory(dcurr, (int)(dend - dcurr)); } @@ -259,7 +259,7 @@ bool NetworkGET_SG(ref TGarnetApi storageApi) } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } } @@ -291,7 +291,7 @@ private bool NetworkSET(ref TGarnetApi storageApi) storageApi.SET(ref key, ref value); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -323,14 +323,14 @@ private bool NetworkSetRange(ref TGarnetApi storageApi) // Validate offset if (!parseState.TryGetInt(1, out var offset)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } if (offset < 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_OFFSETOUTOFRANGE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_OFFSETOUTOFRANGE, ref dcurr, dend)) SendAndReset(); return true; } @@ -342,7 +342,7 @@ private bool NetworkSetRange(ref TGarnetApi storageApi) storageApi.SETRANGE(key, ref input, ref output); - while (!RespWriteUtils.WriteIntegerFromBytes(outputBuffer.Slice(0, output.Length), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteIntegerFromBytes(outputBuffer.Slice(0, output.Length), ref dcurr, dend)) SendAndReset(); return true; @@ -357,7 +357,7 @@ private bool NetworkGetRange(ref TGarnetApi storageApi) // Validate range if (!parseState.TryGetInt(1, out _) || !parseState.TryGetInt(2, out _)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -380,7 +380,7 @@ private bool NetworkGetRange(ref TGarnetApi storageApi) { sessionMetrics?.incr_total_notfound(); Debug.Assert(o.IsSpanByte); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_EMPTY, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_EMPTY, ref dcurr, dend)) SendAndReset(); } @@ -398,14 +398,14 @@ private bool NetworkSETEX(bool highPrecision, ref TGarnetApi storage // Validate expiry if (!parseState.TryGetInt(1, out var expiry)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } if (expiry <= 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_INVALIDEXP_IN_SET, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_INVALIDEXP_IN_SET, ref dcurr, dend)) SendAndReset(); return true; } @@ -420,7 +420,7 @@ private bool NetworkSETEX(bool highPrecision, ref TGarnetApi storage var input = new RawStringInput(RespCommand.SETEX, 0, valMetadata); _ = storageApi.SET(ref key, ref input, ref sbVal); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -565,7 +565,7 @@ private bool NetworkSETEXNX(ref TGarnetApi storageApi) if (!errorMessage.IsEmpty) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; } @@ -612,7 +612,7 @@ private bool NetworkSETEXNX(ref TGarnetApi storageApi) break; } - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) SendAndReset(); return true; } @@ -633,7 +633,7 @@ private unsafe bool NetworkSET_EX(RespCommand cmd, ExpirationOption storageApi.SET(ref key, ref input, ref val); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } @@ -665,12 +665,12 @@ private bool NetworkSET_Conditional(RespCommand cmd, int expiry, ref if (ok) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } return true; @@ -700,7 +700,7 @@ private bool NetworkSET_Conditional(RespCommand cmd, int expiry, ref } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } @@ -726,7 +726,7 @@ private bool NetworkIncrement(RespCommand cmd, ref TGarnetApi storag long incrByValue = 0; if (parseState.Count > 1 && !parseState.TryGetLong(1, out incrByValue)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -744,11 +744,11 @@ private bool NetworkIncrement(RespCommand cmd, ref TGarnetApi storag switch (errorFlag) { case OperationError.SUCCESS: - while (!RespWriteUtils.WriteIntegerFromBytes(outputBuffer.Slice(0, output.Length), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteIntegerFromBytes(outputBuffer.Slice(0, output.Length), ref dcurr, dend)) SendAndReset(); break; case OperationError.INVALID_TYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); break; default: @@ -769,7 +769,7 @@ private bool NetworkIncrementByFloat(ref TGarnetApi storageApi) if (!NumUtils.TryParse(incrSlice.ReadOnlySpan, out float _)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref dcurr, dend)) SendAndReset(); return true; } @@ -787,11 +787,11 @@ private bool NetworkIncrementByFloat(ref TGarnetApi storageApi) switch (errorFlag) { case OperationError.SUCCESS: - while (!RespWriteUtils.WriteBulkString(outputBuffer.Slice(0, output.Length), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(outputBuffer.Slice(0, output.Length), ref dcurr, dend)) SendAndReset(); break; case OperationError.INVALID_TYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOT_VALID_FLOAT, ref dcurr, dend)) SendAndReset(); break; @@ -817,7 +817,7 @@ private bool NetworkAppend(ref TGarnetApi storageApi) storageApi.APPEND(ref sbKey, ref input, ref output); - while (!RespWriteUtils.WriteIntegerFromBytes(outputBuffer.Slice(0, output.Length), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteIntegerFromBytes(outputBuffer.Slice(0, output.Length), ref dcurr, dend)) SendAndReset(); return true; @@ -830,12 +830,12 @@ private bool NetworkPING() { if (isSubscriptionSession && respProtocolVersion == 2) { - while (!RespWriteUtils.WriteDirect(CmdStrings.SUSCRIBE_PONG, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.SUSCRIBE_PONG, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_PONG, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_PONG, ref dcurr, dend)) SendAndReset(); } return true; @@ -849,7 +849,7 @@ private bool NetworkASKING() //*1\r\n$6\r\n ASKING\r\n = 16 if (storeWrapper.serverOptions.EnableCluster) SessionAsking = 2; - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } @@ -859,7 +859,7 @@ private bool NetworkASKING() /// private bool NetworkQUIT() { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); toDispose = true; return true; @@ -905,7 +905,7 @@ private bool NetworkREADONLY() { //*1\r\n$8\r\nREADONLY\r\n clusterSession?.SetReadOnlySession(); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } @@ -918,7 +918,7 @@ private bool NetworkREADWRITE() { //*1\r\n$9\r\nREADWRITE\r\n clusterSession?.SetReadWriteSession(); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } @@ -944,11 +944,11 @@ private bool NetworkSTRLEN(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(value.Length, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(value.Length, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteInteger(0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(0, ref dcurr, dend)) SendAndReset(); break; } @@ -979,9 +979,9 @@ private void WriteCOMMANDResponse() } } - while (!RespWriteUtils.WriteArrayLength(cmdCount, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(cmdCount, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteAsciiDirect(resultSb.ToString(), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiDirect(resultSb.ToString(), ref dcurr, dend)) SendAndReset(); } @@ -996,7 +996,7 @@ private bool NetworkCOMMAND() { var subCommand = parseState.GetString(0); var errorMsg = string.Format(CmdStrings.GenericErrUnknownSubCommand, subCommand, nameof(RespCommand.COMMAND)); - while (!RespWriteUtils.WriteError(errorMsg, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMsg, ref dcurr, dend)) SendAndReset(); } else @@ -1017,7 +1017,7 @@ private bool NetworkCOMMAND_COUNT() if (parseState.Count != 0) { var errorMsg = string.Format(CmdStrings.GenericErrWrongNumArgs, "COMMAND COUNT"); - while (!RespWriteUtils.WriteError(errorMsg, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMsg, ref dcurr, dend)) SendAndReset(); } else @@ -1029,7 +1029,7 @@ private bool NetworkCOMMAND_COUNT() var commandCount = storeWrapper.customCommandManager.CustomCommandsInfoCount + respCommandCount; - while (!RespWriteUtils.WriteInteger(commandCount, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(commandCount, ref dcurr, dend)) SendAndReset(); } @@ -1085,10 +1085,10 @@ private bool NetworkCOMMAND_DOCS() var currptr = startptr; var endptr = startptr + output.Length; - while (!RespWriteUtils.WriteArrayLength(docsCount * 2, ref currptr, endptr)) + while (!RespWriteUtils.TryWriteArrayLength(docsCount * 2, ref currptr, endptr)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref startptr, ref ptrHandle, ref currptr, ref endptr); - while (!RespWriteUtils.WriteAsciiDirect(resultSb.ToString(), ref currptr, endptr)) + while (!RespWriteUtils.TryWriteAsciiDirect(resultSb.ToString(), ref currptr, endptr)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref startptr, ref ptrHandle, ref currptr, ref endptr); output.Length = (int)(currptr - startptr); @@ -1115,7 +1115,7 @@ private bool NetworkCOMMAND_INFO() } else { - while (!RespWriteUtils.WriteArrayLength(count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(count, ref dcurr, dend)) SendAndReset(); for (var i = 0; i < count; i++) @@ -1125,12 +1125,12 @@ private bool NetworkCOMMAND_INFO() if (RespCommandsInfo.TryGetRespCommandInfo(cmdName, out var cmdInfo, true, true, logger) || storeWrapper.customCommandManager.TryGetCustomCommandInfo(cmdName, out cmdInfo)) { - while (!RespWriteUtils.WriteAsciiDirect(cmdInfo.RespFormat, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiDirect(cmdInfo.RespFormat, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); } } @@ -1166,12 +1166,12 @@ private bool NetworkCOMMAND_GETKEYS() parseState.TryExtractKeysFromSpecs(cmdInfo.KeySpecifications, out var keys); - while (!RespWriteUtils.WriteArrayLength(keys.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(keys.Count, ref dcurr, dend)) SendAndReset(); foreach (var key in keys) { - while (!RespWriteUtils.WriteBulkString(key.Span, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(key.Span, ref dcurr, dend)) SendAndReset(); } @@ -1204,23 +1204,23 @@ private bool NetworkCOMMAND_GETKEYSANDFLAGS() parseState.TryExtractKeysAndFlagsFromSpecs(cmdInfo.KeySpecifications, out var keys, out var flags); - while (!RespWriteUtils.WriteArrayLength(keys.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(keys.Count, ref dcurr, dend)) SendAndReset(); for (int i = 0; i < keys.Count; i++) { - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(keys[i].Span, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(keys[i].Span, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteArrayLength(flags[i].Length, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(flags[i].Length, ref dcurr, dend)) SendAndReset(); foreach (var flag in flags[i]) { - while (!RespWriteUtils.WriteBulkString(Encoding.ASCII.GetBytes(flag), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(Encoding.ASCII.GetBytes(flag), ref dcurr, dend)) SendAndReset(); } } @@ -1260,7 +1260,7 @@ private bool NetworkHELLO() // Validate protocol version if (!parseState.TryGetInt(tokenIdx++, out var localRespProtocolVersion)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_PROTOCOL_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_PROTOCOL_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -1306,7 +1306,7 @@ private bool NetworkHELLO() if (errorMsg != default) { - while (!RespWriteUtils.WriteError(errorMsg, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMsg, ref dcurr, dend)) SendAndReset(); return true; @@ -1328,7 +1328,7 @@ private bool NetworkTIME() var uSeconds = utcTime.ToString("ffffff"); var response = $"*2\r\n${seconds.ToString().Length}\r\n{seconds}\r\n${uSeconds.Length}\r\n{uSeconds}\r\n"; - while (!RespWriteUtils.WriteAsciiDirect(response, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiDirect(response, ref dcurr, dend)) SendAndReset(); return true; @@ -1359,7 +1359,7 @@ private bool NetworkAUTH() // NOTE: Some authenticators cannot accept username/password pairs if (!_authenticator.CanAuthenticate) { - while (!RespWriteUtils.WriteError("ERR Client sent AUTH, but configured authenticator does not accept passwords"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR Client sent AUTH, but configured authenticator does not accept passwords"u8, ref dcurr, dend)) SendAndReset(); return true; } @@ -1367,19 +1367,19 @@ private bool NetworkAUTH() // XXX: There should be high-level AuthenticatorException if (this.AuthenticateUser(username, password)) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { if (username.IsEmpty) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_WRONGPASS_INVALID_PASSWORD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_WRONGPASS_INVALID_PASSWORD, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_WRONGPASS_INVALID_USERNAME_PASSWORD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_WRONGPASS_INVALID_USERNAME_PASSWORD, ref dcurr, dend)) SendAndReset(); } } @@ -1404,7 +1404,7 @@ private bool NetworkMemoryUsage(ref TGarnetApi storageApi) // Calculations for nested types do not apply to garnet, but we are checking syntax for API compatibility if (!parseState.GetArgSliceByRef(1).ReadOnlySpan.EqualsUpperCaseSpanIgnoringCase(CmdStrings.SAMPLES)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; } @@ -1412,7 +1412,7 @@ private bool NetworkMemoryUsage(ref TGarnetApi storageApi) // Validate samples count if (!parseState.TryGetInt(2, out _)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -1422,12 +1422,12 @@ private bool NetworkMemoryUsage(ref TGarnetApi storageApi) if (status == GarnetStatus.OK) { - while (!RespWriteUtils.WriteInteger((int)memoryUsage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32((int)memoryUsage, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } @@ -1441,7 +1441,7 @@ private bool NetworkASYNC() { if (respProtocolVersion <= 2) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOT_SUPPORTED_RESP2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOT_SUPPORTED_RESP2, ref dcurr, dend)) SendAndReset(); return true; @@ -1483,13 +1483,13 @@ private bool NetworkASYNC() } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -1504,14 +1504,14 @@ void ProcessHelloCommand(byte? respProtocolVersion, ReadOnlySpan username, { if (respProtocolVersion.Value is < 2 or > 3) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_UNSUPPORTED_PROTOCOL_VERSION, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_UNSUPPORTED_PROTOCOL_VERSION, ref dcurr, dend)) SendAndReset(); return; } if (respProtocolVersion.Value != this.respProtocolVersion && asyncCompleted < asyncStarted) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_ASYNC_PROTOCOL_CHANGE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_ASYNC_PROTOCOL_CHANGE, ref dcurr, dend)) SendAndReset(); return; } @@ -1525,12 +1525,12 @@ void ProcessHelloCommand(byte? respProtocolVersion, ReadOnlySpan username, { if (username.IsEmpty) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_WRONGPASS_INVALID_PASSWORD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_WRONGPASS_INVALID_PASSWORD, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_WRONGPASS_INVALID_USERNAME_PASSWORD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_WRONGPASS_INVALID_USERNAME_PASSWORD, ref dcurr, dend)) SendAndReset(); } return; @@ -1555,32 +1555,32 @@ void ProcessHelloCommand(byte? respProtocolVersion, ReadOnlySpan username, if (this.respProtocolVersion == 2) { - while (!RespWriteUtils.WriteArrayLength(helloResult.Length * 2 + 2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(helloResult.Length * 2 + 2, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteMapLength(helloResult.Length + 1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteMapLength(helloResult.Length + 1, ref dcurr, dend)) SendAndReset(); } for (int i = 0; i < helloResult.Length; i++) { - while (!RespWriteUtils.WriteAsciiBulkString(helloResult[i].Item1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(helloResult[i].Item1, ref dcurr, dend)) SendAndReset(); if (helloResult[i].Item2 is int intValue) { - while (!RespWriteUtils.WriteInteger(intValue, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(intValue, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteAsciiBulkString(helloResult[i].Item2.ToString(), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString(helloResult[i].Item2.ToString(), ref dcurr, dend)) SendAndReset(); } } - while (!RespWriteUtils.WriteAsciiBulkString("modules", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteAsciiBulkString("modules", ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteArrayLength(0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(0, ref dcurr, dend)) SendAndReset(); } @@ -1640,7 +1640,7 @@ void FlushDb(RespCommand cmd) if (syntaxError) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return; } @@ -1651,7 +1651,7 @@ void FlushDb(RespCommand cmd) ExecuteFlushDb(unsafeTruncateLog); logger?.LogInformation($"Running {nameof(cmd)} {{async}} {{mode}}", async ? "async" : "sync", unsafeTruncateLog ? " with unsafetruncatelog." : string.Empty); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } diff --git a/libs/server/Resp/BasicEtagCommands.cs b/libs/server/Resp/BasicEtagCommands.cs index 5c68e5a863..23f4ab7d6d 100644 --- a/libs/server/Resp/BasicEtagCommands.cs +++ b/libs/server/Resp/BasicEtagCommands.cs @@ -31,7 +31,7 @@ private bool NetworkGETWITHETAG(ref TGarnetApi storageApi) { case GarnetStatus.NOTFOUND: Debug.Assert(output.IsSpanByte); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; default: @@ -63,7 +63,7 @@ private bool NetworkGETIFNOTMATCH(ref TGarnetApi storageApi) { case GarnetStatus.NOTFOUND: Debug.Assert(output.IsSpanByte); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; default: @@ -112,7 +112,7 @@ private bool NetworkSETIFMATCH(ref TGarnetApi storageApi) if (!errorMessage.IsEmpty) { - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; } diff --git a/libs/server/Resp/Bitmap/BitmapCommands.cs b/libs/server/Resp/Bitmap/BitmapCommands.cs index 17d3f7d3a6..d2ab63a83c 100644 --- a/libs/server/Resp/Bitmap/BitmapCommands.cs +++ b/libs/server/Resp/Bitmap/BitmapCommands.cs @@ -134,7 +134,7 @@ private bool NetworkStringSetBit(ref TGarnetApi storageApi) // Validate offset if (!parseState.TryGetLong(1, out _)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_BITOFFSET_IS_NOT_INTEGER, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_BITOFFSET_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -144,7 +144,7 @@ private bool NetworkStringSetBit(ref TGarnetApi storageApi) var bSetValSlice = parseState.GetArgSliceByRef(2).ReadOnlySpan; if (bSetValSlice.Length != 1 || (bSetValSlice[0] != '0' && bSetValSlice[0] != '1')) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_BIT_IS_NOT_INTEGER, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_BIT_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -180,7 +180,7 @@ private bool NetworkStringGetBit(ref TGarnetApi storageApi) // Validate offset if (!parseState.TryGetLong(1, out _)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_BITOFFSET_IS_NOT_INTEGER, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_BITOFFSET_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -192,7 +192,7 @@ private bool NetworkStringGetBit(ref TGarnetApi storageApi) var status = storageApi.StringGetBit(ref sbKey, ref input, ref o); if (status == GarnetStatus.NOTFOUND) - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); else dcurr += o.Length; @@ -221,7 +221,7 @@ private bool NetworkStringBitCount(ref TGarnetApi storageApi) { if (!parseState.TryGetInt(1, out _) || (parseState.Count > 2 && !parseState.TryGetInt(2, out _))) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -243,7 +243,7 @@ private bool NetworkStringBitCount(ref TGarnetApi storageApi) } else if (status == GarnetStatus.NOTFOUND) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); } @@ -269,7 +269,7 @@ private bool NetworkStringBitPosition(ref TGarnetApi storageApi) var bSetValSlice = parseState.GetArgSliceByRef(1).ReadOnlySpan; if (bSetValSlice.Length != 1 || (bSetValSlice[0] != '0' && bSetValSlice[0] != '1')) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_BIT_IS_NOT_INTEGER, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_BIT_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -281,7 +281,7 @@ private bool NetworkStringBitPosition(ref TGarnetApi storageApi) if (!parseState.TryGetInt(2, out _) || (parseState.Count > 3 && !parseState.TryGetInt(3, out _))) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -295,7 +295,7 @@ private bool NetworkStringBitPosition(ref TGarnetApi storageApi) if (!sbOffsetType.EqualsUpperCaseSpanIgnoringCase("BIT"u8) && !sbOffsetType.EqualsUpperCaseSpanIgnoringCase("BYTE"u8)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; @@ -318,7 +318,7 @@ private bool NetworkStringBitPosition(ref TGarnetApi storageApi) else if (status == GarnetStatus.NOTFOUND) { var resp = bSetValSlice[0] == '0' ? CmdStrings.RESP_RETURN_VAL_0 : CmdStrings.RESP_RETURN_VAL_N1; - while (!RespWriteUtils.WriteDirect(resp, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(resp, ref dcurr, dend)) SendAndReset(); } @@ -334,7 +334,7 @@ private bool NetworkStringBitOperation(BitmapOperation bitOp, ref TG // Too few keys if (parseState.Count < 2) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_NUMBER_OF_ARGUMENTS, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_NUMBER_OF_ARGUMENTS, ref dcurr, dend)) SendAndReset(); return true; @@ -342,7 +342,7 @@ private bool NetworkStringBitOperation(BitmapOperation bitOp, ref TG if (parseState.Count > 64) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_BITOP_KEY_LIMIT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_BITOP_KEY_LIMIT, ref dcurr, dend)) SendAndReset(); return true; } @@ -350,7 +350,7 @@ private bool NetworkStringBitOperation(BitmapOperation bitOp, ref TG var input = new RawStringInput(RespCommand.BITOP, ref parseState); _ = storageApi.StringBitOperation(ref input, bitOp, out var result); - while (!RespWriteUtils.WriteInteger(result, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt64(result, ref dcurr, dend)) SendAndReset(); return true; @@ -393,7 +393,7 @@ private bool StringBitField(ref TGarnetApi storageApi, bool readOnly // Validate overflow type if (!parseState.TryGetBitFieldOverflow(currTokenIdx, out _)) { - while (!RespWriteUtils.WriteError( + while (!RespWriteUtils.TryWriteError( $"ERR Overflow type {parseState.GetString(currTokenIdx)} not supported", ref dcurr, dend)) SendAndReset(); @@ -420,7 +420,7 @@ private bool StringBitField(ref TGarnetApi storageApi, bool readOnly bitCount > 64 || (bitCount == 64 && encodingArg[0] == 'u')) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_INVALID_BITFIELD_TYPE, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_INVALID_BITFIELD_TYPE, ref dcurr, dend)) SendAndReset(); return true; @@ -433,7 +433,7 @@ private bool StringBitField(ref TGarnetApi storageApi, bool readOnly if (!isOffsetValid) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_BITOFFSET_IS_NOT_INTEGER, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_BITOFFSET_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -448,7 +448,7 @@ private bool StringBitField(ref TGarnetApi storageApi, bool readOnly { if (readOnly) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; } @@ -461,7 +461,7 @@ private bool StringBitField(ref TGarnetApi storageApi, bool readOnly op = RespCommand.INCRBY; else { - while (!RespWriteUtils.WriteError( + while (!RespWriteUtils.TryWriteError( $"ERR Bitfield command {Encoding.ASCII.GetString(command)} not supported", ref dcurr, dend)) SendAndReset(); @@ -472,7 +472,7 @@ private bool StringBitField(ref TGarnetApi storageApi, bool readOnly var valueSlice = parseState.GetArgSliceByRef(currTokenIdx); if (!parseState.TryGetLong(currTokenIdx, out _)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -483,7 +483,7 @@ private bool StringBitField(ref TGarnetApi storageApi, bool readOnly } } - while (!RespWriteUtils.WriteArrayLength(secondaryCommandArgs.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(secondaryCommandArgs.Count, ref dcurr, dend)) SendAndReset(); var input = new RawStringInput(RespCommand.BITFIELD); @@ -512,7 +512,7 @@ private bool StringBitField(ref TGarnetApi storageApi, bool readOnly if (status == GarnetStatus.NOTFOUND && opCode == RespCommand.GET) { - while (!RespWriteUtils.WriteArrayItem(0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayItem(0, ref dcurr, dend)) SendAndReset(); } else diff --git a/libs/server/Resp/ClientCommands.cs b/libs/server/Resp/ClientCommands.cs index dd4bc2128a..17324faf39 100644 --- a/libs/server/Resp/ClientCommands.cs +++ b/libs/server/Resp/ClientCommands.cs @@ -159,7 +159,7 @@ private bool NetworkCLIENTLIST() } var result = resultSb.ToString(); - while (!RespWriteUtils.WriteUtf8BulkString(result, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteUtf8BulkString(result, ref dcurr, dend)) SendAndReset(); return true; @@ -193,7 +193,7 @@ private bool NetworkCLIENTINFO() WriteClientInfo(storeWrapper.clusterProvider, resultSb, this, Environment.TickCount64); var result = resultSb.ToString(); - while (!RespWriteUtils.WriteSimpleString(result, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString(result, ref dcurr, dend)) SendAndReset(); return true; @@ -226,7 +226,7 @@ private bool NetworkCLIENTKILL() { _ = session.TryKill(); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -234,7 +234,7 @@ private bool NetworkCLIENTKILL() } } - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NO_SUCH_CLIENT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NO_SUCH_CLIENT, ref dcurr, dend)) SendAndReset(); return true; @@ -401,7 +401,7 @@ private bool NetworkCLIENTKILL() } // Hand back result, which is count of clients _actually_ killed - while (!RespWriteUtils.WriteInteger(killed, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(killed, ref dcurr, dend)) SendAndReset(); return true; @@ -501,12 +501,12 @@ private bool NetworkCLIENTGETNAME() if (string.IsNullOrEmpty(this.clientName)) { - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteUtf8BulkString(this.clientName, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteUtf8BulkString(this.clientName, ref dcurr, dend)) SendAndReset(); } @@ -531,7 +531,7 @@ private bool NetworkCLIENTSETNAME() this.clientName = name; - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -562,7 +562,7 @@ private bool NetworkCLIENTSETINFO() return AbortWithErrorMessage(CmdStrings.RESP_SYNTAX_ERROR); } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/server/Resp/HyperLogLog/HyperLogLogCommands.cs b/libs/server/Resp/HyperLogLog/HyperLogLogCommands.cs index 74077929a5..3ccff29217 100644 --- a/libs/server/Resp/HyperLogLog/HyperLogLogCommands.cs +++ b/libs/server/Resp/HyperLogLog/HyperLogLogCommands.cs @@ -39,7 +39,7 @@ private bool HyperLogLogAdd(ref TGarnetApi storageApi) // Invalid HLL Type if (*output == 0xFF) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE_HLL, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE_HLL, ref dcurr, dend)) SendAndReset(); return true; } @@ -49,12 +49,12 @@ private bool HyperLogLogAdd(ref TGarnetApi storageApi) if (pfaddUpdated > 0) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_1, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); } return true; @@ -81,12 +81,12 @@ private bool HyperLogLogLength(ref TGarnetApi storageApi) storageApi.HyperLogLogLength(ref input, out var cardinality, out var error); if (error) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE_HLL, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE_HLL, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteInteger(cardinality, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt64(cardinality, ref dcurr, dend)) SendAndReset(); } @@ -112,14 +112,14 @@ private bool HyperLogLogMerge(ref TGarnetApi storageApi) // Invalid Type if (error) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE_HLL, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE_HLL, ref dcurr, dend)) SendAndReset(); return true; } if (status == GarnetStatus.OK) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } return true; diff --git a/libs/server/Resp/KeyAdminCommands.cs b/libs/server/Resp/KeyAdminCommands.cs index d166013c67..3fa2aa1a3a 100644 --- a/libs/server/Resp/KeyAdminCommands.cs +++ b/libs/server/Resp/KeyAdminCommands.cs @@ -34,7 +34,7 @@ bool NetworkRESTORE(ref TGarnetApi storageApi) if (!parseState.TryGetInt(parseState.Count - 2, out var expiry)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_TIMEOUT_NOT_VALID_FLOAT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_TIMEOUT_NOT_VALID_FLOAT, ref dcurr, dend)) SendAndReset(); return true; } @@ -46,7 +46,7 @@ bool NetworkRESTORE(ref TGarnetApi storageApi) // Restore is only implemented for string type if (valueSpan[0] != 0x00) { - while (!RespWriteUtils.WriteError("ERR RESTORE currently only supports string types", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR RESTORE currently only supports string types", ref dcurr, dend)) SendAndReset(); return true; } @@ -54,7 +54,7 @@ bool NetworkRESTORE(ref TGarnetApi storageApi) // check if length of value is at least 10 if (valueSpan.Length < 10) { - while (!RespWriteUtils.WriteError("ERR DUMP payload version or checksum are wrong", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR DUMP payload version or checksum are wrong", ref dcurr, dend)) SendAndReset(); return true; } @@ -66,7 +66,7 @@ bool NetworkRESTORE(ref TGarnetApi storageApi) if (rdbVersion > RDB_VERSION) { - while (!RespWriteUtils.WriteError("ERR DUMP payload version or checksum are wrong", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR DUMP payload version or checksum are wrong", ref dcurr, dend)) SendAndReset(); return true; } @@ -82,7 +82,7 @@ bool NetworkRESTORE(ref TGarnetApi storageApi) if (calculatedCrc.SequenceCompareTo(payloadCrc) != 0) { - while (!RespWriteUtils.WriteError("ERR DUMP payload version or checksum are wrong", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR DUMP payload version or checksum are wrong", ref dcurr, dend)) SendAndReset(); return true; } @@ -91,7 +91,7 @@ bool NetworkRESTORE(ref TGarnetApi storageApi) // decode the length of payload if (!RespLengthEncodingUtils.TryReadLength(valueSpan.Slice(1), out var length, out var payloadStart)) { - while (!RespWriteUtils.WriteError("ERR DUMP payload length format is invalid", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR DUMP payload length format is invalid", ref dcurr, dend)) SendAndReset(); return true; } @@ -120,12 +120,12 @@ bool NetworkRESTORE(ref TGarnetApi storageApi) if (status is GarnetStatus.NOTFOUND) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_BUSSYKEY, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_BUSSYKEY, ref dcurr, dend)) SendAndReset(); return true; @@ -148,7 +148,7 @@ bool NetworkDUMP(ref TGarnetApi storageApi) if (status is GarnetStatus.NOTFOUND) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); return true; } @@ -157,7 +157,7 @@ bool NetworkDUMP(ref TGarnetApi storageApi) if (!RespLengthEncodingUtils.TryWriteLength(value.ReadOnlySpan.Length, encodedLength, out var bytesWritten)) { - while (!RespWriteUtils.WriteError("ERR DUMP payload length is invalid", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR DUMP payload length is invalid", ref dcurr, dend)) SendAndReset(); return true; } @@ -166,8 +166,8 @@ bool NetworkDUMP(ref TGarnetApi storageApi) // Len of the dump (payload type + redis encoded payload len + payload len + rdb version + crc64) var len = 1 + encodedLength.Length + value.ReadOnlySpan.Length + 2 + 8; - Span lengthInASCIIBytes = stackalloc byte[NumUtils.NumDigitsInLong(len)]; - var lengthInASCIIBytesLen = NumUtils.LongToSpanByte(len, lengthInASCIIBytes); + Span lengthInASCIIBytes = stackalloc byte[NumUtils.CountDigits(len)]; + var lengthInASCIIBytesLen = NumUtils.WriteInt64(len, lengthInASCIIBytes); // Total len (% + length of ascii bytes + CR LF + payload type + redis encoded payload len + payload len + rdb version + crc64 + CR LF) var totalLength = 1 + lengthInASCIIBytesLen + 2 + 1 + encodedLength.Length + value.ReadOnlySpan.Length + 2 + 8 + 2; @@ -246,7 +246,7 @@ private bool NetworkRENAME(ref TGarnetApi storageApi) { if (!parseState.GetArgSliceByRef(2).ReadOnlySpan.EqualsUpperCaseSpanIgnoringCase(CmdStrings.WITHETAG)) { - while (!RespWriteUtils.WriteError($"ERR Unsupported option {parseState.GetString(2)}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unsupported option {parseState.GetString(2)}", ref dcurr, dend)) SendAndReset(); return true; } @@ -259,11 +259,11 @@ private bool NetworkRENAME(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_NOSUCHKEY, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_NOSUCHKEY, ref dcurr, dend)) SendAndReset(); break; } @@ -290,7 +290,7 @@ private bool NetworkRENAMENX(ref TGarnetApi storageApi) { if (!parseState.GetArgSliceByRef(2).ReadOnlySpan.EqualsUpperCaseSpanIgnoringCase(CmdStrings.WITHETAG)) { - while (!RespWriteUtils.WriteError($"ERR Unsupported option {parseState.GetString(2)}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unsupported option {parseState.GetString(2)}", ref dcurr, dend)) SendAndReset(); return true; } @@ -304,12 +304,12 @@ private bool NetworkRENAMENX(ref TGarnetApi storageApi) { // Integer reply: 1 if key was renamed to newkey. // Integer reply: 0 if newkey already exists. - while (!RespWriteUtils.WriteInteger(result, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(result, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_NOSUCHKEY, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_NOSUCHKEY, ref dcurr, dend)) SendAndReset(); } @@ -344,7 +344,7 @@ private bool NetworkGETDEL(ref TGarnetApi garnetApi) else { Debug.Assert(o.IsSpanByte); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); } @@ -376,7 +376,7 @@ private bool NetworkEXISTS(ref TGarnetApi storageApi) exists++; } - while (!RespWriteUtils.WriteInteger(exists, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(exists, ref dcurr, dend)) SendAndReset(); return true; @@ -401,7 +401,7 @@ private bool NetworkEXPIRE(RespCommand command, ref TGarnetApi stora var key = parseState.GetArgSliceByRef(0); if (!parseState.TryGetInt(1, out _)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -413,7 +413,7 @@ private bool NetworkEXPIRE(RespCommand command, ref TGarnetApi stora { var optionStr = parseState.GetString(2); - while (!RespWriteUtils.WriteError($"ERR Unsupported option {optionStr}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unsupported option {optionStr}", ref dcurr, dend)) SendAndReset(); return true; } @@ -424,7 +424,7 @@ private bool NetworkEXPIRE(RespCommand command, ref TGarnetApi stora { var optionStr = parseState.GetString(3); - while (!RespWriteUtils.WriteError($"ERR Unsupported option {optionStr}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unsupported option {optionStr}", ref dcurr, dend)) SendAndReset(); return true; } @@ -444,7 +444,7 @@ private bool NetworkEXPIRE(RespCommand command, ref TGarnetApi stora } else { - while (!RespWriteUtils.WriteError( + while (!RespWriteUtils.TryWriteError( "ERR NX and XX, GT or LT options at the same time are not compatible", ref dcurr, dend)) SendAndReset(); @@ -457,12 +457,12 @@ private bool NetworkEXPIRE(RespCommand command, ref TGarnetApi stora if (status == GarnetStatus.OK && timeoutSet) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_1, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); } @@ -488,7 +488,7 @@ private bool NetworkEXPIREAT(RespCommand command, ref TGarnetApi sto var key = parseState.GetArgSliceByRef(0); if (!parseState.TryGetLong(1, out _)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -501,7 +501,7 @@ private bool NetworkEXPIREAT(RespCommand command, ref TGarnetApi sto { var optionStr = parseState.GetString(2); - while (!RespWriteUtils.WriteError($"ERR Unsupported option {optionStr}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unsupported option {optionStr}", ref dcurr, dend)) SendAndReset(); return true; } @@ -513,7 +513,7 @@ private bool NetworkEXPIREAT(RespCommand command, ref TGarnetApi sto { var optionStr = parseState.GetString(3); - while (!RespWriteUtils.WriteError($"ERR Unsupported option {optionStr}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Unsupported option {optionStr}", ref dcurr, dend)) SendAndReset(); return true; } @@ -532,7 +532,7 @@ private bool NetworkEXPIREAT(RespCommand command, ref TGarnetApi sto } else { - while (!RespWriteUtils.WriteError("ERR NX and XX, GT or LT options at the same time are not compatible", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR NX and XX, GT or LT options at the same time are not compatible", ref dcurr, dend)) SendAndReset(); } } @@ -542,12 +542,12 @@ private bool NetworkEXPIREAT(RespCommand command, ref TGarnetApi sto if (status == GarnetStatus.OK && timeoutSet) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_1, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); } @@ -573,12 +573,12 @@ private bool NetworkPERSIST(ref TGarnetApi storageApi) if (status == GarnetStatus.OK) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_1, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); } return true; @@ -614,7 +614,7 @@ private bool NetworkTTL(RespCommand command, ref TGarnetApi storageA } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_N2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_N2, ref dcurr, dend)) SendAndReset(); } return true; @@ -650,7 +650,7 @@ private bool NetworkEXPIRETIME(RespCommand command, ref TGarnetApi s } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_N2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_N2, ref dcurr, dend)) SendAndReset(); } return true; diff --git a/libs/server/Resp/Objects/HashCommands.cs b/libs/server/Resp/Objects/HashCommands.cs index 1062e68ade..6bfbe0add3 100644 --- a/libs/server/Resp/Objects/HashCommands.cs +++ b/libs/server/Resp/Objects/HashCommands.cs @@ -54,18 +54,18 @@ private unsafe bool HashSet(RespCommand command, ref TGarnetApi stor switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: if (command == RespCommand.HMSET) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); } break; @@ -105,11 +105,11 @@ private bool HashGet(RespCommand command, ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -149,11 +149,11 @@ private bool HashGetAll(RespCommand command, ref TGarnetApi storageA ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_EMPTYLIST, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_EMPTYLIST, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -194,11 +194,11 @@ private bool HashGetMultiple(RespCommand command, ref TGarnetApi sto break; case GarnetStatus.NOTFOUND: // Write an empty array of count - 1 elements with null values. - while (!RespWriteUtils.WriteArrayWithNullElements(parseState.Count - 1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayWithNullElements(parseState.Count - 1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -230,7 +230,7 @@ private bool HashRandomField(RespCommand command, ref TGarnetApi sto { if (!parseState.TryGetInt(1, out paramCount)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -244,7 +244,7 @@ private bool HashRandomField(RespCommand command, ref TGarnetApi sto if (!withValuesSlice.ReadOnlySpan.EqualsUpperCaseSpanIgnoringCase(CmdStrings.WITHVALUES)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; } @@ -282,11 +282,11 @@ private bool HashRandomField(RespCommand command, ref TGarnetApi sto break; case GarnetStatus.NOTFOUND: var respBytes = includedCount ? CmdStrings.RESP_EMPTYLIST : CmdStrings.RESP_ERRNOTFOUND; - while (!RespWriteUtils.WriteDirect(respBytes, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(respBytes, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -322,15 +322,15 @@ private unsafe bool HashLength(ref TGarnetApi storageApi) { case GarnetStatus.OK: // Process output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -365,15 +365,15 @@ private unsafe bool HashStrLength(ref TGarnetApi storageApi) { case GarnetStatus.OK: // Process output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -407,15 +407,15 @@ private unsafe bool HashDelete(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -448,15 +448,15 @@ private unsafe bool HashExists(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -508,11 +508,11 @@ private unsafe bool HashKeys(RespCommand command, ref TGarnetApi sto ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -561,7 +561,7 @@ private unsafe bool HashIncrement(RespCommand command, ref TGarnetAp switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: @@ -655,15 +655,15 @@ private unsafe bool HashExpire(RespCommand command, ref TGarnetApi s switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteArrayLength(numFields, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(numFields, ref dcurr, dend)) SendAndReset(); for (var i = 0; i < numFields; i++) { - while (!RespWriteUtils.WriteInteger(-2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(-2, ref dcurr, dend)) SendAndReset(); } break; @@ -745,15 +745,15 @@ private unsafe bool HashTimeToLive(RespCommand command, ref TGarnetA switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteArrayLength(numFields, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(numFields, ref dcurr, dend)) SendAndReset(); for (var i = 0; i < numFields; i++) { - while (!RespWriteUtils.WriteInteger(-2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(-2, ref dcurr, dend)) SendAndReset(); } break; @@ -807,15 +807,15 @@ private unsafe bool HashPersist(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteArrayLength(numFields, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(numFields, ref dcurr, dend)) SendAndReset(); for (var i = 0; i < numFields; i++) { - while (!RespWriteUtils.WriteInteger(-2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(-2, ref dcurr, dend)) SendAndReset(); } break; diff --git a/libs/server/Resp/Objects/ListCommands.cs b/libs/server/Resp/Objects/ListCommands.cs index 89d682da68..5ab15d9530 100644 --- a/libs/server/Resp/Objects/ListCommands.cs +++ b/libs/server/Resp/Objects/ListCommands.cs @@ -49,13 +49,13 @@ private unsafe bool ListPush(RespCommand command, ref TGarnetApi sto if (status == GarnetStatus.WRONGTYPE) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); } else { // Write result to output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); } return true; @@ -87,7 +87,7 @@ private unsafe bool ListPop(RespCommand command, ref TGarnetApi stor // Read count if (!parseState.TryGetInt(1, out popCount)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -119,11 +119,11 @@ private unsafe bool ListPop(RespCommand command, ref TGarnetApi stor ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -166,11 +166,11 @@ private unsafe bool ListPosition(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -249,28 +249,28 @@ private unsafe bool ListPopMultiple(ref TGarnetApi storageApi) switch (statusOp) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(key.Span, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(key.Span, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteArrayLength(elements.Length, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(elements.Length, ref dcurr, dend)) SendAndReset(); foreach (var element in elements) { - while (!RespWriteUtils.WriteBulkString(element.Span, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(element.Span, ref dcurr, dend)) SendAndReset(); } break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteNullArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNullArray(ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -294,7 +294,7 @@ private bool ListBlockingPop(RespCommand command) if (!parseState.TryGetDouble(parseState.Count - 1, out var timeout)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_TIMEOUT_NOT_VALID_FLOAT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_TIMEOUT_NOT_VALID_FLOAT, ref dcurr, dend)) SendAndReset(); return true; } @@ -306,18 +306,18 @@ private bool ListBlockingPop(RespCommand command) if (!result.Found) { - while (!RespWriteUtils.WriteNullArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNullArray(ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(new Span(result.Key), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(result.Key), ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(new Span(result.Item), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(result.Item), ref dcurr, dend)) SendAndReset(); } @@ -338,7 +338,7 @@ private unsafe bool ListBlockingMove() if (!parseState.TryGetDouble(4, out var timeout)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_TIMEOUT_NOT_VALID_FLOAT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_TIMEOUT_NOT_VALID_FLOAT, ref dcurr, dend)) SendAndReset(); return true; } @@ -364,7 +364,7 @@ private bool ListBlockingPopPush() if (!parseState.TryGetDouble(2, out var timeout)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_TIMEOUT_NOT_VALID_FLOAT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_TIMEOUT_NOT_VALID_FLOAT, ref dcurr, dend)) SendAndReset(); return true; } @@ -400,12 +400,12 @@ private bool ListBlockingMove(ArgSlice srcKey, ArgSlice dstKey, ArgSlice srcDir, if (!result.Found) { - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteBulkString(new Span(result.Item), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(result.Item), ref dcurr, dend)) SendAndReset(); } @@ -439,16 +439,16 @@ private bool ListLength(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: // Process output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; } @@ -479,7 +479,7 @@ private bool ListTrim(ref TGarnetApi storageApi) if (!parseState.TryGetInt(1, out var start) || !parseState.TryGetInt(2, out var stop)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -493,13 +493,13 @@ private bool ListTrim(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: //GarnetStatus.OK or NOTFOUND have same result // no need to process output, just send OK - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); break; } @@ -530,7 +530,7 @@ private bool ListRange(ref TGarnetApi storageApi) if (!parseState.TryGetInt(1, out var start) || !parseState.TryGetInt(2, out var end)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -551,11 +551,11 @@ private bool ListRange(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_EMPTYLIST, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_EMPTYLIST, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -584,7 +584,7 @@ private bool ListIndex(ref TGarnetApi storageApi) // Read index param if (!parseState.TryGetInt(1, out var index)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -612,14 +612,14 @@ private bool ListIndex(ref TGarnetApi storageApi) error = CmdStrings.RESP_ERRNOTFOUND; break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } if (!error.IsEmpty) { - while (!RespWriteUtils.WriteDirect(error, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(error, ref dcurr, dend)) SendAndReset(); } @@ -658,15 +658,15 @@ private bool ListInsert(ref TGarnetApi storageApi) if (output.result1 == int.MinValue) return false; //process output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -696,7 +696,7 @@ private bool ListRemove(ref TGarnetApi storageApi) // Get count parameter if (!parseState.TryGetInt(1, out var nCount)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -714,15 +714,15 @@ private bool ListRemove(ref TGarnetApi storageApi) if (output.result1 == int.MinValue) return false; //process output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -767,18 +767,18 @@ private bool ListMove(ref TGarnetApi storageApi) case GarnetStatus.OK: if (node != null) { - while (!RespWriteUtils.WriteBulkString(node, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(node, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); } break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -811,18 +811,18 @@ private bool ListRightPopLeftPush(ref TGarnetApi storageApi) case GarnetStatus.OK: if (node != null) { - while (!RespWriteUtils.WriteBulkString(node, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(node, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); } break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -890,11 +890,11 @@ public bool ListSet(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_NOSUCHKEY, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_NOSUCHKEY, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -981,24 +981,24 @@ private unsafe bool ListBlockingPopMultiple() if (!result.Found) { - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); return true; } - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(result.Key, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(result.Key, ref dcurr, dend)) SendAndReset(); var elements = result.Items; - while (!RespWriteUtils.WriteArrayLength(elements.Length, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(elements.Length, ref dcurr, dend)) SendAndReset(); foreach (var element in elements) { - while (!RespWriteUtils.WriteBulkString(element, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(element, ref dcurr, dend)) SendAndReset(); } diff --git a/libs/server/Resp/Objects/ObjectStoreUtils.cs b/libs/server/Resp/Objects/ObjectStoreUtils.cs index 8645733d54..407ebf5ebc 100644 --- a/libs/server/Resp/Objects/ObjectStoreUtils.cs +++ b/libs/server/Resp/Objects/ObjectStoreUtils.cs @@ -33,7 +33,7 @@ private bool AbortWithWrongNumberOfArguments(string cmdName) private bool AbortWithErrorMessage(ReadOnlySpan errorMessage) { // Print error message to result stream - while (!RespWriteUtils.WriteError(errorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMessage, ref dcurr, dend)) SendAndReset(); return true; diff --git a/libs/server/Resp/Objects/SetCommands.cs b/libs/server/Resp/Objects/SetCommands.cs index deee98c06a..6c130fda1d 100644 --- a/libs/server/Resp/Objects/SetCommands.cs +++ b/libs/server/Resp/Objects/SetCommands.cs @@ -43,12 +43,12 @@ private unsafe bool SetAdd(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: // Write result to output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; } @@ -87,24 +87,24 @@ private bool SetIntersect(ref TGarnetApi storageApi) if (result != null) { resultCount = result.Count; - while (!RespWriteUtils.WriteArrayLength(resultCount, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(resultCount, ref dcurr, dend)) SendAndReset(); foreach (var item in result) { - while (!RespWriteUtils.WriteBulkString(item, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(item, ref dcurr, dend)) SendAndReset(); } } else { - while (!RespWriteUtils.WriteArrayLength(resultCount, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(resultCount, ref dcurr, dend)) SendAndReset(); } break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -140,11 +140,11 @@ private bool SetIntersectStore(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(output, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -206,11 +206,11 @@ private bool SetIntersectLength(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(result, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(result, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -247,17 +247,17 @@ private bool SetUnion(ref TGarnetApi storageApi) case GarnetStatus.OK: // write the size of result var resultCount = result.Count; - while (!RespWriteUtils.WriteArrayLength(resultCount, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(resultCount, ref dcurr, dend)) SendAndReset(); foreach (var item in result) { - while (!RespWriteUtils.WriteBulkString(item, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(item, ref dcurr, dend)) SendAndReset(); } break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -293,11 +293,11 @@ private bool SetUnionStore(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(output, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -335,15 +335,15 @@ private unsafe bool SetRemove(ref TGarnetApi storageApi) { case GarnetStatus.OK: // Write result to output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -379,15 +379,15 @@ private unsafe bool SetLength(ref TGarnetApi storageApi) { case GarnetStatus.OK: // Process output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -429,11 +429,11 @@ private unsafe bool SetMembers(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -484,25 +484,25 @@ private unsafe bool SetIsMember(RespCommand cmd, ref TGarnetApi stor case GarnetStatus.NOTFOUND: if (isSingle) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); } else { var count = parseState.Count - 1; // Remove key - while (!RespWriteUtils.WriteArrayLength(count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(count, ref dcurr, dend)) SendAndReset(); for (var i = 0; i < count; i++) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); } } break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -534,7 +534,7 @@ private unsafe bool SetPop(ref TGarnetApi storageApi) // Prepare response if (!parseState.TryGetInt(1, out countParameter) || countParameter < 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -542,7 +542,7 @@ private unsafe bool SetPop(ref TGarnetApi storageApi) if (countParameter == 0) { - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); return true; @@ -565,11 +565,11 @@ private unsafe bool SetPop(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -606,15 +606,15 @@ private unsafe bool SetMove(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(output, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -650,7 +650,7 @@ private unsafe bool SetRandomMember(ref TGarnetApi storageApi) // Prepare response if (!parseState.TryGetInt(1, out countParameter)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -658,7 +658,7 @@ private unsafe bool SetRandomMember(ref TGarnetApi storageApi) if (countParameter == 0) { - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); return true; @@ -686,17 +686,17 @@ private unsafe bool SetRandomMember(ref TGarnetApi storageApi) case GarnetStatus.NOTFOUND: if (parseState.Count == 2) { - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -730,22 +730,22 @@ private bool SetDiff(ref TGarnetApi storageApi) case GarnetStatus.OK: if (output == null || output.Count == 0) { - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteArrayLength(output.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(output.Count, ref dcurr, dend)) SendAndReset(); foreach (var item in output) { - while (!RespWriteUtils.WriteBulkString(item, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(item, ref dcurr, dend)) SendAndReset(); } } break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -774,11 +774,11 @@ private bool SetDiffStore(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(output, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } diff --git a/libs/server/Resp/Objects/SharedObjectCommands.cs b/libs/server/Resp/Objects/SharedObjectCommands.cs index d2ad5cbcf2..4c38efa613 100644 --- a/libs/server/Resp/Objects/SharedObjectCommands.cs +++ b/libs/server/Resp/Objects/SharedObjectCommands.cs @@ -41,7 +41,7 @@ private unsafe bool ObjectScan(GarnetObjectType objectType, ref TGar // Get cursor value if (!parseState.TryGetInt(1, out var cursorValue) || cursorValue < 0) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_CURSORVALUE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_CURSORVALUE, ref dcurr, dend)) SendAndReset(); return true; } @@ -80,13 +80,13 @@ private unsafe bool ObjectScan(GarnetObjectType objectType, ref TGar return false; break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteScanOutputHeader(0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteScanOutputHeader(0, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } diff --git a/libs/server/Resp/Objects/SortedSetCommands.cs b/libs/server/Resp/Objects/SortedSetCommands.cs index 136372b9b2..e04c353fa4 100644 --- a/libs/server/Resp/Objects/SortedSetCommands.cs +++ b/libs/server/Resp/Objects/SortedSetCommands.cs @@ -42,7 +42,7 @@ private unsafe bool SortedSetAdd(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: @@ -80,15 +80,15 @@ private unsafe bool SortedSetRemove(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(rmwOutput.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(rmwOutput.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -122,15 +122,15 @@ private unsafe bool SortedSetLength(ref TGarnetApi storageApi) { case GarnetStatus.OK: // Process output - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -183,11 +183,11 @@ private unsafe bool SortedSetRange(RespCommand command, ref TGarnetA ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -215,11 +215,11 @@ private unsafe bool SortedSetRangeStore(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.OK: - while (!RespWriteUtils.WriteInteger(result, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(result, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -262,11 +262,11 @@ private unsafe bool SortedSetScore(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -309,11 +309,11 @@ private unsafe bool SortedSetScores(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteArrayWithNullElements(parseState.Count - 1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayWithNullElements(parseState.Count - 1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -348,7 +348,7 @@ private unsafe bool SortedSetPop(RespCommand command, ref TGarnetApi // Read count if (!parseState.TryGetInt(1, out popCount)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_OUT_OF_RANGE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_OUT_OF_RANGE, ref dcurr, dend)) SendAndReset(); return true; @@ -378,11 +378,11 @@ private unsafe bool SortedSetPop(RespCommand command, ref TGarnetApi ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -468,37 +468,37 @@ private unsafe bool SortedSetMPop(ref TGarnetApi storageApi) if (pairs == null || pairs.Length == 0) { // No elements found - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); } else { // Write array with 2 elements: key and array of elements - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); // Write key - while (!RespWriteUtils.WriteBulkString(poppedKey.ReadOnlySpan, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(poppedKey.ReadOnlySpan, ref dcurr, dend)) SendAndReset(); // Write array of member-score pairs - while (!RespWriteUtils.WriteArrayLength(pairs.Length, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(pairs.Length, ref dcurr, dend)) SendAndReset(); foreach (var (member, score) in pairs) { - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(member.ReadOnlySpan, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(member.ReadOnlySpan, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(score.ReadOnlySpan, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(score.ReadOnlySpan, ref dcurr, dend)) SendAndReset(); } } break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -539,11 +539,11 @@ private unsafe bool SortedSetCount(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -597,21 +597,21 @@ private unsafe bool SortedSetLengthByValue(RespCommand command, ref if (output.result1 == int.MaxValue) { // Error in arguments - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_STRING, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_MIN_MAX_NOT_VALID_STRING, ref dcurr, dend)) SendAndReset(); } else if (output.result1 == int.MinValue) // command partially executed return false; else - while (!RespWriteUtils.WriteInteger(output.result1, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(output.result1, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -655,7 +655,7 @@ private unsafe bool SortedSetIncrement(ref TGarnetApi storageApi) ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -691,7 +691,7 @@ private unsafe bool SortedSetRank(RespCommand command, ref TGarnetAp if (!withScoreSlice.ReadOnlySpan.EqualsUpperCaseSpanIgnoringCase(CmdStrings.WITHSCORE)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; @@ -723,11 +723,11 @@ private unsafe bool SortedSetRank(RespCommand command, ref TGarnetAp ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -779,11 +779,11 @@ private unsafe bool SortedSetRemoveRange(RespCommand command, ref TG ProcessOutputWithHeader(outputFooter.SpanByteAndMemory); break; case GarnetStatus.NOTFOUND: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_RETURN_VAL_0, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -816,7 +816,7 @@ private unsafe bool SortedSetRandomMember(ref TGarnetApi storageApi) // Read count if (!parseState.TryGetInt(1, out paramCount)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; @@ -831,7 +831,7 @@ private unsafe bool SortedSetRandomMember(ref TGarnetApi storageApi) if (!withScoresSlice.ReadOnlySpan.EqualsUpperCaseSpanIgnoringCase(CmdStrings.WITHSCORES)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; @@ -867,11 +867,11 @@ private unsafe bool SortedSetRandomMember(ref TGarnetApi storageApi) break; case GarnetStatus.NOTFOUND: var respBytes = includedCount ? CmdStrings.RESP_EMPTYLIST : CmdStrings.RESP_ERRNOTFOUND; - while (!RespWriteUtils.WriteDirect(respBytes, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(respBytes, ref dcurr, dend)) SendAndReset(); break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -897,14 +897,14 @@ private unsafe bool SortedSetDifference(ref TGarnetApi storageApi) // Number of keys if (!parseState.TryGetInt(0, out var nKeys)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } if (parseState.Count - 1 != nKeys && parseState.Count - 1 != nKeys + 1) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; @@ -916,7 +916,7 @@ private unsafe bool SortedSetDifference(ref TGarnetApi storageApi) if (parseState.Count <= 2) { //return empty array - while (!RespWriteUtils.WriteArrayLength(0, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(0, ref dcurr, dend)) SendAndReset(); return true; @@ -935,7 +935,7 @@ private unsafe bool SortedSetDifference(ref TGarnetApi storageApi) if (!withScores.EqualsUpperCaseSpanIgnoringCase(CmdStrings.WITHSCORES)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; @@ -949,20 +949,20 @@ private unsafe bool SortedSetDifference(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: // write the size of the array reply var resultCount = result?.Count ?? 0; - while (!RespWriteUtils.WriteArrayLength(includeWithScores ? resultCount * 2 : resultCount, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(includeWithScores ? resultCount * 2 : resultCount, ref dcurr, dend)) SendAndReset(); if (result != null) { foreach (var (element, score) in result) { - while (!RespWriteUtils.WriteBulkString(element, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(element, ref dcurr, dend)) SendAndReset(); if (includeWithScores) @@ -997,14 +997,14 @@ private unsafe bool SortedSetDifferenceStore(ref TGarnetApi storageA // Number of keys if (!parseState.TryGetInt(1, out var nKeys)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } if (parseState.Count - 2 != nKeys) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; } @@ -1017,11 +1017,11 @@ private unsafe bool SortedSetDifferenceStore(ref TGarnetApi storageA switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: - while (!RespWriteUtils.WriteInteger(count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(count, ref dcurr, dend)) SendAndReset(); break; } @@ -1113,24 +1113,24 @@ private unsafe bool SortedSetIntersect(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: if (result == null || result.Count == 0) { - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; } // write the size of the array reply - while (!RespWriteUtils.WriteArrayLength(includeWithScores ? result.Count * 2 : result.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(includeWithScores ? result.Count * 2 : result.Count, ref dcurr, dend)) SendAndReset(); foreach (var (element, score) in result) { - while (!RespWriteUtils.WriteBulkString(element, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(element, ref dcurr, dend)) SendAndReset(); if (includeWithScores) @@ -1204,11 +1204,11 @@ private unsafe bool SortedSetIntersectLength(ref TGarnetApi storageA switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: - while (!RespWriteUtils.WriteInteger(count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(count, ref dcurr, dend)) SendAndReset(); break; } @@ -1292,11 +1292,11 @@ private unsafe bool SortedSetIntersectStore(ref TGarnetApi storageAp switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: - while (!RespWriteUtils.WriteInteger(count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(count, ref dcurr, dend)) SendAndReset(); break; } @@ -1394,24 +1394,24 @@ private unsafe bool SortedSetUnion(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: if (result == null || result.Count == 0) { - while (!RespWriteUtils.WriteEmptyArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteEmptyArray(ref dcurr, dend)) SendAndReset(); break; } // write the size of the array reply - while (!RespWriteUtils.WriteArrayLength(includeWithScores ? result.Count * 2 : result.Count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(includeWithScores ? result.Count * 2 : result.Count, ref dcurr, dend)) SendAndReset(); foreach (var (element, score) in result) { - while (!RespWriteUtils.WriteBulkString(element, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(element, ref dcurr, dend)) SendAndReset(); if (includeWithScores) @@ -1443,7 +1443,7 @@ private unsafe bool SortedSetUnionStore(ref TGarnetApi storageApi) // Number of keys if (!parseState.TryGetInt(1, out var nKeys)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -1512,11 +1512,11 @@ private unsafe bool SortedSetUnionStore(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: - while (!RespWriteUtils.WriteInteger(count, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(count, ref dcurr, dend)) SendAndReset(); break; } @@ -1553,18 +1553,18 @@ private unsafe bool SortedSetBlockingPop(RespCommand command) if (!result.Found) { - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(result.Key, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(result.Key, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(result.Item, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(result.Item, ref dcurr, dend)) SendAndReset(); while (!RespWriteUtils.TryWriteDoubleBulkString(result.Score, ref dcurr, dend)) @@ -1655,26 +1655,26 @@ private unsafe bool SortedSetBlockingMPop() if (!result.Found) { - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); return true; } // Write array with 2 elements: key and array of member-score pairs - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(result.Key, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(result.Key, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteArrayLength(result.Items.Length, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(result.Items.Length, ref dcurr, dend)) SendAndReset(); for (var i = 0; i < result.Items.Length; i += 2) { - while (!RespWriteUtils.WriteArrayLength(2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(result.Items[i], ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(result.Items[i], ref dcurr, dend)) SendAndReset(); while (!RespWriteUtils.TryWriteDoubleBulkString(result.Scores[i], ref dcurr, dend)) SendAndReset(); diff --git a/libs/server/Resp/Objects/SortedSetGeoCommands.cs b/libs/server/Resp/Objects/SortedSetGeoCommands.cs index 7be7791bfa..9c4c5de1f6 100644 --- a/libs/server/Resp/Objects/SortedSetGeoCommands.cs +++ b/libs/server/Resp/Objects/SortedSetGeoCommands.cs @@ -40,7 +40,7 @@ private unsafe bool GeoAdd(ref TGarnetApi storageApi) switch (status) { case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; default: @@ -120,16 +120,16 @@ private unsafe bool GeoCommands(RespCommand command, ref TGarnetApi switch (op) { case SortedSetOperation.GEODIST: - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_ERRNOTFOUND, ref dcurr, dend)) SendAndReset(); break; default: var inputCount = parseState.Count - 1; - while (!RespWriteUtils.WriteArrayLength(inputCount, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(inputCount, ref dcurr, dend)) SendAndReset(); for (var i = 0; i < inputCount; i++) { - while (!RespWriteUtils.WriteNullArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNullArray(ref dcurr, dend)) SendAndReset(); } break; @@ -137,7 +137,7 @@ private unsafe bool GeoCommands(RespCommand command, ref TGarnetApi break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } @@ -180,7 +180,7 @@ private unsafe bool GeoSearchStore(ref TGarnetApi storageApi) dcurr += output.Length; break; case GarnetStatus.WRONGTYPE: - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_WRONG_TYPE, ref dcurr, dend)) SendAndReset(); break; } diff --git a/libs/server/Resp/Parser/ParseUtils.cs b/libs/server/Resp/Parser/ParseUtils.cs index 7b9f1e6df4..6fd9130b2d 100644 --- a/libs/server/Resp/Parser/ParseUtils.cs +++ b/libs/server/Resp/Parser/ParseUtils.cs @@ -27,7 +27,7 @@ public static int ReadInt(ref ArgSlice slice) var ptr = slice.ptr; if (slice.length == 0 || - !RespReadUtils.TryReadInt(ref ptr, slice.ptr + slice.length, out number, out var bytesRead) || + !RespReadUtils.TryReadInt32(ref ptr, slice.ptr + slice.length, out number, out var bytesRead) || (int)bytesRead != slice.length) { RespParsingException.ThrowNotANumber(slice.ptr, slice.length); @@ -48,7 +48,7 @@ public static bool TryReadInt(ref ArgSlice slice, out int number) number = default; var ptr = slice.ptr; return slice.length != 0 && - RespReadUtils.TryReadIntSafe(ref ptr, slice.ptr + slice.length, out number, out var bytesRead, out _, + RespReadUtils.TryReadInt32Safe(ref ptr, slice.ptr + slice.length, out number, out var bytesRead, out _, out _, allowLeadingZeros: false) && (int)bytesRead == slice.length; } @@ -66,7 +66,7 @@ public static long ReadLong(ref ArgSlice slice) var ptr = slice.ptr; if (slice.length == 0 || - !RespReadUtils.TryReadLong(ref ptr, slice.ptr + slice.length, out number, out var bytesRead) || + !RespReadUtils.TryReadInt64(ref ptr, slice.ptr + slice.length, out number, out var bytesRead) || (int)bytesRead != slice.length) { RespParsingException.ThrowNotANumber(slice.ptr, slice.length); @@ -87,7 +87,7 @@ public static bool TryReadLong(ref ArgSlice slice, out long number) number = default; var ptr = slice.ptr; return slice.length != 0 && - RespReadUtils.TryReadLongSafe(ref ptr, slice.ptr + slice.length, out number, out var bytesRead, + RespReadUtils.TryReadInt64Safe(ref ptr, slice.ptr + slice.length, out number, out var bytesRead, out _, out _, allowLeadingZeros: false) && (int)bytesRead == slice.length; } diff --git a/libs/server/Resp/Parser/RespCommand.cs b/libs/server/Resp/Parser/RespCommand.cs index d9b50c9716..627c2aec6b 100644 --- a/libs/server/Resp/Parser/RespCommand.cs +++ b/libs/server/Resp/Parser/RespCommand.cs @@ -2361,7 +2361,7 @@ private RespCommand ArrayParseCommand(ref int count, ref bool success) } // Read the array length - if (!RespReadUtils.ReadUnsignedArrayLength(out count, ref ptr, recvBufferPtr + bytesRead)) + if (!RespReadUtils.TryReadUnsignedArrayLength(out count, ref ptr, recvBufferPtr + bytesRead)) { success = false; return RespCommand.INVALID; @@ -2383,13 +2383,13 @@ private RespCommand ArrayParseCommand(ref int count, ref bool success) { if (!specificErrorMessage.IsEmpty) { - while (!RespWriteUtils.WriteError(specificErrorMessage, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(specificErrorMessage, ref dcurr, dend)) SendAndReset(); } else { // Return "Unknown RESP Command" message - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) SendAndReset(); } } diff --git a/libs/server/Resp/Parser/SessionParseState.cs b/libs/server/Resp/Parser/SessionParseState.cs index bc76fbd477..e829b55030 100644 --- a/libs/server/Resp/Parser/SessionParseState.cs +++ b/libs/server/Resp/Parser/SessionParseState.cs @@ -335,7 +335,7 @@ public bool Read(int i, ref byte* ptr, byte* end) ref var slice = ref Unsafe.AsRef(bufferPtr + i); // Parse RESP string header - if (!RespReadUtils.ReadUnsignedLengthHeader(out slice.length, ref ptr, end)) + if (!RespReadUtils.TryReadUnsignedLengthHeader(out slice.length, ref ptr, end)) { return false; } diff --git a/libs/server/Resp/PubSubCommands.cs b/libs/server/Resp/PubSubCommands.cs index 89a9dc526d..10131453cc 100644 --- a/libs/server/Resp/PubSubCommands.cs +++ b/libs/server/Resp/PubSubCommands.cs @@ -26,15 +26,15 @@ public override unsafe void Publish(ref byte* keyPtr, int keyLength, ref byte* v networkSender.EnterAndGetResponseObject(out dcurr, out dend); if (respProtocolVersion == 2) { - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WritePushLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWritePushLength(3, ref dcurr, dend)) SendAndReset(); } - while (!RespWriteUtils.WriteBulkString("message"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("message"u8, ref dcurr, dend)) SendAndReset(); // Write key and value to the network @@ -62,15 +62,15 @@ public override unsafe void PrefixPublish(byte* patternPtr, int patternLength, r networkSender.EnterAndGetResponseObject(out dcurr, out dend); if (respProtocolVersion == 2) { - while (!RespWriteUtils.WriteArrayLength(4, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(4, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WritePushLength(4, ref dcurr, dend)) + while (!RespWriteUtils.TryWritePushLength(4, ref dcurr, dend)) SendAndReset(); } - while (!RespWriteUtils.WriteBulkString("pmessage"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("pmessage"u8, ref dcurr, dend)) SendAndReset(); // Write pattern, key, and value to the network @@ -114,7 +114,7 @@ private bool NetworkPUBLISH() if (subscribeBroker == null) { - while (!RespWriteUtils.WriteError("ERR PUBLISH is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR PUBLISH is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) SendAndReset(); return true; } @@ -123,7 +123,7 @@ private bool NetworkPUBLISH() *(int*)valPtr = vSize; var numClients = subscribeBroker.PublishNow(keyPtr, valPtr, vSize + sizeof(int), true); - while (!RespWriteUtils.WriteInteger(numClients, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numClients, ref dcurr, dend)) SendAndReset(); return true; @@ -147,16 +147,16 @@ private bool NetworkSUBSCRIBE() if (disabledBroker) continue; - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString("subscribe"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("subscribe"u8, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(new Span(keyPtr + sizeof(int), kSize), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(keyPtr + sizeof(int), kSize), ref dcurr, dend)) SendAndReset(); numActiveChannels++; - while (!RespWriteUtils.WriteInteger(numActiveChannels, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numActiveChannels, ref dcurr, dend)) SendAndReset(); *(int*)keyPtr = kSize; @@ -165,7 +165,7 @@ private bool NetworkSUBSCRIBE() if (disabledBroker) { - while (!RespWriteUtils.WriteError("ERR SUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR SUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) SendAndReset(); return true; } @@ -192,16 +192,16 @@ private bool NetworkPSUBSCRIBE() if (disabledBroker) continue; - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString("psubscribe"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("psubscribe"u8, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(new Span(keyPtr + sizeof(int), kSize), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(keyPtr + sizeof(int), kSize), ref dcurr, dend)) SendAndReset(); numActiveChannels++; - while (!RespWriteUtils.WriteInteger(numActiveChannels, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numActiveChannels, ref dcurr, dend)) SendAndReset(); *(int*)keyPtr = kSize; @@ -210,7 +210,7 @@ private bool NetworkPSUBSCRIBE() if (disabledBroker) { - while (!RespWriteUtils.WriteError("ERR SUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR SUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) SendAndReset(); return true; } @@ -227,7 +227,7 @@ private bool NetworkUNSUBSCRIBE() { if (subscribeBroker == null) { - while (!RespWriteUtils.WriteError("ERR UNSUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR UNSUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) SendAndReset(); return true; } @@ -235,34 +235,34 @@ private bool NetworkUNSUBSCRIBE() var channels = subscribeBroker.ListAllSubscriptions(this); foreach (var channel in channels) { - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString("unsubscribe"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("unsubscribe"u8, ref dcurr, dend)) SendAndReset(); var channelsize = channel.Length - sizeof(int); fixed (byte* channelPtr = &channel[0]) { - while (!RespWriteUtils.WriteBulkString(new Span(channelPtr + sizeof(int), channelsize), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(channelPtr + sizeof(int), channelsize), ref dcurr, dend)) SendAndReset(); byte* delPtr = channelPtr; if (subscribeBroker.Unsubscribe(delPtr, this)) numActiveChannels--; - while (!RespWriteUtils.WriteInteger(numActiveChannels, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numActiveChannels, ref dcurr, dend)) SendAndReset(); } } if (channels.Count == 0) { - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString("unsubscribe"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("unsubscribe"u8, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteNull(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNull(ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteInteger(numActiveChannels, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numActiveChannels, ref dcurr, dend)) SendAndReset(); } @@ -280,25 +280,25 @@ private bool NetworkUNSUBSCRIBE() if (subscribeBroker != null) { - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString("unsubscribe"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("unsubscribe"u8, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(new Span(keyPtr + sizeof(int), kSize), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(keyPtr + sizeof(int), kSize), ref dcurr, dend)) SendAndReset(); *(int*)keyPtr = kSize; if (subscribeBroker.Unsubscribe(keyPtr, this)) numActiveChannels--; - while (!RespWriteUtils.WriteInteger(numActiveChannels, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numActiveChannels, ref dcurr, dend)) SendAndReset(); } } if (subscribeBroker == null) { - while (!RespWriteUtils.WriteError("ERR UNSUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR UNSUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) SendAndReset(); } return true; @@ -312,7 +312,7 @@ private bool NetworkPUNSUBSCRIBE() { if (subscribeBroker == null) { - while (!RespWriteUtils.WriteError("ERR PUNSUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR PUNSUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) SendAndReset(); return true; } @@ -320,19 +320,19 @@ private bool NetworkPUNSUBSCRIBE() List channels = subscribeBroker.ListAllPSubscriptions(this); foreach (var channel in channels) { - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString("punsubscribe"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("punsubscribe"u8, ref dcurr, dend)) SendAndReset(); var channelsize = channel.Length - sizeof(int); fixed (byte* channelPtr = &channel[0]) { - while (!RespWriteUtils.WriteBulkString(new Span(channelPtr + sizeof(int), channelsize), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(channelPtr + sizeof(int), channelsize), ref dcurr, dend)) SendAndReset(); numActiveChannels--; - while (!RespWriteUtils.WriteInteger(numActiveChannels, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numActiveChannels, ref dcurr, dend)) SendAndReset(); byte* delPtr = channelPtr; @@ -354,15 +354,15 @@ private bool NetworkPUNSUBSCRIBE() if (subscribeBroker != null) { - while (!RespWriteUtils.WriteArrayLength(3, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(3, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString("punsubscribe"u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString("punsubscribe"u8, ref dcurr, dend)) SendAndReset(); - while (!RespWriteUtils.WriteBulkString(new Span(keyPtr + sizeof(int), kSize), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkString(new Span(keyPtr + sizeof(int), kSize), ref dcurr, dend)) SendAndReset(); numActiveChannels--; - while (!RespWriteUtils.WriteInteger(numActiveChannels, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numActiveChannels, ref dcurr, dend)) SendAndReset(); *(int*)keyPtr = kSize; @@ -372,7 +372,7 @@ private bool NetworkPUNSUBSCRIBE() if (subscribeBroker == null) { - while (!RespWriteUtils.WriteError("ERR PUNSUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError("ERR PUNSUBSCRIBE is disabled, enable it with --pubsub option."u8, ref dcurr, dend)) SendAndReset(); } return true; @@ -387,7 +387,7 @@ private bool NetworkPUBSUB_CHANNELS() if (subscribeBroker is null) { - while (!RespWriteUtils.WriteError(string.Format(CmdStrings.GenericPubSubCommandDisabled, "PUBSUB CHANNELS"), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(string.Format(CmdStrings.GenericPubSubCommandDisabled, "PUBSUB CHANNELS"), ref dcurr, dend)) SendAndReset(); return true; } @@ -416,14 +416,14 @@ private bool NetworkPUBSUB_NUMPAT() if (subscribeBroker is null) { - while (!RespWriteUtils.WriteError(string.Format(CmdStrings.GenericPubSubCommandDisabled, "PUBSUB NUMPAT"), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(string.Format(CmdStrings.GenericPubSubCommandDisabled, "PUBSUB NUMPAT"), ref dcurr, dend)) SendAndReset(); return true; } var numPatSubs = subscribeBroker.NumPatternSubscriptions(); - while (!RespWriteUtils.WriteInteger(numPatSubs, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt32(numPatSubs, ref dcurr, dend)) SendAndReset(); return true; @@ -433,7 +433,7 @@ private bool NetworkPUBSUB_NUMSUB() { if (subscribeBroker is null) { - while (!RespWriteUtils.WriteError(string.Format(CmdStrings.GenericPubSubCommandDisabled, "PUBSUB NUMSUB"), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(string.Format(CmdStrings.GenericPubSubCommandDisabled, "PUBSUB NUMSUB"), ref dcurr, dend)) SendAndReset(); return true; } diff --git a/libs/server/Resp/PurgeBPCommand.cs b/libs/server/Resp/PurgeBPCommand.cs index 9197263a63..dba9327812 100644 --- a/libs/server/Resp/PurgeBPCommand.cs +++ b/libs/server/Resp/PurgeBPCommand.cs @@ -54,7 +54,7 @@ private bool NetworkPurgeBP() if (!parseState.TryGetManagerType(0, out var managerType)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_SYNTAX_ERROR, ref dcurr, dend)) SendAndReset(); return true; } @@ -73,7 +73,7 @@ private bool NetworkPurgeBP() break; default: success = false; - while (!RespWriteUtils.WriteError($"ERR Could not purge {managerType}.", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Could not purge {managerType}.", ref dcurr, dend)) SendAndReset(); break; } @@ -81,14 +81,14 @@ private bool NetworkPurgeBP() if (success) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true); - while (!RespWriteUtils.WriteSimpleString(managerType.ToReadOnlySpan(), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteSimpleString(managerType.ToReadOnlySpan(), ref dcurr, dend)) SendAndReset(); } } catch (Exception ex) { logger?.LogError(ex, "PURGEBP {type}:{managerType}", managerType, managerType.ToString()); - while (!RespWriteUtils.WriteError($"ERR {ex.Message}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR {ex.Message}", ref dcurr, dend)) SendAndReset(); return true; } @@ -97,7 +97,7 @@ bool ClusterPurgeBufferPool(ManagerType managerType) { if (clusterSession == null) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_CLUSTER_DISABLED, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_CLUSTER_DISABLED, ref dcurr, dend)) SendAndReset(); return false; } diff --git a/libs/server/Resp/RespServerSession.cs b/libs/server/Resp/RespServerSession.cs index 60b7009bfb..3afa529cc8 100644 --- a/libs/server/Resp/RespServerSession.cs +++ b/libs/server/Resp/RespServerSession.cs @@ -327,7 +327,7 @@ public override int TryConsumeMessages(byte* reqBuffer, int bytesReceived) logger?.Log(ex.LogLevel, ex, "Aborting open session due to RESP parsing error"); // Forward parsing error as RESP error - while (!RespWriteUtils.WriteError($"ERR Protocol Error: {ex.Message}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Protocol Error: {ex.Message}", ref dcurr, dend)) SendAndReset(); // Send message and dispose the network sender to end the session @@ -345,7 +345,7 @@ public override int TryConsumeMessages(byte* reqBuffer, int bytesReceived) // Forward Garnet error as RESP error if (ex.ClientResponse) { - while (!RespWriteUtils.WriteError($"ERR Garnet Exception: {ex.Message}", ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError($"ERR Garnet Exception: {ex.Message}", ref dcurr, dend)) SendAndReset(); } @@ -463,7 +463,7 @@ private void ProcessMessages() } else { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NOAUTH, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NOAUTH, ref dcurr, dend)) SendAndReset(); } } @@ -806,7 +806,7 @@ bool NetworkCLIENTID() return AbortWithWrongNumberOfArguments("client|id"); } - while (!RespWriteUtils.WriteInteger(Id, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteInt64(Id, ref dcurr, dend)) SendAndReset(); return true; @@ -894,7 +894,7 @@ private bool IsCommandArityValid(string cmdName, int count) if ((cmdInfo.Arity > 0 && count != cmdInfo.Arity - 1) || (cmdInfo.Arity < 0 && count < -cmdInfo.Arity - 1)) { - while (!RespWriteUtils.WriteError(string.Format(CmdStrings.GenericErrWrongNumArgs, cmdName), ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(string.Format(CmdStrings.GenericErrWrongNumArgs, cmdName), ref dcurr, dend)) SendAndReset(); return false; @@ -910,7 +910,7 @@ Span GetCommand(out bool success) var end = recvBufferPtr + bytesRead; // Try the command length - if (!RespReadUtils.ReadUnsignedLengthHeader(out int length, ref ptr, end)) + if (!RespReadUtils.TryReadUnsignedLengthHeader(out int length, ref ptr, end)) { success = false; return default; @@ -1079,12 +1079,12 @@ private void SendAndReset(IMemoryOwner memory, int length) [MethodImpl(MethodImplOptions.AggressiveInlining)] private void WriteDirectLargeRespString(ReadOnlySpan message) { - while (!RespWriteUtils.WriteBulkStringLength(message, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteBulkStringLength(message, ref dcurr, dend)) SendAndReset(); WriteDirectLarge(message); - while (!RespWriteUtils.WriteNewLine(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNewLine(ref dcurr, dend)) SendAndReset(); } diff --git a/libs/server/ServerConfig.cs b/libs/server/ServerConfig.cs index 82de1b7023..634114bb31 100644 --- a/libs/server/ServerConfig.cs +++ b/libs/server/ServerConfig.cs @@ -69,7 +69,7 @@ private bool NetworkCONFIG_GET() // Generate response for matching parameters if (parameters.Count > 0) { - while (!RespWriteUtils.WriteArrayLength(parameters.Count * 2, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(parameters.Count * 2, ref dcurr, dend)) SendAndReset(); foreach (var parameter in parameters) @@ -93,13 +93,13 @@ ReadOnlySpan GetDatabases() return Encoding.ASCII.GetBytes($"$9\r\ndatabases\r\n${databases.Length}\r\n{databases}\r\n"); } - while (!RespWriteUtils.WriteDirect(parameterValue, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(parameterValue, ref dcurr, dend)) SendAndReset(); } } else { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_EMPTYLIST, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_EMPTYLIST, ref dcurr, dend)) SendAndReset(); } @@ -114,7 +114,7 @@ private bool NetworkCONFIG_REWRITE() } storeWrapper.clusterProvider?.FlushConfig(); - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -195,12 +195,12 @@ private bool NetworkCONFIG_SET() if (errorMsg == null) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); } else { - while (!RespWriteUtils.WriteError(errorMsg, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(errorMsg, ref dcurr, dend)) SendAndReset(); } diff --git a/libs/server/Storage/Functions/MainStore/PrivateMethods.cs b/libs/server/Storage/Functions/MainStore/PrivateMethods.cs index f9d371e790..b3fcf728ee 100644 --- a/libs/server/Storage/Functions/MainStore/PrivateMethods.cs +++ b/libs/server/Storage/Functions/MainStore/PrivateMethods.cs @@ -43,7 +43,7 @@ void CopyRespTo(ref SpanByte src, ref SpanByteAndMemory dst, int start = 0, int return; } - var numLength = NumUtils.NumDigits(srcLength); + var numLength = NumUtils.CountDigits(srcLength); int totalSize = 1 + numLength + 2 + srcLength + 2; // $5\r\nvalue\r\n if (dst.IsSpanByte) @@ -54,7 +54,7 @@ void CopyRespTo(ref SpanByte src, ref SpanByteAndMemory dst, int start = 0, int byte* tmp = dst.SpanByte.ToPointer(); *tmp++ = (byte)'$'; - NumUtils.IntToBytes(srcLength, numLength, ref tmp); + NumUtils.WriteInt32(srcLength, numLength, ref tmp); *tmp++ = (byte)'\r'; *tmp++ = (byte)'\n'; src.AsReadOnlySpan().Slice(start, srcLength).CopyTo(new Span(tmp, srcLength)); @@ -72,7 +72,7 @@ void CopyRespTo(ref SpanByte src, ref SpanByteAndMemory dst, int start = 0, int { byte* tmp = ptr; *tmp++ = (byte)'$'; - NumUtils.IntToBytes(srcLength, numLength, ref tmp); + NumUtils.WriteInt32(srcLength, numLength, ref tmp); *tmp++ = (byte)'\r'; *tmp++ = (byte)'\n'; src.AsReadOnlySpan().Slice(start, srcLength).CopyTo(new Span(tmp, srcLength)); @@ -403,16 +403,15 @@ void EvaluateExpireCopyUpdate(ExpireOption optionType, bool expiryExists, long n static bool InPlaceUpdateNumber(long val, ref SpanByte value, ref SpanByteAndMemory output, ref RMWInfo rmwInfo, ref RecordInfo recordInfo, int valueOffset) { - var fNeg = false; - var ndigits = NumUtils.NumDigitsInLong(val, ref fNeg); - ndigits += fNeg ? 1 : 0; + var ndigits = NumUtils.CountDigits(val, out var isNegative); + ndigits += isNegative ? 1 : 0; if (ndigits > value.LengthWithoutMetadata - valueOffset) return false; rmwInfo.ClearExtraValueLength(ref recordInfo, ref value, value.TotalSize); value.ShrinkSerializedLength(ndigits + value.MetadataSize + valueOffset); - _ = NumUtils.LongToSpanByte(val, value.AsSpan(valueOffset)); + _ = NumUtils.WriteInt64(val, value.AsSpan(valueOffset)); rmwInfo.SetUsedValueLength(ref recordInfo, ref value, value.TotalSize); Debug.Assert(output.IsSpanByte, "This code assumes it is called in-place and did not go pending"); @@ -423,14 +422,14 @@ static bool InPlaceUpdateNumber(long val, ref SpanByte value, ref SpanByteAndMem static bool InPlaceUpdateNumber(double val, ref SpanByte value, ref SpanByteAndMemory output, ref RMWInfo rmwInfo, ref RecordInfo recordInfo, int valueOffset) { - var ndigits = NumUtils.NumOfCharInDouble(val, out var _, out var _, out var _); + var ndigits = NumUtils.CountCharsInDouble(val, out var _, out var _, out var _); if (ndigits > value.LengthWithoutMetadata - valueOffset) return false; rmwInfo.ClearExtraValueLength(ref recordInfo, ref value, value.TotalSize); value.ShrinkSerializedLength(ndigits + value.MetadataSize + valueOffset); - _ = NumUtils.DoubleToSpanByte(val, value.AsSpan(valueOffset)); + _ = NumUtils.WriteDouble(val, value.AsSpan(valueOffset)); rmwInfo.SetUsedValueLength(ref recordInfo, ref value, value.TotalSize); Debug.Assert(output.IsSpanByte, "This code assumes it is called in-place and did not go pending"); @@ -481,21 +480,21 @@ static bool TryInPlaceUpdateNumber(ref SpanByte value, ref SpanByteAndMemory out static void CopyUpdateNumber(long next, ref SpanByte newValue, ref SpanByteAndMemory output, int etagIgnoredOffset) { - NumUtils.LongToSpanByte(next, newValue.AsSpan(etagIgnoredOffset)); + NumUtils.WriteInt64(next, newValue.AsSpan(etagIgnoredOffset)); newValue.AsReadOnlySpan(etagIgnoredOffset).CopyTo(output.SpanByte.AsSpan()); output.SpanByte.Length = newValue.LengthWithoutMetadata - etagIgnoredOffset; } static void CopyUpdateNumber(double next, ref SpanByte newValue, ref SpanByteAndMemory output, int etagIgnoredOffset) { - NumUtils.DoubleToSpanByte(next, newValue.AsSpan(etagIgnoredOffset)); + NumUtils.WriteDouble(next, newValue.AsSpan(etagIgnoredOffset)); newValue.AsReadOnlySpan(etagIgnoredOffset).CopyTo(output.SpanByte.AsSpan()); output.SpanByte.Length = newValue.LengthWithoutMetadata - etagIgnoredOffset; } static void CopyUpdateNumber(double next, ref SpanByte newValue, ref SpanByteAndMemory output) { - NumUtils.DoubleToSpanByte(next, newValue.AsSpan()); + NumUtils.WriteDouble(next, newValue.AsSpan()); newValue.AsReadOnlySpan().CopyTo(output.SpanByte.AsSpan()); output.SpanByte.Length = newValue.LengthWithoutMetadata; } @@ -577,18 +576,8 @@ static void TryCopyUpdateNumber(ref SpanByte oldValue, ref SpanByte newValue, re /// True if input contained only ASCII decimal characters, otherwise false static bool IsValidNumber(int length, byte* source, Span output, out long val) { - val = 0; - try - { - // Check for valid number - if (!NumUtils.TryBytesToLong(length, source, out val)) - { - // Signal value is not a valid number - output[0] = (byte)OperationError.INVALID_TYPE; - return false; - } - } - catch + // Check for valid number + if (!NumUtils.TryReadInt64(length, source, out val)) { // Signal value is not a valid number output[0] = (byte)OperationError.INVALID_TYPE; @@ -599,18 +588,8 @@ static bool IsValidNumber(int length, byte* source, Span output, out long static bool IsValidDouble(int length, byte* source, Span output, out double val) { - val = 0; - try - { - // Check for valid number - if (!NumUtils.TryBytesToDouble(length, source, out val) || !double.IsFinite(val)) - { - // Signal value is not a valid number - output[0] = (byte)OperationError.INVALID_TYPE; - return false; - } - } - catch + // Check for valid number + if (!NumUtils.TryReadDouble(length, source, out val) || !double.IsFinite(val)) { // Signal value is not a valid number output[0] = (byte)OperationError.INVALID_TYPE; @@ -638,7 +617,7 @@ void CopyRespNumber(long number, ref SpanByteAndMemory dst) { byte* curr = dst.SpanByte.ToPointer(); byte* end = curr + dst.SpanByte.Length; - if (RespWriteUtils.WriteInteger(number, ref curr, end, out int integerLen, out int totalLen)) + if (RespWriteUtils.TryWriteInt64(number, ref curr, end, out int integerLen, out int totalLen)) { dst.SpanByte.Length = (int)(curr - dst.SpanByte.ToPointer()); return; @@ -652,7 +631,7 @@ void CopyRespNumber(long number, ref SpanByteAndMemory dst) { byte* cc = ptr; *cc++ = (byte)':'; - NumUtils.LongToBytes(number, integerLen, ref cc); + NumUtils.WriteInt64(number, integerLen, ref cc); *cc++ = (byte)'\r'; *cc++ = (byte)'\n'; } @@ -663,11 +642,11 @@ void CopyRespNumber(long number, ref SpanByteAndMemory dst) /// static void CopyValueLengthToOutput(ref SpanByte value, ref SpanByteAndMemory output, int eTagIgnoredOffset) { - int numDigits = NumUtils.NumDigits(value.LengthWithoutMetadata - eTagIgnoredOffset); + int numDigits = NumUtils.CountDigits(value.LengthWithoutMetadata - eTagIgnoredOffset); Debug.Assert(output.IsSpanByte, "This code assumes it is called in a non-pending context or in a pending context where dst.SpanByte's pointer remains valid"); var outputPtr = output.SpanByte.ToPointer(); - NumUtils.IntToBytes(value.LengthWithoutMetadata - eTagIgnoredOffset, numDigits, ref outputPtr); + NumUtils.WriteInt32(value.LengthWithoutMetadata - eTagIgnoredOffset, numDigits, ref outputPtr); output.SpanByte.Length = numDigits; } @@ -689,7 +668,7 @@ static void CopyRespWithEtagData(ref SpanByte value, ref SpanByteAndMemory dst, // here we know the value span has first bytes set to etag so we hardcode skipping past the bytes for the etag below etagTruncatedVal = value.AsReadOnlySpan(etagSkippedStart); // *2\r\n :(etag digits)\r\n $(val Len digits)\r\n (value len)\r\n - desiredLength += 1 + NumUtils.NumDigitsInLong(etag) + 2 + 1 + NumUtils.NumDigits(etagAccountedValueLength) + 2 + etagAccountedValueLength + 2; + desiredLength += 1 + NumUtils.CountDigits(etag) + 2 + 1 + NumUtils.CountDigits(etagAccountedValueLength) + 2 + etagAccountedValueLength + 2; WriteValAndEtagToDst(desiredLength, ref etagTruncatedVal, etag, ref dst, memoryPool); } diff --git a/libs/server/Storage/Functions/MainStore/RMWMethods.cs b/libs/server/Storage/Functions/MainStore/RMWMethods.cs index 1cd66baf85..8ef50d6147 100644 --- a/libs/server/Storage/Functions/MainStore/RMWMethods.cs +++ b/libs/server/Storage/Functions/MainStore/RMWMethods.cs @@ -185,10 +185,9 @@ public bool InitialUpdater(ref SpanByte key, ref RawStringInput input, ref SpanB break; case RespCommand.INCRBY: value.UnmarkExtraMetadata(); - var fNeg = false; var incrBy = input.arg1; - var ndigits = NumUtils.NumDigitsInLong(incrBy, ref fNeg); - value.ShrinkSerializedLength(ndigits + (fNeg ? 1 : 0)); + var ndigits = NumUtils.CountDigits(incrBy, out var isNegative); + value.ShrinkSerializedLength(ndigits + (isNegative ? 1 : 0)); CopyUpdateNumber(incrBy, ref value, ref output); break; case RespCommand.DECR: @@ -198,10 +197,10 @@ public bool InitialUpdater(ref SpanByte key, ref RawStringInput input, ref SpanB break; case RespCommand.DECRBY: value.UnmarkExtraMetadata(); - fNeg = false; + isNegative = false; var decrBy = -input.arg1; - ndigits = NumUtils.NumDigitsInLong(decrBy, ref fNeg); - value.ShrinkSerializedLength(ndigits + (fNeg ? 1 : 0)); + ndigits = NumUtils.CountDigits(decrBy, out isNegative); + value.ShrinkSerializedLength(ndigits + (isNegative ? 1 : 0)); CopyUpdateNumber(decrBy, ref value, ref output); break; case RespCommand.INCRBYFLOAT: @@ -362,7 +361,7 @@ private bool InPlaceUpdaterWorker(ref SpanByte key, ref RawStringInput input, re // write back array of the format [etag, nil] var nilResp = CmdStrings.RESP_ERRNOTFOUND; // *2\r\n: + + \r\n + - var numDigitsInEtag = NumUtils.NumDigitsInLong(newEtag); + var numDigitsInEtag = NumUtils.CountDigits(newEtag); WriteValAndEtagToDst(4 + 1 + numDigitsInEtag + 2 + nilResp.Length, ref nilResp, newEtag, ref output, functionsState.memoryPool, writeDirect: true); // reset etag state after done using EtagState.ResetState(ref functionsState.etagState); @@ -956,7 +955,7 @@ public bool CopyUpdater(ref SpanByte key, ref RawStringInput input, ref SpanByte // write back array of the format [etag, nil] var nilResp = CmdStrings.RESP_ERRNOTFOUND; // *2\r\n: + + \r\n + - var numDigitsInEtag = NumUtils.NumDigitsInLong(newEtag); + var numDigitsInEtag = NumUtils.CountDigits(newEtag); WriteValAndEtagToDst(4 + 1 + numDigitsInEtag + 2 + nilResp.Length, ref nilResp, newEtag, ref output, functionsState.memoryPool, writeDirect: true); break; case RespCommand.SET: diff --git a/libs/server/Storage/Functions/MainStore/ReadMethods.cs b/libs/server/Storage/Functions/MainStore/ReadMethods.cs index 6d925472c4..7ead9a714c 100644 --- a/libs/server/Storage/Functions/MainStore/ReadMethods.cs +++ b/libs/server/Storage/Functions/MainStore/ReadMethods.cs @@ -155,7 +155,7 @@ private bool handleGetIfNotMatch(ref RawStringInput input, ref SpanByte value, r // write back array of the format [etag, nil] var nilResp = CmdStrings.RESP_ERRNOTFOUND; // *2\r\n: + + \r\n + - var numDigitsInEtag = NumUtils.NumDigitsInLong(existingEtag); + var numDigitsInEtag = NumUtils.CountDigits(existingEtag); WriteValAndEtagToDst(4 + 1 + numDigitsInEtag + 2 + nilResp.Length, ref nilResp, existingEtag, ref dst, functionsState.memoryPool, writeDirect: true); return true; } diff --git a/libs/server/Storage/Functions/MainStore/VarLenInputMethods.cs b/libs/server/Storage/Functions/MainStore/VarLenInputMethods.cs index 2e6b3d17f3..884c27e052 100644 --- a/libs/server/Storage/Functions/MainStore/VarLenInputMethods.cs +++ b/libs/server/Storage/Functions/MainStore/VarLenInputMethods.cs @@ -24,7 +24,7 @@ static bool IsValidNumber(int length, byte* source, out long val) try { // Check for valid number - if (!NumUtils.TryBytesToLong(length, source, out val)) + if (!NumUtils.TryReadInt64(length, source, out val)) { // Signal value is not a valid number return false; @@ -51,7 +51,7 @@ static bool IsValidDouble(int length, byte* source, out double val) try { // Check for valid number - if (!NumUtils.TryBytesToDouble(length, source, out val) || !double.IsFinite(val)) + if (!NumUtils.TryReadDouble(length, source, out val) || !double.IsFinite(val)) { // Signal value is not a valid number return false; @@ -99,21 +99,19 @@ public int GetRMWInitialValueLength(ref RawStringInput input) return sizeof(int) + 2; // # of digits in "-1" case RespCommand.INCRBY: - var fNeg = false; - var ndigits = NumUtils.NumDigitsInLong(input.arg1, ref fNeg); + var ndigits = NumUtils.CountDigits(input.arg1, out var isNegative); - return sizeof(int) + ndigits + (fNeg ? 1 : 0); + return sizeof(int) + ndigits + (isNegative ? 1 : 0); case RespCommand.DECRBY: - fNeg = false; - ndigits = NumUtils.NumDigitsInLong(-input.arg1, ref fNeg); + ndigits = NumUtils.CountDigits(-input.arg1, out isNegative); - return sizeof(int) + ndigits + (fNeg ? 1 : 0); + return sizeof(int) + ndigits + (isNegative ? 1 : 0); case RespCommand.INCRBYFLOAT: if (!input.parseState.TryGetDouble(0, out var incrByFloat)) return sizeof(int); - ndigits = NumUtils.NumOfCharInDouble(incrByFloat, out var _, out var _, out var _); + ndigits = NumUtils.CountCharsInDouble(incrByFloat, out var _, out var _, out var _); return sizeof(int) + ndigits; default: @@ -147,12 +145,11 @@ public int GetRMWModifiedValueLength(ref SpanByte t, ref RawStringInput input) case RespCommand.INCRBY: var incrByValue = input.header.cmd == RespCommand.INCRBY ? input.arg1 : 1; - var curr = NumUtils.BytesToLong(t.AsSpan(functionsState.etagState.etagOffsetForVarlen)); + var curr = NumUtils.ReadInt64(t.AsSpan(functionsState.etagState.etagOffsetForVarlen)); var next = curr + incrByValue; - var fNeg = false; - var ndigits = NumUtils.NumDigitsInLong(next, ref fNeg); - ndigits += fNeg ? 1 : 0; + var ndigits = NumUtils.CountDigits(next, out var isNegative); + ndigits += isNegative ? 1 : 0; return sizeof(int) + ndigits + t.MetadataSize + functionsState.etagState.etagOffsetForVarlen; @@ -160,22 +157,21 @@ public int GetRMWModifiedValueLength(ref SpanByte t, ref RawStringInput input) case RespCommand.DECRBY: var decrByValue = input.header.cmd == RespCommand.DECRBY ? input.arg1 : 1; - curr = NumUtils.BytesToLong(t.AsSpan(functionsState.etagState.etagOffsetForVarlen)); + curr = NumUtils.ReadInt64(t.AsSpan(functionsState.etagState.etagOffsetForVarlen)); next = curr - decrByValue; - fNeg = false; - ndigits = NumUtils.NumDigitsInLong(next, ref fNeg); - ndigits += fNeg ? 1 : 0; + ndigits = NumUtils.CountDigits(next, out isNegative); + ndigits += isNegative ? 1 : 0; return sizeof(int) + ndigits + t.MetadataSize + functionsState.etagState.etagOffsetForVarlen; case RespCommand.INCRBYFLOAT: // We don't need to TryGetDouble here because InPlaceUpdater will raise an error before we reach this point var incrByFloat = input.parseState.GetDouble(0); - NumUtils.TryBytesToDouble(t.AsSpan(functionsState.etagState.etagOffsetForVarlen), out var currVal); + NumUtils.TryReadDouble(t.AsSpan(functionsState.etagState.etagOffsetForVarlen), out var currVal); var nextVal = currVal + incrByFloat; - ndigits = NumUtils.NumOfCharInDouble(nextVal, out _, out _, out _); + ndigits = NumUtils.CountCharsInDouble(nextVal, out _, out _, out _); return sizeof(int) + ndigits + t.MetadataSize + functionsState.etagState.etagOffsetForVarlen; case RespCommand.SETBIT: diff --git a/libs/server/Storage/Functions/ObjectStore/PrivateMethods.cs b/libs/server/Storage/Functions/ObjectStore/PrivateMethods.cs index e3740c8068..a1c143673f 100644 --- a/libs/server/Storage/Functions/ObjectStore/PrivateMethods.cs +++ b/libs/server/Storage/Functions/ObjectStore/PrivateMethods.cs @@ -85,7 +85,7 @@ static void CopyRespNumber(long number, ref SpanByteAndMemory dst) { byte* curr = dst.SpanByte.ToPointer(); byte* end = curr + dst.SpanByte.Length; - if (RespWriteUtils.WriteInteger(number, ref curr, end, out var integerLen, out int totalLen)) + if (RespWriteUtils.TryWriteInt64(number, ref curr, end, out var integerLen, out int totalLen)) { dst.SpanByte.Length = (int)(curr - dst.SpanByte.ToPointer()); return; @@ -99,7 +99,7 @@ static void CopyRespNumber(long number, ref SpanByteAndMemory dst) { byte* cc = ptr; *cc++ = (byte)':'; - NumUtils.LongToBytes(number, (int)integerLen, ref cc); + NumUtils.WriteInt64(number, (int)integerLen, ref cc); *cc++ = (byte)'\r'; *cc++ = (byte)'\n'; } diff --git a/libs/server/Storage/Session/MainStore/BitmapOps.cs b/libs/server/Storage/Session/MainStore/BitmapOps.cs index 009e4d9685..ab2e5c5394 100644 --- a/libs/server/Storage/Session/MainStore/BitmapOps.cs +++ b/libs/server/Storage/Session/MainStore/BitmapOps.cs @@ -211,8 +211,8 @@ public unsafe GarnetStatus StringBitCount(ArgSlice key, long start, lo return GarnetStatus.OK; // Get parameter lengths - var startLength = NumUtils.NumDigitsInLong(start); - var endLength = NumUtils.NumDigitsInLong(end); + var startLength = NumUtils.CountDigits(start); + var endLength = NumUtils.CountDigits(end); // Calculate # of bytes to store parameters var sliceBytes = 1 + startLength + endLength; @@ -232,13 +232,13 @@ public unsafe GarnetStatus StringBitCount(ArgSlice key, long start, lo // Start var startSpan = paramsSpan.Slice(paramsSpanOffset, startLength); - NumUtils.LongToSpanByte(start, startSpan); + NumUtils.WriteInt64(start, startSpan); var startSlice = ArgSlice.FromPinnedSpan(startSpan); paramsSpanOffset += startLength; // End var endSpan = paramsSpan.Slice(paramsSpanOffset, endLength); - NumUtils.LongToSpanByte(end, endSpan); + NumUtils.WriteInt64(end, endSpan); var endSlice = ArgSlice.FromPinnedSpan(endSpan); SpanByteAndMemory output = new(null); @@ -260,7 +260,7 @@ public unsafe GarnetStatus StringBitCount(ArgSlice key, long start, lo fixed (byte* outputPtr = output.Memory.Memory.Span) { var refPtr = outputPtr; - RespReadUtils.Read64Int(out result, ref refPtr, refPtr + sizeof(long)); + RespReadUtils.TryReadInt64(out result, ref refPtr, refPtr + sizeof(long)); } output.Memory.Dispose(); } @@ -285,9 +285,9 @@ public unsafe GarnetStatus StringBitField(ArgSlice key, List 0 ? "i"u8 : "u"u8; var encodingSuffix = commandArguments[i].typeInfo & 0x7F; - var encodingSuffixLength = NumUtils.NumDigits(encodingSuffix); - var offsetLength = NumUtils.NumDigitsInLong(commandArguments[i].offset); - var valueLength = isGet ? 0 : NumUtils.NumDigitsInLong(commandArguments[i].value); + var encodingSuffixLength = NumUtils.CountDigits(encodingSuffix); + var offsetLength = NumUtils.CountDigits(commandArguments[i].offset); + var valueLength = isGet ? 0 : NumUtils.CountDigits(commandArguments[i].value); var overflowType = ((BitFieldOverflow)commandArguments[i].overflowType).ToString(); // Calculate # of bytes to store parameters @@ -314,13 +314,13 @@ public unsafe GarnetStatus StringBitField(ArgSlice key, List(ArgSlice key, List(ArgSlice key, List(ArgSlice key, List(ArgSlice key, Memory value, ref TContext public unsafe GarnetStatus SETEX(ArgSlice key, ArgSlice value, ArgSlice expiryMs, ref TContext context) where TContext : ITsavoriteContext - => SETEX(key, value, TimeSpan.FromMilliseconds(NumUtils.BytesToLong(expiryMs.Length, expiryMs.ptr)), ref context); + => SETEX(key, value, TimeSpan.FromMilliseconds(NumUtils.ReadInt64(expiryMs.Length, expiryMs.ptr)), ref context); public GarnetStatus SETEX(ArgSlice key, ArgSlice value, TimeSpan expiry, ref TContext context) where TContext : ITsavoriteContext @@ -608,7 +608,7 @@ private unsafe GarnetStatus RENAME(ArgSlice oldKeySlice, ArgSlice newKeySlice, S var memoryHandle = o.Memory.Memory.Pin(); var ptrVal = (byte*)memoryHandle.Pointer; - RespReadUtils.ReadUnsignedLengthHeader(out var headerLength, ref ptrVal, ptrVal + o.Length); + RespReadUtils.TryReadUnsignedLengthHeader(out var headerLength, ref ptrVal, ptrVal + o.Length); // Find expiration time of the old key var expireSpan = new SpanByteAndMemory(); @@ -620,7 +620,7 @@ private unsafe GarnetStatus RENAME(ArgSlice oldKeySlice, ArgSlice newKeySlice, S using var expireMemoryHandle = expireSpan.Memory.Memory.Pin(); var expirePtrVal = (byte*)expireMemoryHandle.Pointer; - RespReadUtils.TryRead64Int(out var expireTimeMs, ref expirePtrVal, expirePtrVal + expireSpan.Length, out var _); + RespReadUtils.TryReadInt64(out var expireTimeMs, ref expirePtrVal, expirePtrVal + expireSpan.Length, out var _); input = isNX ? new RawStringInput(RespCommand.SETEXNX) : new RawStringInput(RespCommand.SET); @@ -818,7 +818,7 @@ public GarnetStatus EXISTS(ArgSlice key, StoreType sto public unsafe GarnetStatus EXPIRE(ArgSlice key, ArgSlice expiryMs, out bool timeoutSet, StoreType storeType, ExpireOption expireOption, ref TContext context, ref TObjectContext objectStoreContext) where TContext : ITsavoriteContext where TObjectContext : ITsavoriteContext - => EXPIRE(key, TimeSpan.FromMilliseconds(NumUtils.BytesToLong(expiryMs.Length, expiryMs.ptr)), out timeoutSet, storeType, expireOption, ref context, ref objectStoreContext); + => EXPIRE(key, TimeSpan.FromMilliseconds(NumUtils.ReadInt64(expiryMs.Length, expiryMs.ptr)), out timeoutSet, storeType, expireOption, ref context, ref objectStoreContext); /// /// Set a timeout on key. @@ -954,10 +954,10 @@ public unsafe GarnetStatus EXPIRE(ArgSlice key, long e var found = false; // Serialize expiry + expiry options to parse state - var expiryLength = NumUtils.NumDigitsInLong(expiry); + var expiryLength = NumUtils.CountDigits(expiry); var expirySlice = scratchBufferManager.CreateArgSlice(expiryLength); var expirySpan = expirySlice.Span; - NumUtils.LongToSpanByte(expiry, expirySpan); + NumUtils.WriteInt64(expiry, expirySpan); if (storeType == StoreType.Main || storeType == StoreType.All) { @@ -1119,7 +1119,7 @@ public unsafe GarnetStatus Increment(ArgSlice key, out long output, lo Debug.Assert(_output.IsSpanByte); - output = NumUtils.BytesToLong(_output.Length, outputBuffer); + output = NumUtils.ReadInt64(_output.Length, outputBuffer); return GarnetStatus.OK; } @@ -1262,13 +1262,13 @@ private unsafe GarnetStatus LCSInternal(ArgSlice key1, ArgSlice key2, { if (status1 != GarnetStatus.OK || status2 != GarnetStatus.OK) { - while (!RespWriteUtils.WriteInteger(0, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(0, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return GarnetStatus.OK; } var len = ComputeLCSLength(val1.ReadOnlySpan, val2.ReadOnlySpan, minMatchLen); - while (!RespWriteUtils.WriteInteger(len, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(len, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } else if (withIndices) @@ -1291,13 +1291,13 @@ private unsafe GarnetStatus LCSInternal(ArgSlice key1, ArgSlice key2, { if (status1 != GarnetStatus.OK || status2 != GarnetStatus.OK) { - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_EMPTY, ref curr, end)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_EMPTY, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return GarnetStatus.OK; } var lcs = ComputeLCS(val1.ReadOnlySpan, val2.ReadOnlySpan, minMatchLen); - while (!RespWriteUtils.WriteBulkString(lcs, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(lcs, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } @@ -1383,53 +1383,53 @@ private static unsafe void WriteLCSMatches(List matches, bool withMatc ref byte* curr, byte* end, ref SpanByteAndMemory output, ref bool isMemory, ref byte* ptr, ref MemoryHandle ptrHandle) { - while (!RespWriteUtils.WriteArrayLength(4, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(4, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); // Write "matches" section identifier - while (!RespWriteUtils.WriteBulkString(CmdStrings.matches, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(CmdStrings.matches, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); // Write matches array - while (!RespWriteUtils.WriteArrayLength(matches.Count, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(matches.Count, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); foreach (var match in matches) { - while (!RespWriteUtils.WriteArrayLength(withMatchLen ? 3 : 2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(withMatchLen ? 3 : 2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteArrayLength(2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteInteger(match.Start1, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(match.Start1, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteInteger(match.Start1 + match.Length - 1, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(match.Start1 + match.Length - 1, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteArrayLength(2, ref curr, end)) + while (!RespWriteUtils.TryWriteArrayLength(2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteInteger(match.Start2, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(match.Start2, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); - while (!RespWriteUtils.WriteInteger(match.Start2 + match.Length - 1, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(match.Start2 + match.Length - 1, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); if (withMatchLen) { - while (!RespWriteUtils.WriteInteger(match.Length, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(match.Length, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } } // Write "len" section identifier - while (!RespWriteUtils.WriteBulkString(CmdStrings.len, ref curr, end)) + while (!RespWriteUtils.TryWriteBulkString(CmdStrings.len, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); // Write LCS length - while (!RespWriteUtils.WriteInteger(lcsLength, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(lcsLength, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } diff --git a/libs/server/Storage/Session/ObjectStore/Common.cs b/libs/server/Storage/Session/ObjectStore/Common.cs index 3ca927b497..4658d401a4 100644 --- a/libs/server/Storage/Session/ObjectStore/Common.cs +++ b/libs/server/Storage/Session/ObjectStore/Common.cs @@ -140,7 +140,7 @@ public unsafe GarnetStatus ObjectScan(GarnetObjectType objectTyp // Prepare the parse state var matchPattern = match.Trim(); - var countLength = NumUtils.NumDigits(count); + var countLength = NumUtils.CountDigits(count); // Calculate # of bytes to store parameters var sliceBytes = CmdStrings.MATCH.Length + @@ -175,7 +175,7 @@ public unsafe GarnetStatus ObjectScan(GarnetObjectType objectTyp // Value var countValueSpan = paramsSpan.Slice(paramsSpanOffset, countLength); - NumUtils.LongToSpanByte(count, countValueSpan); + NumUtils.WriteInt64(count, countValueSpan); var countValueSlice = ArgSlice.FromPinnedSpan(countValueSpan); parseState.InitializeWithArguments(matchSlice, matchPatternSlice, @@ -238,7 +238,7 @@ unsafe ArgSlice[] ProcessRespArrayOutput(GarnetObjectStoreOutput outputFooter, o if (*refPtr == '-') { - if (!RespReadUtils.ReadErrorAsString(out error, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadErrorAsString(out error, ref refPtr, outputPtr + outputSpan.Length)) return default; } else if (*refPtr == '*') @@ -246,18 +246,18 @@ unsafe ArgSlice[] ProcessRespArrayOutput(GarnetObjectStoreOutput outputFooter, o if (isScanOutput) { // Read the first two elements - if (!RespReadUtils.ReadUnsignedArrayLength(out var outerArraySize, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var outerArraySize, ref refPtr, outputPtr + outputSpan.Length)) return default; element = null; len = 0; // Read cursor value - if (!RespReadUtils.ReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) return default; } // Get the number of elements - if (!RespReadUtils.ReadUnsignedArrayLength(out var arraySize, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var arraySize, ref refPtr, outputPtr + outputSpan.Length)) return default; // Create the argslice[] @@ -271,7 +271,7 @@ unsafe ArgSlice[] ProcessRespArrayOutput(GarnetObjectStoreOutput outputFooter, o { element = null; len = 0; - if (RespReadUtils.ReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) + if (RespReadUtils.TryReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) { elements[i] = new ArgSlice(element, len); } @@ -281,7 +281,7 @@ unsafe ArgSlice[] ProcessRespArrayOutput(GarnetObjectStoreOutput outputFooter, o { byte* result = null; len = 0; - if (!RespReadUtils.ReadPtrWithLengthHeader(ref result, ref len, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadPtrWithLengthHeader(ref result, ref len, ref refPtr, outputPtr + outputSpan.Length)) return default; elements = [new ArgSlice(result, len)]; } @@ -321,13 +321,13 @@ unsafe int[] ProcessRespIntegerArrayOutput(GarnetObjectStoreOutput outputFooter, if (*refPtr == '-') { - if (!RespReadUtils.ReadErrorAsString(out error, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadErrorAsString(out error, ref refPtr, outputPtr + outputSpan.Length)) return default; } else if (*refPtr == '*') { // Get the number of elements - if (!RespReadUtils.ReadUnsignedArrayLength(out var arraySize, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var arraySize, ref refPtr, outputPtr + outputSpan.Length)) return default; // Create the argslice[] @@ -335,7 +335,7 @@ unsafe int[] ProcessRespIntegerArrayOutput(GarnetObjectStoreOutput outputFooter, for (int i = 0; i < elements.Length; i++) { element = null; - if (RespReadUtils.TryReadInt(ref refPtr, outputPtr + outputSpan.Length, out var number, out var _)) + if (RespReadUtils.TryReadInt32(ref refPtr, outputPtr + outputSpan.Length, out var number, out var _)) { elements[i] = number; } @@ -372,13 +372,13 @@ unsafe int[] ProcessRespIntegerArrayOutput(GarnetObjectStoreOutput outputFooter, if (*refPtr == '-') { - if (!RespReadUtils.ReadErrorAsString(out error, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadErrorAsString(out error, ref refPtr, outputPtr + outputSpan.Length)) return default; } else if (*refPtr == '*') { // Get the number of result elements - if (!RespReadUtils.ReadUnsignedArrayLength(out var arraySize, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var arraySize, ref refPtr, outputPtr + outputSpan.Length)) return default; Debug.Assert(arraySize % 2 == 0, "Array elements are expected to be in pairs"); @@ -387,12 +387,12 @@ unsafe int[] ProcessRespIntegerArrayOutput(GarnetObjectStoreOutput outputFooter, for (var i = 0; i < result.Length; i++) { - if (!RespReadUtils.ReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) return default; result[i].member = new ArgSlice(element, len); - if (!RespReadUtils.ReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) + if (!RespReadUtils.TryReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) return default; result[i].score = new ArgSlice(element, len); @@ -428,7 +428,7 @@ unsafe ArgSlice ProcessRespSingleTokenOutput(GarnetObjectStoreOutput outputFoote { var refPtr = outputPtr; - if (!RespReadUtils.ReadPtrWithLengthHeader(ref element, ref len, ref refPtr, + if (!RespReadUtils.TryReadPtrWithLengthHeader(ref element, ref len, ref refPtr, outputPtr + outputSpan.Length)) return default; result = new ArgSlice(element, len); @@ -459,7 +459,7 @@ unsafe bool TryProcessRespSimple64IntOutput(GarnetObjectStoreOutput outputFooter { var refPtr = outputPtr; - if (!RespReadUtils.TryRead64Int(out value, ref refPtr, outputPtr + outputSpan.Length, out _)) + if (!RespReadUtils.TryReadInt64(out value, ref refPtr, outputPtr + outputSpan.Length, out _)) return false; } } diff --git a/libs/server/Storage/Session/ObjectStore/HashOps.cs b/libs/server/Storage/Session/ObjectStore/HashOps.cs index a39b270cfb..3d1733eb02 100644 --- a/libs/server/Storage/Session/ObjectStore/HashOps.cs +++ b/libs/server/Storage/Session/ObjectStore/HashOps.cs @@ -557,10 +557,10 @@ public GarnetStatus HashExpire(ArgSlice key, long expireAt, bool where TObjectContext : ITsavoriteContext { var expireAtUtc = isMilliseconds ? ConvertUtils.UnixTimestampInMillisecondsToTicks(expireAt) : ConvertUtils.UnixTimestampInSecondsToTicks(expireAt); - var expiryLength = NumUtils.NumDigitsInLong(expireAtUtc); + var expiryLength = NumUtils.CountDigits(expireAtUtc); var expirySlice = scratchBufferManager.CreateArgSlice(expiryLength); var expirySpan = expirySlice.Span; - NumUtils.LongToSpanByte(expireAtUtc, expirySpan); + NumUtils.WriteInt64(expireAtUtc, expirySpan); parseState.Initialize(1 + input.parseState.Count); parseState.SetArgument(0, expirySlice); diff --git a/libs/server/Storage/Session/ObjectStore/SortedSetGeoOps.cs b/libs/server/Storage/Session/ObjectStore/SortedSetGeoOps.cs index f5be4d08da..eb7aae2ad3 100644 --- a/libs/server/Storage/Session/ObjectStore/SortedSetGeoOps.cs +++ b/libs/server/Storage/Session/ObjectStore/SortedSetGeoOps.cs @@ -92,7 +92,7 @@ public unsafe GarnetStatus GeoSearchStore(ArgSlice key, ArgSlice { // Expire/Delete the destination key if the source key is not found _ = EXPIRE(destination, TimeSpan.Zero, out _, StoreType.Object, ExpireOption.None, ref lockableContext, ref objectStoreLockableContext); - while (!RespWriteUtils.WriteInteger(0, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(0, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return GarnetStatus.OK; } @@ -108,7 +108,7 @@ public unsafe GarnetStatus GeoSearchStore(ArgSlice key, ArgSlice if (RespReadUtils.TryReadErrorAsSpan(out var error, ref currOutPtr, endOutPtr)) { - while (!RespWriteUtils.WriteError(error, ref curr, end)) + while (!RespWriteUtils.TryWriteError(error, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); return GarnetStatus.OK; } @@ -116,14 +116,14 @@ public unsafe GarnetStatus GeoSearchStore(ArgSlice key, ArgSlice var destinationKey = destination.ToArray(); objectStoreLockableContext.Delete(ref destinationKey); - RespReadUtils.ReadUnsignedArrayLength(out var foundItems, ref currOutPtr, endOutPtr); + RespReadUtils.TryReadUnsignedArrayLength(out var foundItems, ref currOutPtr, endOutPtr); // Prepare the parse state for sorted set add parseState.Initialize(foundItems * 2); for (var j = 0; j < foundItems; j++) { - RespReadUtils.ReadUnsignedArrayLength(out var innerLength, ref currOutPtr, endOutPtr); + RespReadUtils.TryReadUnsignedArrayLength(out var innerLength, ref currOutPtr, endOutPtr); Debug.Assert(innerLength == 2, "Should always has location and hash or distance"); // Read location into parse state @@ -142,7 +142,7 @@ public unsafe GarnetStatus GeoSearchStore(ArgSlice key, ArgSlice var zAddOutput = new GarnetObjectStoreOutput { SpanByteAndMemory = new SpanByteAndMemory(null) }; RMWObjectStoreOperationWithOutput(destinationKey, ref zAddInput, ref objectStoreLockableContext, ref zAddOutput); - while (!RespWriteUtils.WriteInteger(foundItems, ref curr, end)) + while (!RespWriteUtils.TryWriteInt32(foundItems, ref curr, end)) ObjectUtils.ReallocateOutput(ref output, ref isMemory, ref ptr, ref ptrHandle, ref curr, ref end); } finally diff --git a/libs/server/Storage/Session/ObjectStore/SortedSetOps.cs b/libs/server/Storage/Session/ObjectStore/SortedSetOps.cs index b874f07976..d20588effc 100644 --- a/libs/server/Storage/Session/ObjectStore/SortedSetOps.cs +++ b/libs/server/Storage/Session/ObjectStore/SortedSetOps.cs @@ -288,8 +288,8 @@ public unsafe GarnetStatus SortedSetRemoveRangeByRank(ArgSlice k GarnetStatus status; // Get parameter lengths - var startLen = NumUtils.NumDigits(start); - var stopLen = NumUtils.NumDigits(stop); + var startLen = NumUtils.CountDigits(start); + var stopLen = NumUtils.CountDigits(stop); // Get buffer from scratch buffer manager var paramsSlice = scratchBufferManager.CreateArgSlice(startLen + stopLen); @@ -297,11 +297,11 @@ public unsafe GarnetStatus SortedSetRemoveRangeByRank(ArgSlice k // Store parameters to buffer var startSpan = paramsSpan.Slice(0, startLen); - NumUtils.LongToSpanByte(start, startSpan); + NumUtils.WriteInt64(start, startSpan); var startSlice = ArgSlice.FromPinnedSpan(startSpan); var stopSpan = paramsSpan.Slice(startLen, stopLen); - NumUtils.LongToSpanByte(stop, stopSpan); + NumUtils.WriteInt64(stop, stopSpan); var stopSlice = ArgSlice.FromPinnedSpan(stopSpan); parseState.InitializeWithArguments(startSlice, stopSlice); @@ -508,9 +508,9 @@ public unsafe GarnetStatus SortedSetRange(ArgSlice key, ArgSlice arguments.Add(scratchBufferManager.CreateArgSlice(limit.Item1)); // Count - var limitCountLength = NumUtils.NumDigitsInLong(limit.Item2); + var limitCountLength = NumUtils.CountDigits(limit.Item2); var limitCountSlice = scratchBufferManager.CreateArgSlice(limitCountLength); - NumUtils.LongToSpanByte(limit.Item2, limitCountSlice.Span); + NumUtils.WriteInt64(limit.Item2, limitCountSlice.Span); arguments.Add(limitCountSlice); } @@ -768,7 +768,7 @@ public unsafe GarnetStatus SortedSetRangeStore(ArgSlice dstKey, var destinationKey = dstKey.ToArray(); objectStoreLockableContext.Delete(ref destinationKey); - RespReadUtils.ReadUnsignedArrayLength(out var arrayLen, ref currOutPtr, endOutPtr); + RespReadUtils.TryReadUnsignedArrayLength(out var arrayLen, ref currOutPtr, endOutPtr); Debug.Assert(arrayLen % 2 == 0, "Should always contain element and its score"); result = arrayLen / 2; diff --git a/libs/server/Transaction/TxnRespCommands.cs b/libs/server/Transaction/TxnRespCommands.cs index 084b004827..bb116178e3 100644 --- a/libs/server/Transaction/TxnRespCommands.cs +++ b/libs/server/Transaction/TxnRespCommands.cs @@ -20,7 +20,7 @@ private bool NetworkMULTI() { if (txnManager.state != TxnState.None) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_NESTED_MULTI, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_NESTED_MULTI, ref dcurr, dend)) SendAndReset(); txnManager.Abort(); return true; @@ -31,7 +31,7 @@ private bool NetworkMULTI() //Keep track of ptr for key verification when cluster mode is enabled txnManager.saveKeyRecvBufferPtr = recvBufferPtr; - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } @@ -48,7 +48,7 @@ private bool NetworkEXEC() // Abort and reset the transaction else if (txnManager.state == TxnState.Aborted) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_EXEC_ABORT, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_EXEC_ABORT, ref dcurr, dend)) SendAndReset(); txnManager.Reset(false); return true; @@ -73,20 +73,20 @@ private bool NetworkEXEC() if (startTxn) { - while (!RespWriteUtils.WriteArrayLength(txnManager.operationCntTxn, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteArrayLength(txnManager.operationCntTxn, ref dcurr, dend)) SendAndReset(); } else { endReadHead = _origReadHead; - while (!RespWriteUtils.WriteNullArray(ref dcurr, dend)) + while (!RespWriteUtils.TryWriteNullArray(ref dcurr, dend)) SendAndReset(); } return true; } // EXEC without MULTI command - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_EXEC_WO_MULTI, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_EXEC_WO_MULTI, ref dcurr, dend)) SendAndReset(); return true; @@ -102,7 +102,7 @@ private bool NetworkSKIP(RespCommand cmd) cmd = cmd.NormalizeForACLs(); if (!RespCommandsInfo.TryGetRespCommandInfo(cmd, out var commandInfo, txnOnly: true, logger)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_UNK_CMD, ref dcurr, dend)) SendAndReset(); txnManager.Abort(); return true; @@ -121,13 +121,13 @@ private bool NetworkSKIP(RespCommand cmd) { if (isWatch) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_WATCH_IN_MULTI, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_WATCH_IN_MULTI, ref dcurr, dend)) SendAndReset(); } else { string err = string.Format(CmdStrings.GenericErrWrongNumArgs, commandInfo.Name); - while (!RespWriteUtils.WriteError(err, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(err, ref dcurr, dend)) SendAndReset(); txnManager.Abort(); } @@ -144,7 +144,7 @@ private bool NetworkSKIP(RespCommand cmd) if (skipped == -2) return false; // We found an unsupported command, abort - while (!RespWriteUtils.WriteError(error, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(error, ref dcurr, dend)) SendAndReset(); txnManager.Abort(); @@ -152,7 +152,7 @@ private bool NetworkSKIP(RespCommand cmd) return true; } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_QUEUED, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_QUEUED, ref dcurr, dend)) SendAndReset(); txnManager.operationCntTxn++; @@ -166,11 +166,11 @@ private bool NetworkDISCARD() { if (txnManager.state == TxnState.None) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_DISCARD_WO_MULTI, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_DISCARD_WO_MULTI, ref dcurr, dend)) SendAndReset(); return true; } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); txnManager.Reset(false); return true; @@ -187,7 +187,7 @@ private bool CommonWATCH(StoreType type) // Have to provide at least one key if (count == 0) { - while (!RespWriteUtils.WriteError(CmdStrings.GenericErrWrongNumArgs, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.GenericErrWrongNumArgs, ref dcurr, dend)) SendAndReset(); return true; @@ -206,7 +206,7 @@ private bool CommonWATCH(StoreType type) txnManager.Watch(toWatch, type); } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; @@ -239,7 +239,7 @@ private bool NetworkUNWATCH() { txnManager.watchContainer.Reset(); } - while (!RespWriteUtils.WriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteDirect(CmdStrings.RESP_OK, ref dcurr, dend)) SendAndReset(); return true; } @@ -258,7 +258,7 @@ private bool NetworkRUNTXP() if (!parseState.TryGetInt(0, out var txId)) { - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER, ref dcurr, dend)) SendAndReset(); return true; } @@ -274,7 +274,7 @@ private bool NetworkRUNTXP() { logger?.LogError(e, "Getting customer transaction in RUNTXP failed"); - while (!RespWriteUtils.WriteError(CmdStrings.RESP_ERR_NO_TRANSACTION_PROCEDURE, ref dcurr, dend)) + while (!RespWriteUtils.TryWriteError(CmdStrings.RESP_ERR_NO_TRANSACTION_PROCEDURE, ref dcurr, dend)) SendAndReset(); return true; @@ -283,7 +283,7 @@ private bool NetworkRUNTXP() if ((arity > 0 && count != arity) || (arity < 0 && count < -arity)) { var expectedParams = arity > 0 ? arity - 1 : -arity - 1; - while (!RespWriteUtils.WriteError( + while (!RespWriteUtils.TryWriteError( string.Format(CmdStrings.GenericErrWrongNumArgsTxn, txId, expectedParams, count - 1), ref dcurr, dend)) SendAndReset(); diff --git a/playground/CommandInfoUpdater/CommandInfoUpdater.cs b/playground/CommandInfoUpdater/CommandInfoUpdater.cs index b9f388b525..3cd358c65d 100644 --- a/playground/CommandInfoUpdater/CommandInfoUpdater.cs +++ b/playground/CommandInfoUpdater/CommandInfoUpdater.cs @@ -186,7 +186,7 @@ private static unsafe bool TryGetCommandsInfo(string[] commandsToQuery, int resp var end = ptr + response.Length; // Read the array length (# of commands info returned) - if (!RespReadUtils.ReadUnsignedArrayLength(out var cmdCount, ref ptr, end)) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var cmdCount, ref ptr, end)) { logger.LogError("Unable to read RESP command info count from server"); return false; diff --git a/playground/CommandInfoUpdater/RespCommandInfoParser.cs b/playground/CommandInfoUpdater/RespCommandInfoParser.cs index a1c16d72ed..ecb2a280d0 100644 --- a/playground/CommandInfoUpdater/RespCommandInfoParser.cs +++ b/playground/CommandInfoUpdater/RespCommandInfoParser.cs @@ -34,55 +34,55 @@ public static unsafe bool TryReadFromResp(ref byte* ptr, byte* end, IReadOnlyDic } // Verify command info array length - if (!RespReadUtils.ReadUnsignedArrayLength(out var infoElemCount, ref ptr, end) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var infoElemCount, ref ptr, end) || infoElemCount != 10) return false; // 1) Name - if (!RespReadUtils.ReadStringWithLengthHeader(out var name, ref ptr, end)) return false; + if (!RespReadUtils.TryReadStringWithLengthHeader(out var name, ref ptr, end)) return false; // 2) Arity - if (!RespReadUtils.ReadIntegerAsString(out var strArity, ref ptr, end) + if (!RespReadUtils.TryReadIntegerAsString(out var strArity, ref ptr, end) || !int.TryParse(strArity, out var arity)) return false; // 3) Flags var flags = RespCommandFlags.None; - if (!RespReadUtils.ReadUnsignedArrayLength(out var flagCount, ref ptr, end)) return false; + if (!RespReadUtils.TryReadUnsignedArrayLength(out var flagCount, ref ptr, end)) return false; for (var flagIdx = 0; flagIdx < flagCount; flagIdx++) { - if (!RespReadUtils.ReadSimpleString(out var strFlag, ref ptr, end) + if (!RespReadUtils.TryReadSimpleString(out var strFlag, ref ptr, end) || !EnumUtils.TryParseEnumFromDescription(strFlag, out var flag)) return false; flags |= flag; } // 4) First key - if (!RespReadUtils.ReadIntegerAsString(out var strFirstKey, ref ptr, end) + if (!RespReadUtils.TryReadIntegerAsString(out var strFirstKey, ref ptr, end) || !int.TryParse(strFirstKey, out var firstKey)) return false; // 5) Last key - if (!RespReadUtils.ReadIntegerAsString(out var strLastKey, ref ptr, end) + if (!RespReadUtils.TryReadIntegerAsString(out var strLastKey, ref ptr, end) || !int.TryParse(strLastKey, out var lastKey)) return false; // 6) Step - if (!RespReadUtils.ReadIntegerAsString(out var strStep, ref ptr, end) + if (!RespReadUtils.TryReadIntegerAsString(out var strStep, ref ptr, end) || !int.TryParse(strStep, out var step)) return false; // 7) ACL categories var aclCategories = RespAclCategories.None; - if (!RespReadUtils.ReadUnsignedArrayLength(out var aclCatCount, ref ptr, end)) return false; + if (!RespReadUtils.TryReadUnsignedArrayLength(out var aclCatCount, ref ptr, end)) return false; for (var aclCatIdx = 0; aclCatIdx < aclCatCount; aclCatIdx++) { - if (!RespReadUtils.ReadSimpleString(out var strAclCat, ref ptr, end) + if (!RespReadUtils.TryReadSimpleString(out var strAclCat, ref ptr, end) || !EnumUtils.TryParseEnumFromDescription(strAclCat.TrimStart('@'), out var aclCat)) return false; aclCategories |= aclCat; } // 8) Tips - if (!RespReadUtils.ReadStringArrayWithLengthHeader(out var tips, ref ptr, end)) return false; + if (!RespReadUtils.TryReadStringArrayWithLengthHeader(out var tips, ref ptr, end)) return false; // 9) Key specifications - if (!RespReadUtils.ReadUnsignedArrayLength(out var ksCount, ref ptr, end)) return false; + if (!RespReadUtils.TryReadUnsignedArrayLength(out var ksCount, ref ptr, end)) return false; var keySpecifications = new RespCommandKeySpecification[ksCount]; for (var ksIdx = 0; ksIdx < ksCount; ksIdx++) { @@ -91,7 +91,7 @@ public static unsafe bool TryReadFromResp(ref byte* ptr, byte* end, IReadOnlyDic } // 10) SubCommands - if (!RespReadUtils.ReadUnsignedArrayLength(out var scCount, ref ptr, end)) return false; + if (!RespReadUtils.TryReadUnsignedArrayLength(out var scCount, ref ptr, end)) return false; var subCommands = new List(); for (var scIdx = 0; scIdx < scCount; scIdx++) { @@ -142,22 +142,22 @@ internal static unsafe bool TryReadFromResp(ref byte* ptr, byte* end, out RespCo KeySpecMethodBase beginSearch = null; KeySpecMethodBase findKeys = null; - if (!RespReadUtils.ReadUnsignedArrayLength(out var elemCount, ref ptr, end)) return false; + if (!RespReadUtils.TryReadUnsignedArrayLength(out var elemCount, ref ptr, end)) return false; for (var elemIdx = 0; elemIdx < elemCount; elemIdx += 2) { - if (!RespReadUtils.ReadStringWithLengthHeader(out var ksKey, ref ptr, end)) return false; + if (!RespReadUtils.TryReadStringWithLengthHeader(out var ksKey, ref ptr, end)) return false; if (string.Equals(ksKey, "notes", StringComparison.Ordinal)) { - if (!RespReadUtils.ReadStringWithLengthHeader(out notes, ref ptr, end)) return false; + if (!RespReadUtils.TryReadStringWithLengthHeader(out notes, ref ptr, end)) return false; } else if (string.Equals(ksKey, "flags", StringComparison.Ordinal)) { - if (!RespReadUtils.ReadUnsignedArrayLength(out var flagsCount, ref ptr, end)) return false; + if (!RespReadUtils.TryReadUnsignedArrayLength(out var flagsCount, ref ptr, end)) return false; for (var flagIdx = 0; flagIdx < flagsCount; flagIdx++) { - if (!RespReadUtils.ReadSimpleString(out var strFlag, ref ptr, end) + if (!RespReadUtils.TryReadSimpleString(out var strFlag, ref ptr, end) || !EnumUtils.TryParseEnumFromDescription(strFlag, out var flag)) return false; flags |= flag; @@ -247,12 +247,12 @@ private static unsafe bool TryReadKeySpecHeader(ref byte* ptr, byte* end, out st { keySpecType = default; - if (!RespReadUtils.ReadUnsignedArrayLength(out var ksTypeElemCount, ref ptr, end) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var ksTypeElemCount, ref ptr, end) || ksTypeElemCount != 4 - || !RespReadUtils.ReadStringWithLengthHeader(out var ksTypeStr, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out var ksTypeStr, ref ptr, end) || !string.Equals(ksTypeStr, "type", StringComparison.Ordinal) - || !RespReadUtils.ReadStringWithLengthHeader(out var ksType, ref ptr, end) - || !RespReadUtils.ReadStringWithLengthHeader(out var ksSpecStr, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out var ksType, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out var ksSpecStr, ref ptr, end) || !string.Equals(ksSpecStr, "spec", StringComparison.Ordinal)) return false; keySpecType = ksType; @@ -299,11 +299,11 @@ public unsafe bool TryReadFromResp(ref byte* ptr, byte* end, out KeySpecMethodBa { keySpecMethod = default; - if (!RespReadUtils.ReadUnsignedArrayLength(out var ksSpecElemCount, ref ptr, end) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var ksSpecElemCount, ref ptr, end) || ksSpecElemCount != 2 - || !RespReadUtils.ReadStringWithLengthHeader(out var ksArgKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out var ksArgKey, ref ptr, end) || !string.Equals(ksArgKey, "index", StringComparison.Ordinal) - || !RespReadUtils.ReadIntegerAsString(out var strIndex, ref ptr, end) + || !RespReadUtils.TryReadIntegerAsString(out var strIndex, ref ptr, end) || !int.TryParse(strIndex, out var index)) return false; keySpecMethod = new BeginSearchIndex(index); @@ -338,14 +338,14 @@ public unsafe bool TryReadFromResp(ref byte* ptr, byte* end, out KeySpecMethodBa { keySpecMethod = default; - if (!RespReadUtils.ReadUnsignedArrayLength(out var specElemCount, ref ptr, end) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var specElemCount, ref ptr, end) || specElemCount != 4 - || !RespReadUtils.ReadStringWithLengthHeader(out var argKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out var argKey, ref ptr, end) || !string.Equals(argKey, "keyword", StringComparison.Ordinal) - || !RespReadUtils.ReadStringWithLengthHeader(out var keyword, ref ptr, end) - || !RespReadUtils.ReadStringWithLengthHeader(out argKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out var keyword, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out argKey, ref ptr, end) || !string.Equals(argKey, "startfrom", StringComparison.Ordinal) - || !RespReadUtils.ReadIntegerAsString(out var strStartFrom, ref ptr, end) + || !RespReadUtils.TryReadIntegerAsString(out var strStartFrom, ref ptr, end) || !int.TryParse(strStartFrom, out var startFrom)) return false; keySpecMethod = new BeginSearchKeyword(keyword, startFrom); @@ -379,7 +379,7 @@ public unsafe bool TryReadFromResp(ref byte* ptr, byte* end, out KeySpecMethodBa { keySpecMethod = default; - if (!RespReadUtils.ReadUnsignedArrayLength(out var ksSpecElemCount, ref ptr, end) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var ksSpecElemCount, ref ptr, end) || ksSpecElemCount == 0) return false; keySpecMethod = new BeginSearchUnknown(); @@ -413,19 +413,19 @@ public unsafe bool TryReadFromResp(ref byte* ptr, byte* end, out KeySpecMethodBa { keySpecMethod = default; - if (!RespReadUtils.ReadUnsignedArrayLength(out var specElemCount, ref ptr, end) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var specElemCount, ref ptr, end) || specElemCount != 6 - || !RespReadUtils.ReadStringWithLengthHeader(out var argKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out var argKey, ref ptr, end) || !string.Equals(argKey, "lastkey", StringComparison.Ordinal) - || !RespReadUtils.ReadIntegerAsString(out var strLastKey, ref ptr, end) + || !RespReadUtils.TryReadIntegerAsString(out var strLastKey, ref ptr, end) || !int.TryParse(strLastKey, out var lastKey) - || !RespReadUtils.ReadStringWithLengthHeader(out argKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out argKey, ref ptr, end) || !string.Equals(argKey, "keystep", StringComparison.Ordinal) - || !RespReadUtils.ReadIntegerAsString(out var strKeyStep, ref ptr, end) + || !RespReadUtils.TryReadIntegerAsString(out var strKeyStep, ref ptr, end) || !int.TryParse(strKeyStep, out var keyStep) - || !RespReadUtils.ReadStringWithLengthHeader(out argKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out argKey, ref ptr, end) || !string.Equals(argKey, "limit", StringComparison.Ordinal) - || !RespReadUtils.ReadIntegerAsString(out var strLimit, ref ptr, end) + || !RespReadUtils.TryReadIntegerAsString(out var strLimit, ref ptr, end) || !int.TryParse(strLimit, out var limit)) return false; keySpecMethod = new FindKeysRange(lastKey, keyStep, limit); @@ -460,19 +460,19 @@ public unsafe bool TryReadFromResp(ref byte* ptr, byte* end, out KeySpecMethodBa { keySpecMethod = default; - if (!RespReadUtils.ReadUnsignedArrayLength(out var specElemCount, ref ptr, end) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var specElemCount, ref ptr, end) || specElemCount != 6 - || !RespReadUtils.ReadStringWithLengthHeader(out var argKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out var argKey, ref ptr, end) || !string.Equals(argKey, "keynumidx", StringComparison.Ordinal) - || !RespReadUtils.ReadIntegerAsString(out var strKeyNumIdx, ref ptr, end) + || !RespReadUtils.TryReadIntegerAsString(out var strKeyNumIdx, ref ptr, end) || !int.TryParse(strKeyNumIdx, out var keyNumIdx) - || !RespReadUtils.ReadStringWithLengthHeader(out argKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out argKey, ref ptr, end) || !string.Equals(argKey, "firstkey", StringComparison.Ordinal) - || !RespReadUtils.ReadIntegerAsString(out var strFirstKey, ref ptr, end) + || !RespReadUtils.TryReadIntegerAsString(out var strFirstKey, ref ptr, end) || !int.TryParse(strFirstKey, out var firstKey) - || !RespReadUtils.ReadStringWithLengthHeader(out argKey, ref ptr, end) + || !RespReadUtils.TryReadStringWithLengthHeader(out argKey, ref ptr, end) || !string.Equals(argKey, "keystep", StringComparison.Ordinal) - || !RespReadUtils.ReadIntegerAsString(out var strKeyStep, ref ptr, end) + || !RespReadUtils.TryReadIntegerAsString(out var strKeyStep, ref ptr, end) || !int.TryParse(strKeyStep, out var keyStep)) return false; keySpecMethod = new FindKeysKeyNum(keyNumIdx, firstKey, keyStep); @@ -506,7 +506,7 @@ public unsafe bool TryReadFromResp(ref byte* ptr, byte* end, out KeySpecMethodBa { keySpecMethod = default; - if (!RespReadUtils.ReadUnsignedArrayLength(out var ksSpecElemCount, ref ptr, end) + if (!RespReadUtils.TryReadUnsignedArrayLength(out var ksSpecElemCount, ref ptr, end) || ksSpecElemCount == 0) return false; keySpecMethod = new FindKeysUnknown(); diff --git a/test/Garnet.test.cluster/ClusterTestUtils.cs b/test/Garnet.test.cluster/ClusterTestUtils.cs index b4002cc698..fdfdd27f01 100644 --- a/test/Garnet.test.cluster/ClusterTestUtils.cs +++ b/test/Garnet.test.cluster/ClusterTestUtils.cs @@ -792,27 +792,27 @@ public static (int, int) LightReceive(byte* buf, int bytesRead, int opType) switch (*buf) { case (byte)'+': - if (!RespReadResponseUtils.ReadSimpleString(out result, ref ptr, buf + bytesRead)) + if (!RespReadResponseUtils.TryReadSimpleString(out result, ref ptr, buf + bytesRead)) return (0, 0); count++; break; case (byte)':': - if (!RespReadResponseUtils.ReadIntegerAsString(out result, ref ptr, buf + bytesRead)) + if (!RespReadResponseUtils.TryReadIntegerAsString(out result, ref ptr, buf + bytesRead)) return (0, 0); count++; break; case (byte)'-': - if (!RespReadResponseUtils.ReadErrorAsString(out result, ref ptr, buf + bytesRead)) + if (!RespReadResponseUtils.TryReadErrorAsString(out result, ref ptr, buf + bytesRead)) return (0, 0); count++; break; case (byte)'$': - if (!RespReadResponseUtils.ReadStringWithLengthHeader(out result, ref ptr, buf + bytesRead)) + if (!RespReadResponseUtils.TryReadStringWithLengthHeader(out result, ref ptr, buf + bytesRead)) return (0, 0); count++; break; case (byte)'*': - if (!RespReadResponseUtils.ReadStringArrayWithLengthHeader(out resultArray, ref ptr, buf + bytesRead)) + if (!RespReadResponseUtils.TryReadStringArrayWithLengthHeader(out resultArray, ref ptr, buf + bytesRead)) return (0, 0); count++; break; @@ -835,19 +835,19 @@ public static string ParseRespToString(byte[] data, out string[] resultArray) switch (*buf) { case (byte)'+': - RespReadResponseUtils.ReadSimpleString(out result, ref ptr, buf + data.Length); + RespReadResponseUtils.TryReadSimpleString(out result, ref ptr, buf + data.Length); break; case (byte)':': - RespReadResponseUtils.ReadIntegerAsString(out result, ref ptr, buf + data.Length); + RespReadResponseUtils.TryReadIntegerAsString(out result, ref ptr, buf + data.Length); break; case (byte)'-': - RespReadResponseUtils.ReadErrorAsString(out result, ref ptr, buf + data.Length); + RespReadResponseUtils.TryReadErrorAsString(out result, ref ptr, buf + data.Length); break; case (byte)'$': - RespReadResponseUtils.ReadStringWithLengthHeader(out result, ref ptr, buf + data.Length); + RespReadResponseUtils.TryReadStringWithLengthHeader(out result, ref ptr, buf + data.Length); break; case (byte)'*': - RespReadResponseUtils.ReadStringArrayWithLengthHeader(out resultArray, ref ptr, buf + data.Length); + RespReadResponseUtils.TryReadStringArrayWithLengthHeader(out resultArray, ref ptr, buf + data.Length); break; default: throw new Exception("Unexpected response: " + Encoding.ASCII.GetString(new Span(buf, data.Length)).Replace("\n", "|").Replace("\r", "") + "]"); diff --git a/test/Garnet.test/Resp/RespReadUtilsTests.cs b/test/Garnet.test/Resp/RespReadUtilsTests.cs index 7860dd7bc2..802d0e498d 100644 --- a/test/Garnet.test/Resp/RespReadUtilsTests.cs +++ b/test/Garnet.test/Resp/RespReadUtilsTests.cs @@ -29,7 +29,7 @@ public static unsafe void ReadLengthHeaderTest(string text, int expected) { var start = ptr; var end = ptr + bytes.Length; - var success = RespReadUtils.ReadSignedLengthHeader(out var length, ref start, end); + var success = RespReadUtils.TryReadSignedLengthHeader(out var length, ref start, end); ClassicAssert.IsTrue(success); ClassicAssert.AreEqual(expected, length); @@ -57,7 +57,7 @@ public static unsafe void ReadLengthHeaderExceptionsTest(string text) fixed (byte* ptr = bytes) { var start = ptr; - _ = RespReadUtils.ReadUnsignedLengthHeader(out var length, ref start, ptr + bytes.Length); + _ = RespReadUtils.TryReadUnsignedLengthHeader(out var length, ref start, ptr + bytes.Length); } }); } @@ -76,7 +76,7 @@ public static unsafe void ReadArrayLengthTest(string text, int expected) { var start = ptr; var end = ptr + bytes.Length; - var success = RespReadUtils.ReadUnsignedArrayLength(out var length, ref start, end); + var success = RespReadUtils.TryReadUnsignedArrayLength(out var length, ref start, end); ClassicAssert.IsTrue(success); ClassicAssert.AreEqual(expected, length); @@ -103,7 +103,7 @@ public static unsafe void ReadArrayLengthExceptionsTest(string text) fixed (byte* ptr = bytes) { var start = ptr; - _ = RespReadUtils.ReadUnsignedArrayLength(out var length, ref start, ptr + bytes.Length); + _ = RespReadUtils.TryReadUnsignedArrayLength(out var length, ref start, ptr + bytes.Length); } }); } @@ -123,7 +123,7 @@ public static unsafe void ReadIntWithLengthHeaderTest(string text, int expected) { var start = ptr; var end = ptr + bytes.Length; - var success = RespReadUtils.ReadIntWithLengthHeader(out var length, ref start, end); + var success = RespReadUtils.TryReadInt32WithLengthHeader(out var length, ref start, end); ClassicAssert.IsTrue(success); ClassicAssert.AreEqual(expected, length); @@ -148,7 +148,7 @@ public static unsafe void ReadIntWithLengthHeaderExceptionsTest(string text) fixed (byte* ptr = bytes) { var start = ptr; - _ = RespReadUtils.ReadIntWithLengthHeader(out var length, ref start, ptr + bytes.Length); + _ = RespReadUtils.TryReadInt32WithLengthHeader(out var length, ref start, ptr + bytes.Length); } }); } @@ -168,7 +168,7 @@ public static unsafe void ReadLongWithLengthHeaderTest(string text, long expecte { var start = ptr; var end = ptr + bytes.Length; - var success = RespReadUtils.ReadLongWithLengthHeader(out var length, ref start, end); + var success = RespReadUtils.TryReadInt64WithLengthHeader(out var length, ref start, end); ClassicAssert.IsTrue(success); ClassicAssert.AreEqual(expected, length); @@ -194,7 +194,7 @@ public static unsafe void ReadLongWithLengthHeaderExceptionsTest(string text) fixed (byte* ptr = bytes) { var start = ptr; - _ = RespReadUtils.ReadLongWithLengthHeader(out var length, ref start, ptr + bytes.Length); + _ = RespReadUtils.TryReadInt64WithLengthHeader(out var length, ref start, ptr + bytes.Length); } }); } @@ -213,7 +213,7 @@ public static unsafe void ReadULongWithLengthHeaderTest(string text, ulong expec { var start = ptr; var end = ptr + bytes.Length; - var success = RespReadUtils.ReadULongWithLengthHeader(out var length, ref start, end); + var success = RespReadUtils.TryReadUInt64WithLengthHeader(out var length, ref start, end); ClassicAssert.IsTrue(success); ClassicAssert.AreEqual(expected, length); @@ -238,7 +238,7 @@ public static unsafe void ReadULongWithLengthHeaderExceptionsTest(string text) fixed (byte* ptr = bytes) { var start = ptr; - _ = RespReadUtils.ReadULongWithLengthHeader(out var length, ref start, ptr + bytes.Length); + _ = RespReadUtils.TryReadUInt64WithLengthHeader(out var length, ref start, ptr + bytes.Length); } }); } @@ -258,7 +258,7 @@ public static unsafe void ReadPtrWithLengthHeaderTest(string text) var length = -1; var start = ptr; var end = ptr + bytes.Length; - var success = RespReadUtils.ReadPtrWithLengthHeader(ref result, ref length, ref start, end); + var success = RespReadUtils.TryReadPtrWithLengthHeader(ref result, ref length, ref start, end); ClassicAssert.IsTrue(success); ClassicAssert.IsTrue(result != null); @@ -281,7 +281,7 @@ public static unsafe void ReadBoolWithLengthHeaderTest(string text, bool expecte { var start = ptr; var end = ptr + bytes.Length; - var success = RespReadUtils.ReadBoolWithLengthHeader(out var result, ref start, end); + var success = RespReadUtils.TryReadBoolWithLengthHeader(out var result, ref start, end); ClassicAssert.IsTrue(success); ClassicAssert.AreEqual(expected, result);