File: WebsocketMaskService.java

package info (click to toggle)
ruby-websocket-driver 0.6.3-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 188 kB
  • sloc: ruby: 1,203; java: 44; ansic: 33; makefile: 3
file content (55 lines) | stat: -rw-r--r-- 1,673 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.jcoglan.websocket;

import java.lang.Long;
import java.io.IOException;

import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.BasicLibraryService;

public class WebsocketMaskService implements BasicLibraryService {
  private Ruby runtime;

  public boolean basicLoad(Ruby runtime) throws IOException {
    this.runtime = runtime;
    RubyModule websocket = runtime.defineModule("WebSocket");

    RubyClass webSocketMask = websocket.defineClassUnder("Mask", runtime.getObject(), new ObjectAllocator() {
      public IRubyObject allocate(Ruby runtime, RubyClass rubyClass) {
        return new WebsocketMask(runtime, rubyClass);
      }
    });

    webSocketMask.defineAnnotatedMethods(WebsocketMask.class);
    return true;
  }

  public class WebsocketMask extends RubyObject {
    public WebsocketMask(final Ruby runtime, RubyClass rubyClass) {
      super(runtime, rubyClass);
    }

    @JRubyMethod
    public IRubyObject mask(ThreadContext context, IRubyObject payload, IRubyObject mask) {
      if (mask.isNil()) return payload;

      byte[] payload_a = ((RubyString)payload).getBytes();
      byte[] mask_a    = ((RubyString)mask).getBytes();
      int i, n         = payload_a.length;

      if (n == 0) return payload;

      for (i = 0; i < n; i++) {
        payload_a[i] ^= mask_a[i % 4];
      }
      return RubyString.newStringNoCopy(runtime, payload_a);
    }
  }
}