Debian Codegraph @

server/subject_transform.go

raw
1 // Copyright 2023-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "fmt"
18 "hash/fnv"
19 "math"
20 "math/rand"
21 "regexp"
22 "slices"
23 "strconv"
24 "strings"
25 )
26
27 // Subject mapping and transform setups.
28 var (
29 commaSeparatorRegEx = regexp.MustCompile(`,\s*`)
30 partitionMappingFunctionRegEx = regexp.MustCompile(`{{\s*[pP]artition\s*\((.*)\)\s*}}`)
31 wildcardMappingFunctionRegEx = regexp.MustCompile(`{{\s*[wW]ildcard\s*\((.*)\)\s*}}`)
32 splitFromLeftMappingFunctionRegEx = regexp.MustCompile(`{{\s*[sS]plit[fF]rom[lL]eft\s*\((.*)\)\s*}}`)
33 splitFromRightMappingFunctionRegEx = regexp.MustCompile(`{{\s*[sS]plit[fF]rom[rR]ight\s*\((.*)\)\s*}}`)
34 sliceFromLeftMappingFunctionRegEx = regexp.MustCompile(`{{\s*[sS]lice[fF]rom[lL]eft\s*\((.*)\)\s*}}`)
35 sliceFromRightMappingFunctionRegEx = regexp.MustCompile(`{{\s*[sS]lice[fF]rom[rR]ight\s*\((.*)\)\s*}}`)
36 splitMappingFunctionRegEx = regexp.MustCompile(`{{\s*[sS]plit\s*\((.*)\)\s*}}`)
37 leftMappingFunctionRegEx = regexp.MustCompile(`{{\s*[lL]eft\s*\((.*)\)\s*}}`)
38 rightMappingFunctionRegEx = regexp.MustCompile(`{{\s*[rR]ight\s*\((.*)\)\s*}}`)
39 randomMappingFunctionRegEx = regexp.MustCompile(`{{\s*[rR]andom\s*\((.*)\)\s*}}`)
40 )
41
42 // Enum for the subject mapping subjectTransform function types
43 const (
44 NoTransform int16 = iota
45 BadTransform
46 Partition
47 Wildcard
48 SplitFromLeft
49 SplitFromRight
50 SliceFromLeft
51 SliceFromRight
52 Split
53 Left
54 Right
55 Random
56 )
57
58 // Transforms for arbitrarily mapping subjects from one to another for maps, tees and filters.
59 // These can also be used for proper mapping on wildcard exports/imports.
60 // These will be grouped and caching and locking are assumed to be in the upper layers.
61 type subjectTransform struct {
62 src, dest string
63 dtoks []string // destination tokens
64 stoks []string // source tokens
65 dtokmftypes []int16 // destination token mapping function types
66 dtokmftokindexesargs [][]int // destination token mapping function array of source token index arguments
67 dtokmfintargs []int32 // destination token mapping function int32 arguments
68 dtokmfstringargs []string // destination token mapping function string arguments
69 }
70
71 // SubjectTransformer transforms subjects using mappings
72 //
73 // This API is not part of the public API and not subject to SemVer protections
74 type SubjectTransformer interface {
75 // TODO(dlc) - We could add in client here to allow for things like foo -> foo.$ACCOUNT
76 Match(string) (string, error)
77 TransformSubject(subject string) string
78 TransformTokenizedSubject(tokens []string) string
79 }
80
81 func NewSubjectTransformWithStrict(src, dest string, strict bool) (*subjectTransform, error) {
82 // strict = true for import subject mappings that need to be reversible
83 // (meaning can only use the Wildcard function and must use all the pwcs that are present in the source)
84 // No source given is equivalent to the source being ">"
85
86 if dest == _EMPTY_ {
87 return nil, nil
88 }
89
90 if src == _EMPTY_ {
91 src = fwcs
92 }
93
94 // Both entries need to be valid subjects.
95 sv, stokens, npwcs, hasFwc := subjectInfo(src)
96 dv, dtokens, dnpwcs, dHasFwc := subjectInfo(dest)
97
98 // Make sure both are valid, match fwc if present and there are no pwcs in the dest subject.
99 if !sv || !dv || dnpwcs > 0 || hasFwc != dHasFwc {
100 return nil, ErrBadSubject
101 }
102
103 var dtokMappingFunctionTypes []int16
104 var dtokMappingFunctionTokenIndexes [][]int
105 var dtokMappingFunctionIntArgs []int32
106 var dtokMappingFunctionStringArgs []string
107
108 // If the src has partial wildcards then the dest needs to have the token place markers.
109 if npwcs > 0 || hasFwc {
110 // We need to count to make sure that the dest has token holders for the pwcs.
111 sti := make(map[int]int)
112 for i, token := range stokens {
113 if len(token) == 1 && token[0] == pwc {
114 sti[len(sti)+1] = i
115 }
116 }
117
118 nphs := 0
119 for _, token := range dtokens {
120 tranformType, transformArgWildcardIndexes, transfomArgInt, transformArgString, err := indexPlaceHolders(token)
121 if err != nil {
122 return nil, err
123 }
124
125 if strict {
126 if tranformType != NoTransform && tranformType != Wildcard {
127 return nil, &mappingDestinationErr{token, ErrMappingDestinationNotSupportedForImport}
128 }
129 }
130
131 if tranformType == NoTransform {
132 dtokMappingFunctionTypes = append(dtokMappingFunctionTypes, NoTransform)
133 dtokMappingFunctionTokenIndexes = append(dtokMappingFunctionTokenIndexes, []int{-1})
134 dtokMappingFunctionIntArgs = append(dtokMappingFunctionIntArgs, -1)
135 dtokMappingFunctionStringArgs = append(dtokMappingFunctionStringArgs, _EMPTY_)
136 } else if tranformType == Random {
137 dtokMappingFunctionTypes = append(dtokMappingFunctionTypes, Random)
138 dtokMappingFunctionTokenIndexes = append(dtokMappingFunctionTokenIndexes, []int{})
139 dtokMappingFunctionIntArgs = append(dtokMappingFunctionIntArgs, transfomArgInt)
140 dtokMappingFunctionStringArgs = append(dtokMappingFunctionStringArgs, _EMPTY_)
141 } else {
142 nphs += len(transformArgWildcardIndexes)
143 // Now build up our runtime mapping from dest to source tokens.
144 var stis []int
145 for _, wildcardIndex := range transformArgWildcardIndexes {
146 if wildcardIndex > npwcs {
147 return nil, &mappingDestinationErr{fmt.Sprintf("%s: [%d]", token, wildcardIndex), ErrMappingDestinationIndexOutOfRange}
148 }
149 stis = append(stis, sti[wildcardIndex])
150 }
151 dtokMappingFunctionTypes = append(dtokMappingFunctionTypes, tranformType)
152 dtokMappingFunctionTokenIndexes = append(dtokMappingFunctionTokenIndexes, stis)
153 dtokMappingFunctionIntArgs = append(dtokMappingFunctionIntArgs, transfomArgInt)
154 dtokMappingFunctionStringArgs = append(dtokMappingFunctionStringArgs, transformArgString)
155
156 }
157 }
158 if strict && nphs < npwcs {
159 // not all wildcards are being used in the destination
160 return nil, &mappingDestinationErr{dest, ErrMappingDestinationNotUsingAllWildcards}
161 }
162 } else {
163 // no wildcards used in the source: check that no transform functions are used in the destination
164 for _, token := range dtokens {
165 tranformType, _, transfomArgInt, _, err := indexPlaceHolders(token)
166 if err != nil {
167 return nil, err
168 }
169
170 if tranformType == NoTransform {
171 dtokMappingFunctionTypes = append(dtokMappingFunctionTypes, NoTransform)
172 dtokMappingFunctionTokenIndexes = append(dtokMappingFunctionTokenIndexes, []int{-1})
173 dtokMappingFunctionIntArgs = append(dtokMappingFunctionIntArgs, -1)
174 dtokMappingFunctionStringArgs = append(dtokMappingFunctionStringArgs, _EMPTY_)
175 } else if tranformType == Random || tranformType == Partition {
176 dtokMappingFunctionTypes = append(dtokMappingFunctionTypes, tranformType)
177 dtokMappingFunctionTokenIndexes = append(dtokMappingFunctionTokenIndexes, []int{})
178 dtokMappingFunctionIntArgs = append(dtokMappingFunctionIntArgs, transfomArgInt)
179 dtokMappingFunctionStringArgs = append(dtokMappingFunctionStringArgs, _EMPTY_)
180 } else {
181 return nil, &mappingDestinationErr{token, ErrMappingDestinationIndexOutOfRange}
182 }
183 }
184 }
185
186 return &subjectTransform{
187 src: src,
188 dest: dest,
189 dtoks: dtokens,
190 stoks: stokens,
191 dtokmftypes: dtokMappingFunctionTypes,
192 dtokmftokindexesargs: dtokMappingFunctionTokenIndexes,
193 dtokmfintargs: dtokMappingFunctionIntArgs,
194 dtokmfstringargs: dtokMappingFunctionStringArgs,
195 }, nil
196 }
197
198 func NewSubjectTransform(src, dest string) (*subjectTransform, error) {
199 return NewSubjectTransformWithStrict(src, dest, false)
200 }
201
202 func NewSubjectTransformStrict(src, dest string) (*subjectTransform, error) {
203 return NewSubjectTransformWithStrict(src, dest, true)
204 }
205
206 func getMappingFunctionArgs(functionRegEx *regexp.Regexp, token string) []string {
207 commandStrings := functionRegEx.FindStringSubmatch(token)
208 if len(commandStrings) > 1 {
209 return commaSeparatorRegEx.Split(commandStrings[1], -1)
210 }
211 return nil
212 }
213
214 // Helper for mapping functions that take a wildcard index and an integer as arguments
215 func transformIndexIntArgsHelper(token string, args []string, transformType int16) (int16, []int, int32, string, error) {
216 if len(args) < 2 {
217 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationNotEnoughArgs}
218 }
219 if len(args) > 2 {
220 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationTooManyArgs}
221 }
222 i, err := strconv.Atoi(strings.Trim(args[0], " "))
223 if err != nil {
224 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationInvalidArg}
225 }
226 mappingFunctionIntArg, err := strconv.ParseInt(strings.Trim(args[1], " "), 10, 32)
227 if err != nil {
228 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationInvalidArg}
229 }
230
231 return transformType, []int{i}, int32(mappingFunctionIntArg), _EMPTY_, nil
232 }
233
234 // Helper to ingest and index the subjectTransform destination token (e.g. $x or {{}}) in the token
235 // returns a transformation type, and three function arguments: an array of source subject token indexes,
236 // and a single number (e.g. number of partitions, or a slice size), and a string (e.g.a split delimiter)
237 func indexPlaceHolders(token string) (int16, []int, int32, string, error) {
238 length := len(token)
239 if length > 1 {
240 // old $1, $2, etc... mapping format still supported to maintain backwards compatibility
241 if token[0] == '$' { // simple non-partition mapping
242 tp, err := strconv.Atoi(token[1:])
243 if err != nil {
244 // other things rely on tokens starting with $ so not an error just leave it as is
245 return NoTransform, []int{-1}, -1, _EMPTY_, nil
246 }
247 return Wildcard, []int{tp}, -1, _EMPTY_, nil
248 }
249
250 // New 'mustache' style mapping
251 if length > 4 && token[0] == '{' && token[1] == '{' && token[length-2] == '}' && token[length-1] == '}' {
252 // wildcard(wildcard token index) (equivalent to $)
253 args := getMappingFunctionArgs(wildcardMappingFunctionRegEx, token)
254 if args != nil {
255 if len(args) == 1 && args[0] == _EMPTY_ {
256 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationNotEnoughArgs}
257 }
258 if len(args) == 1 {
259 tokenIndex, err := strconv.Atoi(strings.Trim(args[0], " "))
260 if err != nil {
261 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationInvalidArg}
262 }
263 return Wildcard, []int{tokenIndex}, -1, _EMPTY_, nil
264 } else {
265 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationTooManyArgs}
266 }
267 }
268
269 // partition(number of partitions, token1, token2, ...)
270 args = getMappingFunctionArgs(partitionMappingFunctionRegEx, token)
271 if args != nil {
272 if len(args) < 1 {
273 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationNotEnoughArgs}
274 }
275 if len(args) == 1 {
276 mappingFunctionIntArg, err := strconv.Atoi(strings.Trim(args[0], " "))
277 if err != nil || mappingFunctionIntArg > math.MaxInt32 {
278 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationInvalidArg}
279 }
280 return Partition, []int{}, int32(mappingFunctionIntArg), _EMPTY_, nil
281 }
282 if len(args) >= 2 {
283 mappingFunctionIntArg, err := strconv.Atoi(strings.Trim(args[0], " "))
284 if err != nil || mappingFunctionIntArg > math.MaxInt32 {
285 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationInvalidArg}
286 }
287 var numPositions = len(args[1:])
288 tokenIndexes := make([]int, numPositions)
289 for ti, t := range args[1:] {
290 i, err := strconv.Atoi(strings.Trim(t, " "))
291 if err != nil {
292 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationInvalidArg}
293 }
294 tokenIndexes[ti] = i
295 }
296
297 return Partition, tokenIndexes, int32(mappingFunctionIntArg), _EMPTY_, nil
298 }
299 }
300
301 // SplitFromLeft(token, position)
302 args = getMappingFunctionArgs(splitFromLeftMappingFunctionRegEx, token)
303 if args != nil {
304 return transformIndexIntArgsHelper(token, args, SplitFromLeft)
305 }
306
307 // SplitFromRight(token, position)
308 args = getMappingFunctionArgs(splitFromRightMappingFunctionRegEx, token)
309 if args != nil {
310 return transformIndexIntArgsHelper(token, args, SplitFromRight)
311 }
312
313 // SliceFromLeft(token, position)
314 args = getMappingFunctionArgs(sliceFromLeftMappingFunctionRegEx, token)
315 if args != nil {
316 return transformIndexIntArgsHelper(token, args, SliceFromLeft)
317 }
318
319 // SliceFromRight(token, position)
320 args = getMappingFunctionArgs(sliceFromRightMappingFunctionRegEx, token)
321 if args != nil {
322 return transformIndexIntArgsHelper(token, args, SliceFromRight)
323 }
324
325 // Right(token, length)
326 args = getMappingFunctionArgs(rightMappingFunctionRegEx, token)
327 if args != nil {
328 return transformIndexIntArgsHelper(token, args, Right)
329 }
330
331 // Left(token, length)
332 args = getMappingFunctionArgs(leftMappingFunctionRegEx, token)
333 if args != nil {
334 return transformIndexIntArgsHelper(token, args, Left)
335 }
336
337 // split(token, deliminator)
338 args = getMappingFunctionArgs(splitMappingFunctionRegEx, token)
339 if args != nil {
340 if len(args) < 2 {
341 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationNotEnoughArgs}
342 }
343 if len(args) > 2 {
344 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationTooManyArgs}
345 }
346 i, err := strconv.Atoi(strings.Trim(args[0], " "))
347 if err != nil {
348 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationInvalidArg}
349 }
350 if strings.Contains(args[1], " ") || strings.Contains(args[1], tsep) {
351 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token: token, err: ErrMappingDestinationInvalidArg}
352 }
353
354 return Split, []int{i}, -1, args[1], nil
355 }
356
357 // Random(max)
358 args = getMappingFunctionArgs(randomMappingFunctionRegEx, token)
359 if args != nil {
360 if len(args) != 1 {
361 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationNotEnoughArgs}
362 }
363 mappingFunctionIntArg, err := strconv.Atoi(strings.Trim(args[0], " "))
364 if err != nil || mappingFunctionIntArg > math.MaxInt32 {
365 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrMappingDestinationInvalidArg}
366 }
367 return Random, []int{}, int32(mappingFunctionIntArg), _EMPTY_, nil
368 }
369
370 return BadTransform, []int{}, -1, _EMPTY_, &mappingDestinationErr{token, ErrUnknownMappingDestinationFunction}
371 }
372 }
373 return NoTransform, []int{-1}, -1, _EMPTY_, nil
374 }
375
376 // Helper function to tokenize subjects with partial wildcards into formal transform destinations.
377 // e.g. "foo.*.*" -> "foo.$1.$2"
378 func transformTokenize(subject string) string {
379 // We need to make the appropriate markers for the wildcards etc.
380 i := 1
381 var nda []string
382 for token := range strings.SplitSeq(subject, tsep) {
383 if token == pwcs {
384 nda = append(nda, fmt.Sprintf("$%d", i))
385 i++
386 } else {
387 nda = append(nda, token)
388 }
389 }
390 return strings.Join(nda, tsep)
391 }
392
393 // Helper function to go from transform destination to a subject with partial wildcards and ordered list of placeholders
394 // E.g.:
395 //
396 // "bar" -> "bar", []
397 // "foo.$2.$1" -> "foo.*.*", ["$2","$1"]
398 // "foo.{{wildcard(2)}}.{{wildcard(1)}}" -> "foo.*.*", ["{{wildcard(2)}}","{{wildcard(1)}}"]
399 func transformUntokenize(subject string) (string, []string) {
400 var phs []string
401 var nda []string
402
403 for token := range strings.SplitSeq(subject, tsep) {
404 if args := getMappingFunctionArgs(wildcardMappingFunctionRegEx, token); (len(token) > 1 && token[0] == '$' && token[1] >= '1' && token[1] <= '9') || (len(args) == 1 && args[0] != _EMPTY_) {
405 phs = append(phs, token)
406 nda = append(nda, pwcs)
407 } else {
408 nda = append(nda, token)
409 }
410 }
411 return strings.Join(nda, tsep), phs
412 }
413
414 func tokenizeSubject(subject string) []string {
415 // Tokenize the subject.
416 tsa := [32]string{}
417 tts := tsa[:0]
418 start := 0
419 for i := 0; i < len(subject); i++ {
420 if subject[i] == btsep {
421 tts = append(tts, subject[start:i])
422 start = i + 1
423 }
424 }
425 tts = append(tts, subject[start:])
426 return tts
427 }
428
429 // Match will take a literal published subject that is associated with a client and will match and subjectTransform
430 // the subject if possible.
431 //
432 // This API is not part of the public API and not subject to SemVer protections
433 func (tr *subjectTransform) Match(subject string) (string, error) {
434 // Special case: matches any and no no-op subjectTransform. May not be legal config for some features
435 // but specific validations made at subjectTransform create time
436 if (tr.src == fwcs || tr.src == _EMPTY_) && (tr.dest == fwcs || tr.dest == _EMPTY_) {
437 return subject, nil
438 }
439
440 tts := tokenizeSubject(subject)
441
442 // TODO(jnm): optimization -> not sure this is actually needed but was there in initial code
443 if !isValidLiteralSubject(slices.Values(tts)) {
444 return _EMPTY_, ErrBadSubject
445 }
446
447 if (tr.src == _EMPTY_ || tr.src == fwcs) || isSubsetMatch(tts, tr.src) {
448 return tr.TransformTokenizedSubject(tts), nil
449 }
450 return _EMPTY_, ErrNoTransforms
451 }
452
453 // TransformSubject transforms a subject
454 //
455 // This API is not part of the public API and not subject to SemVer protection
456 func (tr *subjectTransform) TransformSubject(subject string) string {
457 return tr.TransformTokenizedSubject(tokenizeSubject(subject))
458 }
459
460 func (tr *subjectTransform) getRandomPartition(ceiling int) string {
461 // Avoid an integer divide by zero panic below.
462 if ceiling == 0 {
463 return "0"
464 }
465
466 return strconv.Itoa(int(rand.Int31()) % ceiling)
467 }
468
469 func (tr *subjectTransform) getHashPartition(key []byte, numBuckets int) string {
470 // Avoid an integer divide by zero panic below.
471 if numBuckets == 0 {
472 return "0"
473 }
474
475 h := fnv.New32a()
476 _, _ = h.Write(key)
477
478 return strconv.Itoa(int(h.Sum32() % uint32(numBuckets)))
479 }
480
481 // Do a subjectTransform on the subject to the dest subject.
482 func (tr *subjectTransform) TransformTokenizedSubject(tokens []string) string {
483 if len(tr.dtokmftypes) == 0 {
484 return tr.dest
485 }
486
487 var b strings.Builder
488
489 // We need to walk destination tokens and create the mapped subject pulling tokens or mapping functions
490 li := len(tr.dtokmftypes) - 1
491 for i, mfType := range tr.dtokmftypes {
492 if mfType == NoTransform {
493 // Break if fwc
494 if len(tr.dtoks[i]) == 1 && tr.dtoks[i][0] == fwc {
495 break
496 }
497 b.WriteString(tr.dtoks[i])
498 } else {
499 switch mfType {
500 case Partition:
501 var (
502 _buffer [64]byte
503 keyForHashing = _buffer[:0]
504 )
505 if len(tr.dtokmftokindexesargs[i]) > 0 {
506 // When token positions are specified.
507 for _, sourceToken := range tr.dtokmftokindexesargs[i] {
508 keyForHashing = append(keyForHashing, []byte(tokens[sourceToken])...)
509 }
510 } else {
511 // When using the shorthand partition(n).
512 keyForHashing = append(keyForHashing, strings.Join(tokens, ".")...)
513 }
514 b.WriteString(tr.getHashPartition(keyForHashing, int(tr.dtokmfintargs[i])))
515 case Wildcard: // simple substitution
516 switch {
517 case len(tr.dtokmftokindexesargs) < i:
518 break
519 case len(tr.dtokmftokindexesargs[i]) < 1:
520 break
521 case len(tokens) <= tr.dtokmftokindexesargs[i][0]:
522 break
523 default:
524 b.WriteString(tokens[tr.dtokmftokindexesargs[i][0]])
525 }
526 case SplitFromLeft:
527 sourceToken := tokens[tr.dtokmftokindexesargs[i][0]]
528 sourceTokenLen := len(sourceToken)
529 position := int(tr.dtokmfintargs[i])
530 if position > 0 && position < sourceTokenLen {
531 b.WriteString(sourceToken[:position])
532 b.WriteString(tsep)
533 b.WriteString(sourceToken[position:])
534 } else { // too small to split at the requested position: don't split
535 b.WriteString(sourceToken)
536 }
537 case SplitFromRight:
538 sourceToken := tokens[tr.dtokmftokindexesargs[i][0]]
539 sourceTokenLen := len(sourceToken)
540 position := int(tr.dtokmfintargs[i])
541 if position > 0 && position < sourceTokenLen {
542 b.WriteString(sourceToken[:sourceTokenLen-position])
543 b.WriteString(tsep)
544 b.WriteString(sourceToken[sourceTokenLen-position:])
545 } else { // too small to split at the requested position: don't split
546 b.WriteString(sourceToken)
547 }
548 case SliceFromLeft:
549 sourceToken := tokens[tr.dtokmftokindexesargs[i][0]]
550 sourceTokenLen := len(sourceToken)
551 sliceSize := int(tr.dtokmfintargs[i])
552 if sliceSize > 0 && sliceSize < sourceTokenLen {
553 for i := 0; i+sliceSize <= sourceTokenLen; i += sliceSize {
554 if i != 0 {
555 b.WriteString(tsep)
556 }
557 b.WriteString(sourceToken[i : i+sliceSize])
558 if i+sliceSize != sourceTokenLen && i+sliceSize+sliceSize > sourceTokenLen {
559 b.WriteString(tsep)
560 b.WriteString(sourceToken[i+sliceSize:])
561 break
562 }
563 }
564 } else { // too small to slice at the requested size: don't slice
565 b.WriteString(sourceToken)
566 }
567 case SliceFromRight:
568 sourceToken := tokens[tr.dtokmftokindexesargs[i][0]]
569 sourceTokenLen := len(sourceToken)
570 sliceSize := int(tr.dtokmfintargs[i])
571 if sliceSize > 0 && sliceSize < sourceTokenLen {
572 remainder := sourceTokenLen % sliceSize
573 if remainder > 0 {
574 b.WriteString(sourceToken[:remainder])
575 b.WriteString(tsep)
576 }
577 for i := remainder; i+sliceSize <= sourceTokenLen; i += sliceSize {
578 b.WriteString(sourceToken[i : i+sliceSize])
579 if i+sliceSize < sourceTokenLen {
580 b.WriteString(tsep)
581 }
582 }
583 } else { // too small to slice at the requested size: don't slice
584 b.WriteString(sourceToken)
585 }
586 case Split:
587 sourceToken := tokens[tr.dtokmftokindexesargs[i][0]]
588 splits := strings.Split(sourceToken, tr.dtokmfstringargs[i])
589 for j, split := range splits {
590 if split != _EMPTY_ {
591 b.WriteString(split)
592 }
593 if j < len(splits)-1 && splits[j+1] != _EMPTY_ && !(j == 0 && split == _EMPTY_) {
594 b.WriteString(tsep)
595 }
596 }
597 case Left:
598 sourceToken := tokens[tr.dtokmftokindexesargs[i][0]]
599 sourceTokenLen := len(sourceToken)
600 sliceSize := int(tr.dtokmfintargs[i])
601 if sliceSize > 0 && sliceSize < sourceTokenLen {
602 b.WriteString(sourceToken[0:sliceSize])
603 } else { // too small to slice at the requested size: don't slice
604 b.WriteString(sourceToken)
605 }
606 case Right:
607 sourceToken := tokens[tr.dtokmftokindexesargs[i][0]]
608 sourceTokenLen := len(sourceToken)
609 sliceSize := int(tr.dtokmfintargs[i])
610 if sliceSize > 0 && sliceSize < sourceTokenLen {
611 b.WriteString(sourceToken[sourceTokenLen-sliceSize : sourceTokenLen])
612 } else { // too small to slice at the requested size: don't slice
613 b.WriteString(sourceToken)
614 }
615 case Random:
616 b.WriteString(tr.getRandomPartition(int(tr.dtokmfintargs[i])))
617 }
618 }
619
620 if i < li {
621 b.WriteByte(btsep)
622 }
623 }
624
625 // We may have more source tokens available. This happens with ">".
626 if tr.dtoks[len(tr.dtoks)-1] == fwcs {
627 for sli, i := len(tokens)-1, len(tr.stoks)-1; i < len(tokens); i++ {
628 b.WriteString(tokens[i])
629 if i < sli {
630 b.WriteByte(btsep)
631 }
632 }
633 }
634 return b.String()
635 }
636
637 // Reverse a subjectTransform.
638 func (tr *subjectTransform) reverse() *subjectTransform {
639 if len(tr.dtokmftokindexesargs) == 0 {
640 rtr, _ := NewSubjectTransformStrict(tr.dest, tr.src)
641 return rtr
642 }
643 // If we are here we need to dynamically get the correct reverse
644 // of this subjectTransform.
645 nsrc, phs := transformUntokenize(tr.dest)
646 var nda []string
647 for _, token := range tr.stoks {
648 if token == pwcs {
649 if len(phs) == 0 {
650 // TODO(dlc) - Should not happen
651 return nil
652 }
653 nda = append(nda, phs[0])
654 phs = phs[1:]
655 } else {
656 nda = append(nda, token)
657 }
658 }
659 ndest := strings.Join(nda, tsep)
660 rtr, _ := NewSubjectTransformStrict(nsrc, ndest)
661 return rtr
662 }
663
664 // Will share relevant info regarding the subject.
665 // Returns valid, tokens, num pwcs, has fwc.
666 func subjectInfo(subject string) (bool, []string, int, bool) {
667 if subject == "" {
668 return false, nil, 0, false
669 }
670 npwcs := 0
671 sfwc := false
672 tokens := strings.Split(subject, tsep)
673 for _, t := range tokens {
674 if len(t) == 0 || sfwc {
675 return false, nil, 0, false
676 }
677 if len(t) > 1 {
678 continue
679 }
680 switch t[0] {
681 case fwc:
682 sfwc = true
683 case pwc:
684 npwcs++
685 }
686 }
687 return true, tokens, npwcs, sfwc
688 }