Fixed string length check into SetStringAt

- fix #28
This commit is contained in:
Federico Barresi
2022-05-18 14:56:38 +02:00
parent e5836c4283
commit 5d92d8b3a3
3 changed files with 17 additions and 7 deletions

View File

@@ -1,6 +1,12 @@
# Change Log # Change Log
All notable changed to this project will be documented in this file. All notable changed to this project will be documented in this file.
## [1.1.82] - 18.05.2022
### Added
### Changed
### Fixed
- Fixed string length check into SetStringAt [#28](https://github.com/fbarresi/Sharp7/issues/28)
## [1.1.81] - 18.05.2022 ## [1.1.81] - 18.05.2022
### Added ### Added
### Changed ### Changed

View File

@@ -337,11 +337,12 @@ namespace Sharp7.Tests
} }
[Theory] [Theory]
[InlineData("888", new byte[] {200, 3, 56,56,56})] [InlineData("888", 200, new byte[] {200, 3, 56,56,56})]
public void TestSetStringAt(string test, byte[] expected) [InlineData("888888", 5, new byte[] {5, 5, 56,56,56,56,56})]
public void TestSetStringAt(string test, int maxLength, byte[] expected)
{ {
var buffer = new byte[200]; var buffer = new byte[maxLength+2];
S7.SetStringAt(buffer, 0, buffer.Length, test); S7.SetStringAt(buffer, 0, maxLength, test);
buffer.Take(expected.Length).ToArray().ShouldBe(expected); buffer.Take(expected.Length).ToArray().ShouldBe(expected);
} }

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
namespace Sharp7 namespace Sharp7
@@ -615,10 +616,12 @@ namespace Sharp7
public static void SetStringAt(this byte[] buffer, int pos, int MaxLen, string value) public static void SetStringAt(this byte[] buffer, int pos, int MaxLen, string value)
{ {
int size = value.Length; int length = value.Length;
// checking current length against MaxLen
if (length > MaxLen) length = MaxLen;
buffer[pos] = (byte) MaxLen; buffer[pos] = (byte) MaxLen;
buffer[pos + 1] = (byte) size; buffer[pos + 1] = (byte) length;
Encoding.UTF8.GetBytes(value, 0, size, buffer, pos + 2); Encoding.UTF8.GetBytes(value, 0, length, buffer, pos + 2);
} }
#endregion #endregion