@nxtedition/shared 1.0.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +32 -7
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import assert from 'node:assert'
2
+
1
3
  const WRITE_INDEX = 0
2
4
  const READ_INDEX = 1
3
5
  const END_OF_PACKET = -1
@@ -67,12 +69,25 @@ export function writer({ sharedState, sharedBuffer }) {
67
69
  let flushing = null
68
70
 
69
71
  function tryWrite(...raw) {
72
+ if (Array.isArray(raw[0])) {
73
+ raw = raw[0]
74
+ }
75
+
76
+ if (!raw.length) {
77
+ return true
78
+ }
79
+
70
80
  readPos = Atomics.load(state, READ_INDEX)
71
81
 
72
- const len = raw.reduce((len, buf) => len + buf.byteLength, 4)
82
+ let maxLen = 4
83
+ for (const buf of raw) {
84
+ maxLen += buf.byteLength ?? buf.length * 3
85
+ }
73
86
 
74
- if (size - writePos < len + 4) {
75
- if (readPos < len + 4) {
87
+ assert(maxLen < size / 2)
88
+
89
+ if (size - writePos < maxLen + 4) {
90
+ if (readPos < maxLen + 4) {
76
91
  return false
77
92
  }
78
93
 
@@ -81,19 +96,29 @@ export function writer({ sharedState, sharedBuffer }) {
81
96
  } else {
82
97
  const available = writePos >= readPos ? size - writePos : readPos - writePos
83
98
 
84
- if (available < len + 4) {
99
+ if (available < maxLen + 4) {
85
100
  return false
86
101
  }
87
102
  }
88
103
 
89
- buffer.writeInt32LE(len, writePos)
104
+ const lenPos = writePos
90
105
  writePos += 4
91
106
 
92
107
  for (const buf of raw) {
93
- buffer.set(buf, writePos)
94
- writePos += buf.byteLength
108
+ if (typeof buf === 'string') {
109
+ writePos += buffer.write(buf, writePos)
110
+ } else {
111
+ buffer.set(buf, writePos)
112
+ writePos += buf.byteLength
113
+ }
95
114
  }
96
115
 
116
+ const len = writePos - lenPos
117
+
118
+ assert(len <= maxLen)
119
+
120
+ buffer.writeInt32LE(len, lenPos)
121
+
97
122
  Atomics.store(state, WRITE_INDEX, writePos)
98
123
  Atomics.notify(state, WRITE_INDEX)
99
124
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nxtedition/shared",
3
- "version": "1.0.1",
3
+ "version": "1.1.2",
4
4
  "description": "Ring Buffer for NodeJS cross Worker communication",
5
5
  "main": "index.js",
6
6
  "repository": {